Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.
Output the elements of S modulo m in the same way as A is given.
2 2 4 0 1 1 1
1 2 2 3
题解:
Sk=A+A^2+A^3+...+A^k;
S(k-1)=A+A^2+A^3+...+A^(k-1);
则:Sk=A*S(k-1)+A;
结合矩阵快速幂求解
#include"stdio.h" #include"string.h" #include"cstdio" #include"algorithm" using namespace std; typedef long long ll; int n,mod; struct Mat { int m[65][65]; }; Mat multy(Mat X,Mat Y) { Mat Z; memset(Z.m,0,sizeof(Z.m)); for(int i=0;i<2*n;i++) { for(int j=0;j<2*n;j++) { if(X.m[i][j]) { for(int k=0;k<2*n;k++) { Z.m[i][k]+=((X.m[i][j]*Y.m[j][k])%mod); Z.m[i][k]%=mod; } } } } return Z; } Mat pow_m(Mat A,int k) { Mat B; memset(B.m,0,sizeof(B.m)); for(int i=0;i<2*n;i++) B.m[i][i]=1; while(k) { if(k&1) B=multy(B,A); A=multy(A,A); k>>=1; } return B; } int main() { int k; while(scanf("%d%d%d",&n,&k,&mod)!=EOF) { Mat A,B; int i; memset(A.m,0,sizeof(A.m)); memset(B.m,0,sizeof(B.m)); for(i=0;i<n;i++) { for(int j=0;j<n;j++) scanf("%d",&A.m[i][j]); } for(;i<2*n;i++) A.m[i-n][i]=1; for(i=0;i<n;i++) { for(int j=0;j<n;j++) B.m[i][j]=A.m[i][j]; } for(;i<2*n;i++) { for(int j=0;j<n;j++) B.m[i][j]=A.m[i-n][j]; } for(i=n;i<2*n;i++) B.m[i][i]=1; Mat Q=pow_m(B,k-1); Mat R=multy(A,Q); for(i=0;i<n;i++) { for(int j=0;j<n;j++) printf("%d%c",R.m[i][j],j==n-1?'\n':' '); } } }