hdu6172-(矩阵快速幂)

本文介绍了一种利用矩阵快速幂解决特定递推数列的方法,通过找到递推公式 an=4an-1+17an-2-12an-3 的规律,并使用矩阵快速幂进行高效计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题解:打表后你会找到规律an = 4an-1+17an-2-12an-3,然后套个矩阵快速幂就可以了


#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
const int mod = 1e9+7;
typedef long long int ll;
struct mat{
    ll a[3][3];
};
mat operator*(const mat &x,const mat &y){
        mat z;
        for(int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++){
                z.a[i][j] = 0;
                for(int k = 0; k < 3; k++)
                    z.a[i][j] = (z.a[i][j]+x.a[i][k]*y.a[k][j])%mod;
            }
        return z;
}
mat x = {1255,0,0,197,0,0,31,0,0};
mat a = {4,17,-12,1,0,0,0,1,0};
void calc(mat &ans,mat x,ll n){
    while(n){
        if(n&1)ans = x*ans;
        x = x*x;
        n/=2;
    }
}
int main(){
    int t;
    ll n;
    scanf("%d",&t);
    while(t--){
        scanf("%I64d",&n);
        if(n<=4){
            printf("%I64d\n",x.a[4-n][0]);
            continue;
        }
        mat ans = x;
        calc(ans,a,n-4);
        printf("%I64d\n",(ans.a[0][0]%mod+mod)%mod);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值