Description
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
Input
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
Output the elements of S modulo m in the same way as A is given.
Sample Input
2 2 4 0 1 1 1
Sample Output
1 2 2 3
思路:令S=I+A+A^2+...+A^N-1;
构造矩阵[S,A^N]*[1,1]
[I, I ] [1,A]
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> typedef long long int LL; using namespace std; int n,k,mod; struct Matrix { int a[2*30][2*30]; Matrix(){memset(a,0,sizeof(a));} Matrix operator* (const Matrix &p) { Matrix res; for(int i=0;i<2*n;i++) { for(int j=0;j<2*n;j++) { for(int k=0;k<2*n;k++) { res.a[i][j]+=(a[i][k]*p.a[k][j]%mod); } res.a[i][j]%=mod; } } return res; } }ans,base; Matrix quick_pow(Matrix base,int k) { Matrix res; for(int i=0;i<2*n;i++) { res.a[i][i]=1; } while(k) { if(k&1) res=res*base; base=base*base; k>>=1; } return res; } void init_Matrix() { for(int i=0;i<2*n;i++) { ans.a[i][i]=1; } for(int i=0;i<n;i++) { base.a[n+i][i]=1; base.a[n+i][n+i]=1; } } int main() { while(~scanf("%d%d%d",&n,&k,&mod)) { init_Matrix(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { scanf("%d",&base.a[i][j]); } } ans=ans*quick_pow(base,k+1); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { int tmp=ans.a[n+i][j]%mod; if(i==j) tmp=(tmp+mod-1)%mod; printf("%d%c",tmp,j==n-1?'\n':' '); } } } return 0; }