P3390 【模板】矩陣快速冪
阿新 • • 發佈:2021-12-14
原題傳送門
題目大意:給定\(n\times n\)的矩陣\(A\),求\(A^k\),對矩陣每個元素模\(10^9+7\)
資料範圍:\(n\le 100,k\le 10^{12},|A_{i,j}|\le 1000\)
矩陣乘法+快速冪
PS: 記得開\(longlong\)!!!
Code:
#include <bits/stdc++.h> using namespace std; const int N=1e2+10,mod=1e9+7; typedef long long ll; struct Mat{ ll mat[N][N]; }; Mat mul(Mat a,Mat b,ll n){ Mat c; memset(c.mat,0,sizeof(c.mat)); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ c.mat[i][j]+=a.mat[i][k]*b.mat[k][j]; c.mat[i][j]%=mod; } } } return c; } Mat mat_power(Mat c,ll n,ll k){ Mat ans; for(int i=0;i<n;i++) ans.mat[i][i]=1; for(;k;k>>=1){ if(k&1) ans=mul(ans,c,n); c=mul(c,c,n); } return ans; } int main(){ ll n,k; cin>>n>>k; Mat c,ans; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>c.mat[i][j]; } } ans=mat_power(c,n,k); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<ans.mat[i][j]<<" "; } cout<<endl; } return 0; }