标签:
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
一道比较有意思的水题,水一水更健康!
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 const int maxn=50; 6 int mod,n,K; 7 struct Matrix{ 8 int mat[maxn][maxn]; 9 Matrix(){ 10 memset(mat,0,sizeof(mat)); 11 } 12 13 Matrix operator +(Matrix a){ 14 Matrix r; 15 for(int i=1;i<=n;i++) 16 for(int j=1;j<=n;j++) 17 (r.mat[i][j]=(mat[i][j]+a.mat[i][j])%mod)%=mod; 18 return r; 19 } 20 21 Matrix operator *(Matrix a){ 22 Matrix r; 23 for(int i=1,s;i<=n;i++) 24 for(int k=1;k<=n;k++){ 25 s=mat[i][k]; 26 for(int j=1;j<=n;j++) 27 (r.mat[i][j]+=(s*a.mat[k][j])%mod)%=mod; 28 } 29 return r; 30 } 31 32 Matrix operator ^(int k){ 33 Matrix r,x; 34 for(int i=1;i<=n;i++) 35 r.mat[i][i]=1; 36 for(int i=1;i<=n;i++) 37 for(int j=1;j<=n;j++) 38 x.mat[i][j]=mat[i][j]; 39 while(k){ 40 if(k&1) 41 r=r*x; 42 k>>=1; 43 x=x*x; 44 } 45 return r; 46 } 47 }A,B,ans; 48 Matrix Solve(int k){ 49 if(k==1)return A; 50 if(k%2)return A+A*Solve(k-1); 51 else return ((A^(k/2))+B)*Solve(k/2); 52 } 53 int main(){ 54 #ifndef ONLINE_JUDGE 55 //freopen("","r",stdin); 56 //freopen("","w",stdout); 57 #endif 58 scanf("%d%d%d",&n,&K,&mod); 59 for(int i=1;i<=n;i++) 60 for(int j=1;j<=n;j++) 61 scanf("%d",&A.mat[i][j]); 62 63 for(int i=1;i<=n;i++) 64 B.mat[i][i]=1; 65 66 ans=Solve(K); 67 68 for(int i=1;i<=n;i++){ 69 for(int j=1;j<=n;j++) 70 printf("%d ",ans.mat[i][j]); 71 printf("\n"); 72 } 73 return 0; 74 }
线性代数(矩阵乘法):POJ 3233 Matrix Power Series
标签:
原文地址:http://www.cnblogs.com/TenderRun/p/5568226.html