hdu 5950 Recursive sequence(矩阵快速幂)

题意

f[n]=f[n-1]+2*f[n-2]+n^4; f[1]=a f[2]=b 求第n项

题解

由于n太大,直接递推肯定会超时间,因此用到矩阵快速幂

先推一下

\((n+1)^4=n^4+4n^3+6n^2+4n+1\\\ (n+1)^3=n^3+3n^2+3n+1\\\ (n+1)^2=n^2+2n+1\)

因此构造矩阵

\(\begin{bmatrix} 1&2&1&0&0&0&0\\1&0&0&0&0&0&0\\0&0&1&4&6&4&1\\0&0&0&1&3&3&1\\0&0&0&0&1&2&1\\0&0&0&0&0&1&1\\0&0&0&0&0&0&1 \end{bmatrix}\)

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 2147493647;
struct node{LL c[7][7];};
node mul(node x,node y)
{
    node res;
    for(int i=0;i<7;i++)
    for(int j=0;j<7;j++)
    {
        res.c[i][j]=0;
        for(int k=0;k<7;k++)
            res.c[i][j]=(res.c[i][j]+(x.c[i][k]*y.c[k][j])%mod)%mod;
    }
    return res;
}
node quickmod(node x,int y)
{
    node res;
    for(int i=0;i<7;i++)
        for(int j=0;j<7;j++)
        {
            if(i==j)res.c[i][j]=1;
            else res.c[i][j]=0;
        }
    while(y)
    {
        if(y&1)res=mul(res,x);
        y>>=1;
        x=mul(x,x);
    }
    return res;
}
int main()
{
    node t;
    for(int i=0;i<7;i++)
        for(int j=0;j<7;j++)t.c[i][j]=0;
    t.c[0][0]=1;t.c[0][1]=2;t.c[0][2]=1;t.c[1][0]=1;
    t.c[2][2]=1;t.c[2][3]=4;t.c[2][4]=6;t.c[2][5]=4;t.c[2][6]=1;
    t.c[3][3]=1;t.c[3][4]=3;t.c[3][5]=3;t.c[3][6]=1;
    t.c[4][4]=1;t.c[4][5]=2;t.c[4][6]=1;
    t.c[5][5]=1;t.c[5][6]=1;t.c[6][6]=1;
    int T;
    cin>>T;
    while(T--)
    {
        int n,a,b;
        scanf("%d%d%d",&n,&a,&b);
        if(n==1)printf("%d\n",a%mod);
        else if(n==2)printf("%d\n",b%mod);
        else
        {
            node now=quickmod(t,n-2);
            node s;
            for(int i=0;i<7;i++)
                for(int j=0;j<7;j++)s.c[i][j]=0;
            s.c[0][0]=b%mod;s.c[1][0]=a%mod;s.c[2][0]=81;s.c[3][0]=27;
            s.c[4][0]=9;s.c[5][0]=3;s.c[6][0]=1;
            node ans=mul(now,s);
            printf("%lld\n",ans.c[0][0]);
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/HooYing/p/11422758.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值