hdu4549 M斐波那契数列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sxy201658506207/article/details/83512815

题意:F[0] = a ,F[1] = b,F[n] = F[n-1] * F[n-2] ( n > 1 )
现在给出a, b, n,你能求出F[n]的值
想到点子上就很简单了,可当时做的时候都没有向找递推式的方向去思考
1.找F[n]的递推式

附:斐波那契数矩阵公式
 Fn+1   Fn        1    1
                     =             的n次方
 Fn     Fn-1       1     0

#include <bits/stdc++.h>
#define X 10005
#define inf 0x3f3f3f3f
#define PI 3.141592653589793238462643383
using namespace std;
typedef long long ll;
const int mod=1e9+7;
struct node
{
    ll e[2][2];
} f;
node Matrix(node a,node b)
{
    node ans;
    for(int i=0; i<2; ++i)
    {
        for(int j=0; j<2; ++j)
        {
            ans.e[i][j]=0;
            for(int k=0; k<2; ++k)
                if(a.e[i][k]&&b.e[k][j])
                    //ans.e[i][j]=(ans.e[i][j]+(a.e[i][k]*b.e[k][j])%(mod-1))%(mod-1);  相等
                    ans.e[i][j]=(ans.e[i][j]+(a.e[i][k]*b.e[k][j]))%(mod-1);
        }
    }
    return ans;
}
node Pow(node a,int n)
{
    node E;
    E.e[0][0]=E.e[1][1]=1;
    E.e[0][1]=E.e[1][0]=0;
    while(n)
    {
        if(n&1) E=Matrix(E,a);
        a=Matrix(a,a);
        n/=2;
    }
    return E;
}
ll Pow_(ll a,ll n)
{
    ll ans=1;
    while(n)
    {
        if(n&1)
            ans=ans*a%mod;
        a=a*a%mod;
        n/=2;
    }
    return ans%mod;
}
int main()
{
    ll a,b,n;
    while(scanf("%lld %lld %lld",&a,&b,&n)!=EOF)
    {
        f.e[0][0]=f.e[0][1]=f.e[1][0]=1,f.e[1][1]=0;
        if(n==0)
        {
            cout<<a<<endl;
        }
        else
        {
            f=Pow(f,n-1);
            ll x=f.e[1][0];
            ll y=f.e[0][0];
            printf("%lld\n",Pow_(a,x)*Pow_(b,y)%mod);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sxy201658506207/article/details/83512815