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
#include <cstdio>
#include <vector>

int main() {
    int N,M;
    long long int P;
    scanf("%d %d %lld", &N, &M, &P);

    std::vector<long long int> psum, csum, psumsum, csumsum;
    std::vector<std::vector<long long int> > dp;
    dp.resize(N+1);
    dp[0].resize(M+1);
    psum.resize(M+1);
    psumsum.resize(M+1);
    csum.resize(M+1);
    csumsum.resize(M+1);
    psum[M] = 1;
    psumsum[M] = 1;

    for (int i=1; i<=N; ++i) {
        dp[i].resize(M+1);
        for (int j=1; j<=M; ++j) {
            dp[i][j] = (j*psum[M] + j*P - j*psum[M-j]) % P;
            dp[i][j] = (dp[i][j] + P - psumsum[j-1]) % P;
            csum[j] = (csum[j-1] + dp[i][j]) % P;
            csumsum[j] = (csum[j] + csumsum[j-1]) %P;
        }

        std::swap(psum, csum);
        std::swap(psumsum, csumsum);
    }

    printf("%lld\n",psum[M]);
    return 0;
}