poj 3233
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 <cstdio> #include <iostream> #include <cstring> using namespace std; const int NN=32; typedef struct node{ int matrix[NN][NN]; }Matrix; Matrix a,sa,unit; int n,m,k; Matrix mtAdd(Matrix a,Matrix b) //矩阵加法(%m) { Matrix c; for (int i=0; i<n; i++) for (int j=0; j<n; j++) { c.matrix[i][j]=a.matrix[i][j]+b.matrix[i][j]; c.matrix[i][j]%=m; } return c; } Matrix mtMul(Matrix a,Matrix b) //矩阵乘法(%m) { Matrix c; for (int i=0; i<n; i++) for (int j=0; j<n; j++) { c.matrix[i][j]=0; for (k=0; k<n; k++) c.matrix[i][j]+=a.matrix[i][k]*b.matrix[k][j]; c.matrix[i][j]%=m; } return c; } Matrix mtPow(Matrix p,int exp) //矩阵快速幂 { Matrix q; q=unit; while (exp!=1) { if (exp&1) { exp--; q=mtMul(p,q); } else { exp>>=1; p=mtMul(p,p); } } return mtMul(p,q); } Matrix MatrixSum(int k) { if (k==1) return a; Matrix tmp,tnow; tmp=MatrixSum(k/2); if (k&1) //k为奇数时sum(k)=(1+A^(k/2+1))*sum(k/2)+A^(k/2+1); { tnow=mtPow(a, k/2+1); tmp=mtAdd(tmp,mtMul(tmp,tnow)); tmp=mtAdd(tnow,tmp); } else //k为偶数时sum(k)=(1+A^(k/2))*sum(k/2) { tnow=mtPow(a, k/2); tmp=mtAdd(tmp,mtMul(tmp,tnow)); } 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.matrix[i][j]); a.matrix[i][j]%=m; unit.matrix[i][j]=(i==j); } sa=MatrixSum(k); for (int i=0; i<n; i++) { for (int j=0; j<n; j++) printf("%d ",sa.matrix[i][j]); printf("\n"); } return 0; }