G04 矩阵加速 P1962 斐波那契数列
视频链接:G04 矩阵加速 P1962 斐波那契数列_哔哩哔哩_bilibili



// O(2^3*logn) #include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int mod=1000000007; struct mat{ LL c[2][2]; mat(){memset(c,0,sizeof c);} }F,A; //F:数列矩阵 A:转移矩阵 mat operator*(const mat &a,const mat &b){ mat t; for(int i=0; i<2; ++i) for(int j=0; j<2; ++j) for(int k=0; k<2; ++k) t.c[i][j]=(t.c[i][j]+a.c[i][k]*b.c[k][j])%mod; return t; } void qpow(LL n){ F.c[0][0]=F.c[0][1]=1; A.c[0][0]=A.c[0][1]=A.c[1][0]=1; while(n){ if(n&1) F=F*A; A=A*A; n>>=1; } } int main(){ LL n; cin>>n; if(n<=2){puts("1"); return 0;} qpow(n-2); cout<<F.c[0][0]; }
// O(2^3*logn) #include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int mod=1000000007; struct mat{ LL c[2][2]; mat(){memset(c,0,sizeof c);} mat operator*(const mat &x){ mat t; for(int i=0; i<2; ++i) for(int j=0; j<2; ++j) for(int k=0; k<2; ++k) t.c[i][j]=(t.c[i][j]+c[i][k]*x.c[k][j])%mod; return t; } }F,A; //F:数列矩阵 A:转移矩阵 void qpow(LL n){ while(n){ if(n&1) F=F*A; A=A*A; n>>=1; } } int main(){ LL n; cin>>n; if(n<=2){puts("1"); return 0;} F.c[0][0]=F.c[0][1]=1; A.c[0][0]=A.c[0][1]=A.c[1][0]=1; qpow(n-2); cout<<F.c[0][0]; }
// O(2^3*logn) #include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int mod=1000000007; struct mat{ LL c[2][2]; mat(){memset(c,0,sizeof c);} mat operator*(const mat &x){ mat t; for(int i=0; i<2; ++i) for(int j=0; j<2; ++j) for(int k=0; k<2; ++k) t.c[i][j]=(t.c[i][j]+c[i][k]*x.c[k][j])%mod; return t; } }F,A; //F:数列矩阵 A:转移矩阵 void qpow(LL n){ while(n){ if(n&1) F=A*F; //A*F型 A=A*A; n>>=1; } } int main(){ LL n; cin>>n; if(n<=2){puts("1"); return 0;} A.c[0][0]=A.c[0][1]=A.c[1][0]=1; F.c[0][0]=F.c[1][0]=1; qpow(n-2); cout<<F.c[0][0]; }
#include <iostream> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const int mod=1000000007; struct mat{ LL c[3][3]; mat(){memset(c, 0, sizeof c);} }F,A; //F:数列矩阵 A:转移矩阵 mat operator*(mat &a, mat &b){ mat t; for(int i=0; i<3; ++i) for(int j=0; j<3; ++j) for(int k=0; k<3; ++k){ t.c[i][j]+=a.c[i][k]*b.c[k][j]%mod; t.c[i][j]%=mod; } return t; } void qpow(LL n){ F.c[0][0]=F.c[0][1]=F.c[0][2]=1; memset(A.c, 0, sizeof(A.c)); A.c[0][0]=A.c[0][1]=A.c[1][2]=A.c[2][0]=1; while(n){ if(n&1) F=F*A; A=A*A; n>>=1; } } int main(){ LL T,n; cin>>T; while(T--){ cin>>n; if(n<=3){puts("1"); continue;} qpow(n-3); cout<<F.c[0][0]<<endl; } }
浙公网安备 33010602011771号