Fork me on GitHub

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

 




#include <iostream> #include <cstdio> #include <cstring> using namespace std; int m,n,K; int a[30][30]; class Matrix { public: int num[4*30][4*30]; Matrix() { memset(num,0,sizeof(num)); } void print() { for(int i=0;i<n;++i) { printf("%d",num[i][0]); for(int j=1;j<n;++j) printf(" %d",num[i][j]); printf("\n"); } printf("\n"); } friend Matrix& operator *(Matrix max1,Matrix max2); }; Matrix& operator *(Matrix max1,Matrix max2) { Matrix tmp; for(int i=0;i<2*n;++i) for(int j=0;j<2*n;++j) { for(int k=0;k<2*n;++k) tmp.num[i][j]+=(max1.num[i][k]*max2.num[k][j])%m; tmp.num[i][j]%=m; } return tmp; } int main() { scanf("%d %d %d",&n,&K,&m); for(int i=0;i<n;++i) for(int j=0;j<n;++j) scanf("%d",&a[i][j]); Matrix b,c; for(i=0;i<n;++i) for(int j=0;j<n;++j) c.num[i+n][j+n]=b.num[i][j+n]=a[i][j]; for(int k=0;k<2;++k) for(int i=0;i<n;++i) c.num[i+k*n][i]=1; while(K) { if(K&1) b=b*c; K>>=1; c=c*c; } b.print(); return 0; }

 

posted on 2013-01-14 20:58  huashiyiqike  阅读(164)  评论(0编辑  收藏  举报