Olympiad in Informatics

U63113: Invasion - a.k.a. “XG's Math Problem”

Background

As everyone knows, XG_Zepto is a god from FZOI. He thought the current contests were too easy, so he used his Minesweeper time to set a math problem for kal0rona. kal0rona is way too weak to understand the problem or solve it, so now he's turning to you for help.

Approach

A really nice counting DP, set by our godlike group leader XG_Zepto. First, let \(f[i][j]\) be the number of valid permutations of length \(i\) with \(j\) reloads. Then, consider enumerating, for the \(i\)-th number, the position \(k\) where it appears. The numbers after position \(k\) make no special contribution (the contribution is \((i-k)!\)), while for the numbers before it, we can enumerate the previous segment to transition: there are \({k-1}\choose{i-1}\) ways to choose the numbers and \(f[i-1][j-1\) permutations, and we just multiply them together, that is:

\[ F[i][j] = \sum_{k = 1}^{i}f[k-1][j-1]* {{k-1} \choose {i-1}} *(i-1)! \]

This can be simplified and optimized with prefix sums:

\[ F[i][j] = (i-1)!\sum_{k=1}^{i}\frac{f[k-1][j-1]}{(k-1)!} \]

Code

// U63113.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 5050, mod = 998244353;
ll f[MAX_N], prefix[MAX_N], level[MAX_N], inv[MAX_N], n, m;
ll quick_pow(ll bas, ll tim)
{
    ll ans = 1;
    while (tim)
    {
        if (tim & 1)
            ans = ans * bas % mod;
        bas = bas * bas % mod;
        tim >>= 1;
    }
    return ans;
}
int main()
{
    scanf("%lld%lld", &n, &m);
    level[0] = 1, inv[0] = 1;
    for (int i = 1; i <= n; i++)
        level[i] = level[i - 1] * i % mod;
    inv[n] = quick_pow(level[n], mod - 2);
    for (int i = n; i >= 1; i--)
        inv[i - 1] = inv[i] * i % mod;
    for (int i = 0; i <= n; i++)
        prefix[i] = 1;
    for (int j = 1; j <= m; j++)
    {
        for (int i = j; i <= n; i++)
            f[i] = prefix[i - 1] * level[i - 1] % mod;
        for (int i = j; i <= n; i++)
            prefix[i] = f[i] * inv[i] % mod;
        for (int i = j + 1; i <= n; i++)
            prefix[i] = (prefix[i] + prefix[i - 1]) % mod;
    }
    printf("%lld", f[n]);
    return 0;
}