luogu_1939 【模板】矩阵加速(数列)

本文介绍了一种利用矩阵快速幂解决特定数列求值问题的方法。通过定义特定矩阵及其乘法运算,实现了对数时间复杂度内计算数列第n项的值。文章提供了两种实现方式,一种为传统循环实现,另一种则采用面向对象的方式,增强了代码的可读性和复用性。

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

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
int T;
LL n;

struct Matrix{
	LL h[5][5];
}a;

int main(){
	ios::sync_with_stdio(false);
	cin>>T;
	while(T--){
		Matrix ans,t;
		cin>>n;
		ans.h[1][1]=1; ans.h[1][2]=1; ans.h[1][3]=1;
		t.h[1][1]=1; t.h[1][2]=1; t.h[1][3]=0;
		t.h[2][1]=0; t.h[2][2]=0; t.h[2][3]=1;
		t.h[3][1]=1; t.h[3][2]=0; t.h[3][3]=0;
		for(n-=3;n>0;n>>=1){
			if(n&1){
				Matrix x;
				for(int i=1;i<=3;i++){
					LL sum=0;
					for(int j=1;j<=3;j++)sum+=ans.h[1][j]*t.h[j][i],sum%=mod;
					x.h[1][i]=sum;
				}
				for(int i=1;i<=3;i++)ans.h[1][i]=x.h[1][i];
			}
			Matrix d;
			for(int i=1;i<=3;i++)
				for(int j=1;j<=3;j++){
					LL sum=0;
					for(int k=1;k<=3;k++)sum+=t.h[i][k]*t.h[k][j],sum%=mod;
					d.h[i][j]=sum;
				}
			for(int i=1;i<=3;i++)
				for(int j=1;j<=3;j++)t.h[i][j]=d.h[i][j];
		}
		cout<<ans.h[1][1]<<endl;
	}
	return 0; 
}

  

  //结构体函数版:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
int T;
LL n;

struct Matrix{
	LL h[5][5];
	void clear(){
		memset(h,0,sizeof(h));
	}
	Matrix operator * (const Matrix& t) const{
		Matrix d; d.clear();
		for(int i=1;i<=3;i++)
			for(int j=1;j<=3;j++){
				LL sum=0;
				for(int k=1;k<=3;k++)sum+=h[i][k]*t.h[k][j],sum%=mod;
				d.h[i][j]=sum;
			}
		return d;
	}
	Matrix operator ^ (LL k) const {
		Matrix ans(*this),t(*this),x(*this);
		t.clear();
		t.h[1][1]=1; t.h[1][2]=1; t.h[1][3]=0;
		t.h[2][1]=0; t.h[2][2]=0; t.h[2][3]=1;
		t.h[3][1]=1; t.h[3][2]=0; t.h[3][3]=0;
		for(k-=3;k>0;k>>=1){
			if(k&1)
				for(int i=1;i<=3;i++){
					LL sum=0;
					for(int j=1;j<=3;j++)sum+=ans.h[1][j]*t.h[j][i],sum%=mod;
					x.h[1][i]=sum;
				}
			for(int i=1;i<=3;i++)ans.h[1][i]=x.h[1][i];
			t=t*t;
		}
		return ans;
	}
}a;

int main(){
	ios::sync_with_stdio(false);
	cin>>T;
	while(T--){
		Matrix ans,t;
		cin>>n;
		ans.h[1][1]=1; ans.h[1][2]=1; ans.h[1][3]=1;
		t.h[1][1]=1; t.h[1][2]=1; t.h[1][3]=0;
		t.h[2][1]=0; t.h[2][2]=0; t.h[2][3]=1;
		t.h[3][1]=1; t.h[3][2]=0; t.h[3][3]=0;
		ans=ans^n;
		cout<<ans.h[1][1]<<endl;
	}
	return 0; 
}

  

转载于:https://www.cnblogs.com/codetogether/p/7577191.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值