#include <cstdio> #include <algorithm> using namespace std; int N, M; int PP; constexpr int MAXX = 4096; int H[2][MAXX][MAXX]; int how(int x, int d, int depthToGo) { long result = 0; for (int dd = 1; dd <= N; dd++) { for (int xx = max(0, x-dd+1); xx <= min(N-dd, x+d-1); xx++) { if (depthToGo == 1) { result++; if (result >= PP) result-=PP; } else { result += how(xx, dd, depthToGo-1); result %= PP; } } } return result; } void hhh() { for (int d = 1; d <= N; d++) for (int x = 0; x+d <= N; x++) H[0][d][x] = 1; for (int depth = 1; depth < M; depth++) { int curr=depth&1; int prev=!curr; for (int d = 1; d <= N; d++) { for (int x = 0; x+d <= N; x++) { H[curr][d][x] = 0; for (int dd = 1; dd <= N; dd++) { for (int xx = max(0, x-dd+1); xx <= min(N-dd, x+d-1); xx++) { H[curr][d][x] += H[prev][dd][xx]; H[curr][d][x] %= PP; } } } } } int curr = (M-1)&1; int sum = 0; for (int d = 1; d <= N; d++) for (int x = 0; x+d <= N; x++) sum += H[curr][d][x], sum %= PP; printf("%d\n", sum); } int main() { scanf("%d%d%d", &M, &N, &PP); if (N<=MAXX-1) hhh(); else printf("%d\n", how(0, N, M)); return 0; }
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 59 60 61 62 63 | #include <cstdio> #include <algorithm> using namespace std; int N, M; int PP; constexpr int MAXX = 4096; int H[2][MAXX][MAXX]; int how(int x, int d, int depthToGo) { long result = 0; for (int dd = 1; dd <= N; dd++) { for (int xx = max(0, x-dd+1); xx <= min(N-dd, x+d-1); xx++) { if (depthToGo == 1) { result++; if (result >= PP) result-=PP; } else { result += how(xx, dd, depthToGo-1); result %= PP; } } } return result; } void hhh() { for (int d = 1; d <= N; d++) for (int x = 0; x+d <= N; x++) H[0][d][x] = 1; for (int depth = 1; depth < M; depth++) { int curr=depth&1; int prev=!curr; for (int d = 1; d <= N; d++) { for (int x = 0; x+d <= N; x++) { H[curr][d][x] = 0; for (int dd = 1; dd <= N; dd++) { for (int xx = max(0, x-dd+1); xx <= min(N-dd, x+d-1); xx++) { H[curr][d][x] += H[prev][dd][xx]; H[curr][d][x] %= PP; } } } } } int curr = (M-1)&1; int sum = 0; for (int d = 1; d <= N; d++) for (int x = 0; x+d <= N; x++) sum += H[curr][d][x], sum %= PP; printf("%d\n", sum); } int main() { scanf("%d%d%d", &M, &N, &PP); if (N<=MAXX-1) hhh(); else printf("%d\n", how(0, N, M)); return 0; } |