【模板】矩阵快速幂
洛谷 3390
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #define rg register 5 #define N 110 6 #define LL long long 7 using namespace std; 8 const LL Mod=1e9+7; 9 LL n,m,tmp[N][N]; 10 struct Mat{LL m[N][N];}a,t,ans; 11 inline LL read(){ 12 LL k=0,f=1; char c=getchar(); 13 while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar(); 14 while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar(); 15 return k*f; 16 } 17 inline void mul(Mat &a,Mat b){ 18 memset(tmp,0,sizeof(tmp)); 19 for(rg int i=1;i<=n;i++) 20 for(rg int j=1;j<=n;j++) 21 for(rg int k=1;k<=n;k++) 22 tmp[i][j]+=a.m[i][k]*b.m[k][j],tmp[i][j]%=Mod; 23 for(rg int i=1;i<=n;i++) 24 for(rg int j=1;j<=n;j++) 25 a.m[i][j]=tmp[i][j]; 26 } 27 int main(){ 28 n=read(); m=read(); 29 for(rg int i=1;i<=n;i++) 30 for(rg int j=1;j<=n;j++) t.m[i][j]=read(); 31 for(rg int i=1;i<=n;i++) ans.m[i][i]=1; 32 while(m){ 33 if(m&1) mul(ans,t); 34 mul(t,t); 35 m>>=1; 36 } 37 for(rg int i=1;i<=n;i++){ 38 for(rg int j=1;j<=n;j++) printf("%lld ",ans.m[i][j]); 39 puts(""); 40 } 41 return 0; 42 }