HDU 6470 /// 矩阵快速幂

本文介绍了一种使用矩阵快速幂方法求解特定形式递推数列的高效算法,并通过一个具体的实例展示了如何将递推公式转化为矩阵运算的形式,进而利用快速幂的方法求得第n项的值。

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

题目大意:

f[1]=1 f[2]=2

f[n]=f[n-1]+2*f[n-2]+n^3

 

在某博客截的图 现在忘记原博位置了 抱歉

 

 

根据递推式1和递推式3构造出两个矩阵 

#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define LL long long
#define inc(i,j,k) for(int i=j;i<=k;i++)
#define dec(i,j,k) for(int i=j;i>=k;i--)
#define gcd(i,j) __gcd(i,j)
#define mem(i,j) memset(i,j,sizeof(i))
const int N=1e5+5;
const int M=6;
const int mod=123456789;

LL n,m;
struct MAT {
    LL a[M][M];
    MAT(){ mem(a,0); }
    MAT operator*(MAT p) {
        MAT res;
        for(int i=0;i<M;i++)
        for(int j=0;j<M;j++)
        for(int k=0;k<M;k++)
            res.a[i][j]=(res.a[i][j]+a[i][k]*p.a[k][j])%mod;
        return res;
    }
};
MAT mod_pow(MAT A,LL x) {
    MAT res;
    res.a[0][0]=1;
    while(x) {
        if(x&1) res=res*A;
        A=A*A; x>>=1;
    } 
    return res;
}
void init(MAT& A,MAT& B) {
    A.a[0][0]=1,A.a[0][1]=2,A.a[0][2]=1,
    A.a[1][0]=1,
                            A.a[2][2]=1,A.a[2][3]=3,A.a[2][4]=3,A.a[2][5]=1,
                                        A.a[3][3]=1,A.a[3][4]=2,A.a[3][5]=1,
                                                    A.a[4][4]=1,A.a[4][5]=1,
                                                                A.a[5][5]=1;
    B.a[0][0]=2,B.a[1][0]=1,B.a[2][0]=27,B.a[3][0]=9,B.a[4][0]=3,B.a[5][0]=1;
}

int main()
{
    int _; scanf("%d",&_);
    while(_--) {
        LL n; scanf("%lld",&n); 
        MAT A; MAT ans;
        init(A,ans);
        ans=mod_pow(A,n-2LL)*ans;
        printf("%lld\n",ans.a[0][0]);
    }

    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/zquzjx/p/10549775.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值