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
题解:
| A+A2+A3+……Ak | |A A| (k-1)次方 | A | | | = | | | | | E | |0 E| | E |代码:
#include <iostream> #include <cstdio> #include <cstring> using namespace std; struct mat { int t[65][65]; void set() { memset(t,0,sizeof(t)); } } a,b; mat multiple(mat a,mat b,int n,int p) { int i,j,k; mat temp; temp.set(); for(i=0; i<n; i++) for(j=0; j<n; j++) { if(a.t[i][j]>0) for(k=0; k<n; k++) temp.t[i][k]=(temp.t[i][k]+a.t[i][j]*b.t[j][k])%p; } return temp; } mat quick_mod(mat b,int n,int m,int p) { mat t; t.set(); for(int i=0;i<n;i++) t.t[i][i]=1; while(m) { if(m&1) { t=multiple(t,b,n,p); } m>>=1; b=multiple(b,b,n,p); } return t; } void init(int n,int m,int p) { a.set(); b.set(); for(int i=0;i<n;i++) for(int j=0;j<n;j++) { scanf("%d",&b.t[i][j]); b.t[i][j+n]=b.t[i][j]; a.t[i][j]=b.t[i][j]; } for(int i=n;i<2*n;i++) for(int j=n;j<2*n;j++) if(i==j) b.t[i][j]=1; for(int i=n;i<2*n;i++) for(int j=0;j<n;j++) if(j+n==i) a.t[i][j]=1; b=quick_mod(b,2*n,m-1,p); mat temp; temp.set(); for(int i=0; i<n; i++) for(int j=0; j<n; j++) { for(int k=0; k<2*n; k++) temp.t[i][j]=(temp.t[i][j]+b.t[i][k]*a.t[k][j])%p; } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) printf("%d ",temp.t[i][j]); puts(""); } } int main() { int n,m,p; while(cin>>n>>m>>p) { init(n,m,p); } return 0; }
Linux平台下裸设备的绑定:,布布扣,bubuko.com
原文:http://blog.csdn.net/panfelix/article/details/26480509