P1939 【模板】矩阵加速(数列) (矩阵快速幂)

题目链接

题面:
在这里插入图片描述

题解:
求出转移矩阵来,利用矩阵快速幂加速运算。

其实这种线性的表达式,杜教BM一下就好啦。

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<queue>
#define ll long long
using namespace std;
const int maxn=110;
const int mod=1e9+7;
struct node
{
    ll a[5][5];
    node()
    {
        memset(a,0,sizeof(a));
    }
};
node operator *(const node &a,const node &b)
{
    node c;
    for(int i=1;i<=3;i++)
    {
        for(int j=1;j<=3;j++)
        {
            for(int k=1;k<=3;k++)
            {
                c.a[i][j]=(c.a[i][j]+a.a[i][k]*b.a[k][j])%mod;
            }
        }
    }
    return c;
}

node mypow(node a,ll b)
{
    node ans;
    for(int i=1;i<=3;i++)
        ans.a[i][i]=1;
    while(b)
    {
        if(b&1) ans=ans*a;
        a=a*a;
        b>>=1;
    }
    return ans;
}

int main(void)
{
    ll t,n;
    scanf("%lld",&t);
    while(t--)
    {
        scanf("%lld",&n);
        node res;
        res.a[1][1]=res.a[1][3]=res.a[2][1]=res.a[3][2]=1;
        if(n<=3) printf("1\n");
        else
        {
            res=mypow(res,n-3);
            printf("%lld\n",(res.a[1][1]+res.a[1][2]+res.a[1][3])%mod);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值