hdu 5667 Sequence

来源:互联网 发布:算法第四版pdf百度云 编辑:程序博客网 时间:2024/06/06 14:22
 Lcomyn 是个很厉害的选手,除了喜欢写17kb+的代码题,偶尔还会写数学题.他找到了一个数列:f_n=\left\{\begin{matrix} 1 ,&n=1 \\ a^b,&n=2 \\ a^bf_{n-1}^cf_{n-2},&otherwise \end{matrix}\right.fn=1,ab,abfn1cfn2,n=1n=2otherwise\ \ \ \    他给了你几个数:nn,aa,bb,cc,你需要告诉他f_nfnpp后的数值.
经过递推不难发现:
(1)a^0 (2) a^(b) (3) a^(b+bc) 
答案结果对于a的幂存在一个关系式 f(n)=b+c*f(n-1)+f(n-2)
这里我们可以利用矩阵快速幂求解,注意对于幂的我们要取模p-1,还要考虑a%p为0的情况。
ac代码:
#include <iostream>#include <cstdio>#include <set>#include <cstring>#include <algorithm>#include <vector>#include <cmath>#include <map>#include <string>#include <cctype>using namespace std;typedef long long LL;const int maxn = 3e5+10;LL mod,a,b,c,n;struct node{    LL len;    LL a[4][4];};node xmult(node as,node zx){    node x;    for(int i=0; i<3; i++)    {        for(int j=0; j<3; j++)        {            x.a[i][j]=0;            for(int k=0; k<3; k++)            {                x.a[i][j]+=as.a[i][k]*zx.a[k][j];                x.a[i][j]%=mod;            }        }    }    return x;}node init(){    node x;    x.a[0][0]=c;    x.a[0][1]=1;    x.a[0][2]=b;    x.a[1][0]=1;    x.a[1][1]=0;    x.a[1][2]=0;    x.a[2][0]=0;    x.a[2][1]=0;    x.a[2][2]=1;    return x;}node power(node x,LL y){    node ans;    for(int i=0; i<3; i++)    {        for(int j=0; j<3; j++)            if(i==j)                ans.a[i][j]=1;            else ans.a[i][j]=0;    }    while(y)    {        if(y&1)        {            ans=xmult(ans,x);        }        y>>=1;        x=xmult(x,x);    }    return ans;}LL power_mod(LL x ,LL y){    LL sum=1;    while(y)    {        if(y&1)        {            sum*=x,sum%=mod;        }        y>>=1;        x*=x;        x%=mod;    }    return sum;}int main(){    LL T;    scanf("%lld",&T);    while(T--)    {        scanf("%lld%lld%lld%lld%lld",&n,&a,&b,&c,&mod);        node x=init();        if(n==1) printf("%lld\n",1LL%mod);        else if(n==2) printf("%lld\n",power_mod(a,b));        else        {            node x=init();            mod--;            x=power(x,n-2);            LL sum=x.a[0][0]*b%mod+x.a[0][2]*1%mod;            sum=(sum%mod+mod)%mod;            mod++;            printf("%lld\n",power_mod(a,sum));        }    }    return 0;}


0 0
原创粉丝点击