- BC20260025's blog
矩阵快速幂 模板
- 2024-6-2 21:06:35 @
# include<iostream>
# include<cstring>
using namespace std;
const int N=103,mod=1e9+7;
int n;
long long k;
struct jz{
long long a[N][N];
jz(){
memset(a,0,sizeof(a));
}
void init(){
for(int i=1;i<=n;++i)
a[i][i]=1;
}
void in(){
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
cin>>a[i][j];
}
void out(){
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
}A;
jz mul(jz x,jz y){
jz z;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
for(int l=1;l<=n;++l)
z.a[i][j]=(z.a[i][j]+(x.a[i][l]%mod)*(y.a[l][j]%mod)%mod)%mod;
return z;
}
jz qpow(jz x,long long k){
jz ans;
ans.init();
while(k){
if(k&1) ans=mul(ans,x);
x=mul(x,x);
k>>=1;
}
return ans;
}
int main(){
cin>>n>>k;
A.in();
qpow(A,k).out();
return 0;
}
矩阵快速幂求斐波那契数列第 项:
# include<iostream>
# include<cstring>
using namespace std;
const int mod=1e9+7;
long long n;
struct jz{
long long a[3][3];
jz(){
memset(a,0,sizeof(a));
}
void init(){
for(int i=1;i<=2;++i)
a[i][i]=1;
}
}A,B;
jz mul(jz x,jz y){
jz z;
for(int i=1;i<=2;++i)
for(int j=1;j<=2;++j)
for(int l=1;l<=2;++l)
z.a[i][j]=(z.a[i][j]+(x.a[i][l]%mod)*(y.a[l][j]%mod)%mod)%mod;
return z;
}
jz qpow(jz x,long long k){
jz ans;
ans.init();
while(k){
if(k&1) ans=mul(ans,x);
x=mul(x,x);
k>>=1;
}
return ans;
}
int main(){
cin>>n;
if(n==1){
cout<<1;
return 0;
}
A.a[1][1]=A.a[1][2]=A.a[2][1]=1;
B=qpow(A,n-2);
cout<<(B.a[1][1]+B.a[1][2])%mod;
return 0;
}