#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int n, m;
ll p;
struct fence{
ll dp, c;
};
ll counter;
ll res;
int main()
{
scanf("%d%d%lld", &n, &m, &p);
const int r = m;
auto tab = new fence [n*m];
for(int i = 0; i < m; i++)
{
tab[i].dp = i+1;
}
counter = -1;
for(int i = m-1; i >=0 ; i--)
{
tab[i].c = tab[i].dp;
if(i < m-1)
{
tab[i].c += tab[i+1].c;
tab[i].c %=p;
}
if(counter >= 0)
{
tab[i].c-=tab[counter].dp;
tab[i].c +=p;
tab[i].c %=p;
}
counter++;
}
for(int i = 1; i<n; i++)
{
counter = 0;
for(int j = 0; j<m; j++)
{
tab[i*m+j].dp = tab[(i-1)*m+j].c*(j+1);
tab[i*m+j].dp %= p;
tab[i*m+j].dp+=counter;
tab[i*m+j].dp %= p;
counter+= tab[(i-1)*m+j].dp * (j+1);
counter %= p;
}
counter = -1;
for(int j = m-1; j>=0; j--)
{
tab[i*m + j].c = tab[i*m + j].dp;
if(j < m-1)
{
tab[i*m + j].c += tab[i*m + j + 1].c;
tab[i*m + j].c %= p;
}
if(counter >= 0)
{
tab[i*m + j].c-=tab[i*m + counter].dp;
tab[i*m + j].c += p;
tab[i*m + j].c %= p;
}
counter++;
}
}
for(int j = 0; j<m; j++)
{
res+=tab[(n-1)*m+j].dp;
res%=p;
}
printf("%lld", res);
}
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #include <bits/stdc++.h> typedef long long ll; using namespace std; int n, m; ll p; struct fence{ ll dp, c; }; ll counter; ll res; int main() { scanf("%d%d%lld", &n, &m, &p); const int r = m; auto tab = new fence [n*m]; for(int i = 0; i < m; i++) { tab[i].dp = i+1; } counter = -1; for(int i = m-1; i >=0 ; i--) { tab[i].c = tab[i].dp; if(i < m-1) { tab[i].c += tab[i+1].c; tab[i].c %=p; } if(counter >= 0) { tab[i].c-=tab[counter].dp; tab[i].c +=p; tab[i].c %=p; } counter++; } for(int i = 1; i<n; i++) { counter = 0; for(int j = 0; j<m; j++) { tab[i*m+j].dp = tab[(i-1)*m+j].c*(j+1); tab[i*m+j].dp %= p; tab[i*m+j].dp+=counter; tab[i*m+j].dp %= p; counter+= tab[(i-1)*m+j].dp * (j+1); counter %= p; } counter = -1; for(int j = m-1; j>=0; j--) { tab[i*m + j].c = tab[i*m + j].dp; if(j < m-1) { tab[i*m + j].c += tab[i*m + j + 1].c; tab[i*m + j].c %= p; } if(counter >= 0) { tab[i*m + j].c-=tab[i*m + counter].dp; tab[i*m + j].c += p; tab[i*m + j].c %= p; } counter++; } } for(int j = 0; j<m; j++) { res+=tab[(n-1)*m+j].dp; res%=p; } printf("%lld", res); } |
English