【矩阵乘法加速递推】洛谷P1939 矩阵加速(数列)

链接

https://www.luogu.org/problemnew/show/P1939


大意

a [ 1 ] = a [ 2 ] = a [ 3 ] = 1 a[1]=a[2]=a[3]=1 a[1]=a[2]=a[3]=1
a [ x ] = a [ x − 3 ] + a [ x − 1 ] ( x > 3 ) a[x]=a[x-3]+a[x-1] (x>3) a[x]=a[x3]+a[x1](x>3)
a a a数列的第 n n n项对 1 0 9 + 7 10^9+7 109+7取余的值


思路

矩阵乘法加速递推


代码

#include<cstdio>
#include<cstring>
#define ymw 1000000007
#define LL long long
#define r(i,x,y) for(register int i=x;i<y;i++)
using namespace std; 
LL n,g,f[3],a[3][3]; 
inline void mulself()
{
    LL c[3][3]={{0,0,0},{0,0,0},{0,0,0}}; 
    r(i,0,3) r(j,0,3) r(k,0,3) c[i][j]=(c[i][j]+a[i][k]*a[k][j])%ymw; 
    memcpy(a,c,sizeof(c)); 
}
inline void mulans()
{
    LL c[3]={0,0,0};  
    r(j,0,3) r(k,0,3) c[j]=(c[j]+f[k]*a[k][j])%ymw; 
    memcpy(f,c,sizeof(c));
}
signed main()
{
    scanf("%lld",&g); 
    while (g--)
    {
        scanf("%lld",&n); 
        if(n<4) {printf("1\n");continue;}
        n-=3;  
        f[0]=f[1]=f[2]=1;
        a[0][0]=a[0][1]=a[1][1]=a[1][2]=a[2][0]=0;
        a[0][2]=a[1][0]=a[2][1]=a[2][2]=1;
        for(;n;mulself(),n>>=1) if (n&1) mulans();
        printf("%lld\n",f[2]%ymw);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值