G04 矩阵加速 P1962 斐波那契数列
视频链接:510 矩阵加速 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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!