1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

#define f first
#define s second

const int MAXN = 1e7 + 13;

long long dp[2][MAXN];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    long long mod;
    cin >> n >> m >> mod;
    for (int i = 1; i <= m; i++)
        dp[1][i] = i;
    int pop = 0, akt = 1;
    long long pref, sum, rsum, suf, J;
    for (int i = 2; i <= n; i++) {
        pop = 1 - pop;
        akt = 1 - akt;
        pref = sum = rsum = J = 0;
        for (int j = 1; j <= m; j++) {
            J++;
            rsum += dp[pop][m - j + 1];
            if (rsum >= mod)
                rsum -= mod;
            suf = (J * rsum) % mod;
            dp[akt][j] = (suf - pref + mod) % mod;
            sum += dp[pop][j];
            if (sum >= mod)
                sum -= mod;
            pref += sum;
            if (pref >= mod)
                pref -= mod;
        }
    }
    long long ans = 0;
    for (int i = 1; i <= m; i++)
        ans += dp[n % 2][i];
    cout << ans % mod;
    return 0;
}