标签:title space play relative info namespace 斐波那契 code pen
/* 矩阵快速幂模板 斐波那契 */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 2; const int mod = 10000; //矩阵结构体 struct Matrix{ int a[maxn][maxn]; void init(){ //初始化为单位矩阵 memset(a, 0, sizeof(a)); for(int i=0;i<maxn;++i){ a[i][i] = 1; } } }; //矩阵乘法 Matrix mul(Matrix a, Matrix b){ Matrix ans; for(int i=0;i<maxn;++i){ for(int j=0;j<maxn;++j){ ans.a[i][j] = 0; for(int k=0;k<maxn;++k){ ans.a[i][j] += a.a[i][k] * b.a[k][j]; ans.a[i][j] %= mod; } } } return ans; } //矩阵快速幂 Matrix qpow(Matrix a, int n){ Matrix ans; ans.init(); while(n){ if(n&1) ans = mul(ans, a); a = mul(a, a); n /= 2; } return ans; } void output(Matrix a){ for(int i=0;i<maxn;++i){ for(int j=0;j<maxn;++j){ cout << a.a[i][j] << " "; } cout << endl; } } int main(){ Matrix a; a.a[0][0] = 1; a.a[0][1] = 1; a.a[1][0] = 1; a.a[1][1] = 0; Matrix ans = qpow(a, 10); cout << "f(12) = [f(2), f(1)] = [1, 1] * a^10 = " << ans.a[0][0] + ans.a[1][0]; return 0; }
Input
Output
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> using namespace std; const long long mod = 2147493647; const int MAXN = 8; struct prog { long long a[MAXN][MAXN]; }; prog s,B; prog matrixmul(prog a,prog b) //矩阵相乘 { prog c; for(int i=1; i<MAXN; ++i) for(int j=1; j<MAXN; ++j) { c.a[i][j]=0; for(int k=1; k<MAXN; k++) c.a[i][j]+=(a.a[i][k]*b.a[k][j])%mod; c.a[i][j]%=mod; } return c; } prog mul(prog s,int k) { prog ans; for(int i=1; i<MAXN; ++i) for(int j=1; j<MAXN; ++j) ans.a[i][j]=(i==j)?1:0; while(k) { if(k&1) ans=matrixmul(ans,s); k>>=1; s=matrixmul(s,s); } return ans; } int main() { int n,t,a,b; for(scanf("%d",&t); t--;) { scanf("%d %d %d",&n,&a,&b); if(n==1) { printf("%lld\n",a%mod); continue; } if(n==2) { printf("%lld\n",b%mod); continue; } if(n==3) { printf("%lld\n",(81+2*a%mod+b%mod)%mod); continue; } n-=2; for(int i=1; i<=7; ++i) for(int j=1; j<=7; ++j) s.a[i][j]=0, B.a[i][j]=0; for(int i=1; i<=5; i++) s.a[i][1]=1; for(int i=2; i<=5; i++) s.a[i][2]=i-1; s.a[3][3]=1; s.a[4][3]=3; s.a[5][3]=6; s.a[4][4]=1; s.a[5][4]=4; s.a[5][5]=1; s.a[6][5]=1; s.a[6][6]=1; s.a[7][6]=1; s.a[6][7]=2; B.a[1][1]=1; B.a[2][1]=3; B.a[3][1]=9; B.a[4][1]=27; B.a[5][1]=81; B.a[6][1]=b; B.a[7][1]=a; s=mul(s,n); s=matrixmul(s,B); printf("%lld\n",s.a[6][1]%mod); } return 0; }
Sample Input
Sample Output
Hint
In the first case, the third number is 85 = 2*1十2十3^4. In the second case, the third number is 93 = 2*1十1*10十3^4 and the fourth number is 369 = 2 * 10 十 93 十 4^4.
标签:title space play relative info namespace 斐波那契 code pen
原文地址:https://www.cnblogs.com/jk17211764/p/9744907.html