设S[k] = A + A^2 +````+A^k.
设矩阵T =
A[1] | 0 |
E | E |
这里的E为n*n单位方阵,0为n*n方阵
令A[k] = A ^ k
矩阵B[k] =
A[k+1] |
S[k] |
则有递推式B[K] = T*B[k-1],即有B[k] = T^k*B[0],令S[0] 为n*n的0矩阵。
矩阵快速幂求出即可·····
还可以使用两次分治的方法····自行百度····
贴代码:
#include<cstdio>
#include<cstring>
int n,k,p,d;//d = 2*n
struct matrix
{
int m[][];
} A;
matrix mul(int a[][],int b[][])
{
matrix ans;
memset(ans.m,,sizeof(ans.m));
for(int i=; i<=d; ++i)
for(int j=; j<=d; ++j)
for(int k=; k<=d; ++k)
ans.m[i][j] = (ans.m[i][j] + a[i][k]*b[k][j]%p)%p;
return ans;
}
matrix qPow()
{
matrix ans;
memset(ans.m,,sizeof(ans.m));
for(int i=; i<=d; ++i)
ans.m[i][i] = ;
while(k)
{
if(k&) ans = mul(ans.m,A.m);
A = mul(A.m,A.m);
k >>= ;
}
return ans;
}
int main()
{
// freopen("in.txt","r",stdin);
while(~scanf("%d%d%d",&n,&k,&p))
{
memset(A.m,,sizeof(A.m));
int t[][];
for(int i=; i<=n; ++i)
{
for(int j=; j<=n; ++j)
{
scanf("%d",&A.m[i][j]);
t[i][j] = A.m[i][j];
}
}
for(int i=n+; i<=*n; ++i)
A.m[i][i-n] = ,A.m[i][i] = ;
d = n<<;
matrix ans = qPow();
for(int i=n+; i<=d; ++i)
{
for(int j=; j<=n; ++j)
{
int res =;
for(int k=; k<=n; ++k)
res = (res + ans.m[i][k]*t[k][j]%p)%p;
if(j != ) printf(" ");
printf("%d",res);
}
puts("");
}
}
return ;
}