【矩阵乘法】 P1939 【模板】矩阵加速(数列)

本文介绍了一种使用矩阵快速幂的方法来高效求解斐波那契数列的问题。通过构建特定矩阵并利用快速幂运算,可以大幅提高计算斐波那契数列第n项的速度,尤其在n值较大时优势明显。

这道题的思路与 P1962 斐波那契数列 基本一致,推出矩阵\begin{bmatrix} 0 &0 &1 \\ 1 &0 &0 \\ 0 &1 &1 \end{bmatrix},然后快速幂即可

#include<bits/stdc++.h>
using namespace std;
int T,n;
const int mod=1e9+7;
struct juzhen
{
	long long a[4][4];
}ans,fore,temp;
juzhen mul(juzhen xa, juzhen xb)
{
	juzhen cnt;
	for(int i=1;i<=3;i++)
		for(int j=1;j<=3;j++)
		{
			long long tmp=0;
			for(int k=1;k<=3;k++)
				tmp+=(xa.a[i][k]*xb.a[k][j])%mod,tmp%=mod;
			cnt.a[i][j]=tmp;	
		}
	return cnt;
}
juzhen pow(long long x)
{
	if(x==0)
	{
		return temp;
	}
	if(x==1)
	{
		return fore;
	}
	if(x%2==1)
	{
		juzhen xa=pow((x-1)/2);
		return mul(mul(xa,xa),fore);
	}
	else
	{
		juzhen xa=pow(x/2);
		return mul(xa,xa);
	}
}
int main()
{
	scanf("%d",&T);
	for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) fore.a[i][j]=0;
	fore.a[1][3]=fore.a[2][1]=fore.a[3][2]=fore.a[3][3]=1;
	for(int i=1;i<=3;i++) for(int j=1;j<=3;j++) temp.a[i][j]=0;
	temp.a[1][1]=temp.a[2][2]=temp.a[3][3]=1;
	while(T--)
	{
		scanf("%d",&n);
		ans=pow(n-1);
		printf("%lld\n",(ans.a[1][1]+ans.a[2][1]+ans.a[3][1])%mod);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值