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
50
51
52
53
54
55
56
57
58
#include<bits/stdc++.h>
using namespace std;
using lld = long long;

const int MAXN = 1e7;

lld mod;
lld dp[2][MAXN];

int main(void){
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);

	int n,m;
	cin >> n >> m >> mod;

	for(int h=1;h<=m;h++)
		dp[0][h] = m-h+1;

	for(int i=1;i<n;i++){
		int x = (i&1);
		int y = 1-x;

		lld sum = 0;
		for(int h=1;h<=m;h++)
			sum += dp[y][h];
		sum %= mod;

		lld a = 0;
		lld da = 0;
		lld b = 0;

		for(int h=1;h<=m;h++)
			b += dp[y][h];
		b %= mod;

		for(int h=m;h>=1;h--){
			if(h < m)
				da = (da + dp[y][h+1]) % mod;
			a = (a + da) % mod;	

			b = (b + mod-dp[y][m-h+1]) % mod;

			dp[x][h] = 0;
			dp[x][h] += a;
			dp[x][h] += ((lld) (m-h+1) * b) % mod;
			dp[x][h] = ((lld) (m-h+1) * sum + mod-dp[x][h]) % mod;
		}
	}

	lld res = 0;
	for(int k=1;k<=m;k++)
		res += dp[1-(n&1)][k];

	cout << res%mod << "\n";

	return 0;
}