HDU 4549 M斐波那契数列(矩阵快速幂)

来源:互联网 发布:回家吃饭网络订餐 编辑:程序博客网 时间:2024/05/16 19:36
Problem Description
M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?
 

Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )
 

Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。
 

Sample Input
0 1 06 10 2
 

Sample Output
060
 
通过观察我们发现f[n]中a,b的数量变化符合斐波那契数列特征。
于是f[n]=a^k*b^m%MOD;因此我们要用矩阵快速幂去求a和b的幂
然而由于数很大,同样要去模一个数,根据欧拉公式(a^b%c=a^(b%phi(c)+phi(c))%c;
(b>=phi(c)),这就是这个题的坑点。求和后用快速幂求f[n]就简单了。同样此题要注意前两项。
#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#include<string>#include<iostream>#include<queue>#include<cmath>#include<map>#include<stack>#include<bitset>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;}



0 0
原创粉丝点击