Matrix Power Series
Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions: 16711 | Accepted: 7126 |
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
Source
POJ Monthly--2007.06.03, Huang, Jinsong
/*
两次二分,矩阵快速幂一次,递归一次二分
如果k为奇数
f[k]=f[k-1]+A^k;
偶数
f[k]=f[k/2]+A^(2/k)*f[k/2]
例如:k=6 S=A+A^2+A^3+A^4+A^5+A^6
S=(A+A^2+A^3)+A^3(A+A^2+A^3)
加油!!!
Time:2015-04-08 17:11
*/
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int mod;
struct Matrix{
int mat[33][33];
int n;
void Init(int _n){
n=_n;
memset(mat,0,sizeof(mat));
}
Matrix operator*(const Matrix &b) const{
Matrix ret;
ret.Init(n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
ret.mat[i][j]+=mat[i][k]*b.mat[k][j];
ret.mat[i][j]%=mod;
}
}
}
return ret;
}
Matrix operator+(const Matrix &b) const{
Matrix ret;
ret.Init(n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
ret.mat[i][j]=mat[i][j]+b.mat[i][j];
ret.mat[i][j]%=mod;
}
}
return ret;
}
};
Matrix pow_mat(Matrix a,int k){
Matrix ret;
ret.Init(a.n);
for(int i=0;i<ret.n;i++)ret.mat[i][i]=1;
while(k>0){
if(k&1)ret=ret*a;
a=a*a;
k>>=1;
}
return ret;
}
Matrix a;
int n;
Matrix matSum(int k){
if(k==1) return a;
if(k&1){
return pow_mat(a,k)+matSum(k-1);
}else{
Matrix ret=matSum(k/2);
return ret+pow_mat(a,k/2)*ret;
}
}
int main(){
int k,m;
while(scanf("%d%d%d",&n,&k,&m)!=EOF){
mod=m;a.Init(n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&a.mat[i][j]);
}
}
Matrix ans=matSum(k);
for(int i=0;i<n;i++){
for(int j=0;j<n-1;j++){
printf("%d ",ans.mat[i][j]);
}printf("%d\n",ans.mat[i][n-1]);
}
}
return 0;
}