Problem DescriptionM斐波那契數(shù)列F[n]是一種整數(shù)數(shù)列,它的定義如下:
F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n >1 )
現(xiàn)在給出a, b, n,你能求出F[n]的值嗎?
Input輸入包含多組測試數(shù)據(jù);
每組數(shù)據(jù)占一行,包含3個整數(shù)a, b, n( 0<= a, b, n<= 10^9 )
Output對每組測試數(shù)據(jù)請輸出一個整數(shù)F[n],由于F[n]可能很大,你只需輸出F[n]對1000000007取模后的值即可,每組數(shù)據(jù)輸出一行,
HDU 4549 M斐波那契數(shù)列(矩陣快速冪)
。Sample Input
0 1 06 10 2
Sample Output
060通過觀察我們發(fā)現(xiàn)f[n]中a,b的數(shù)量變化符合斐波那契數(shù)列特征。于是f[n]=a^k*b^m%MOD;因此我們要用矩陣快速冪去求a和b的冪然而由于數(shù)很大,同樣要去模一個數(shù),這就是這個題的坑點。求和后用快速冪求f[n]就簡單了。同樣此題要注意前兩項。
#include<cstdio>#include<cstring>#include#include<vector>#include<string>#include<iostream>#include<queue>#include<cmath>#include<map>#include<stack>#include<b>using namespace std;#define REPF( i , a , b ) for ( int i = a ; i<= b ; ++ i )#define REP( i , n ) for ( int i = 0 ; i< n ; ++ i )#define CLEAR( a , x ) memset ( a , x , sizeof a )typedef long long LL;typedef pair<int,int>pil;const int INF = 0x3f3f3f3f;const int MOD=1e9+6;LL a,b,n;struct Matrix{ LL mat[2][2]; void Clear() { CLEAR(mat,0); }};Matrix mult(Matrix m1,Matrix m2){ Matrix ans; for(int i=0;i<2;i++) for(int j=0;j<2;j++) { ans.mat[i][j]=0; for(int k=0;k<2;k++) ans.mat[i][j]=(ans.mat[i][j]+m1.mat[i][k]*m2.mat[k][j])%MOD; } return ans;}Matrix Pow(Matrix m1,LL b){ Matrix ans;ans.Clear(); for(int i=0;i<2;i++) ans.mat[i][i]=1; while(b) { if(b&1) ans=mult(ans,m1); b>>=1; m1=mult(m1,m1); } return ans;}LL quick_mod(LL a,LL b){ LL ans=1; while(b) { if(b&1) ans=ans*a%1000000007; b>>=1; a=a*a%1000000007; } return ans;}int main(){ while(~scanf("%lld%lld%lld",&a,&b,&n)) { Matrix A; if(n<=1) { printf("%lld\n",n==0?a:b); continue; } A.mat[0][0]=A.mat[0][1]=1; A.mat[1][0]=1;A.mat[1][1]=0; A=Pow(A,n-1); LL m,k; m=(A.mat[0][0])%MOD;k=(A.mat[0][1])%MOD; LL ans=1; ans=ans*quick_mod(a,k)%1000000007; ans=ans*quick_mod(b,m)%1000000007; printf("%lld\n",ans); } return 0;}