CODEVS 3332 数列

博客介绍了如何利用矩阵快速幂算法解决CODEVS 3332题目的数列问题。给定数列的递推公式是a[x] = a[x-3] + a[x-1],对于大数n,直接搜索或预处理不可行。博主通过矩阵乘法和快速幂的方法实现了高效求解,并提供了完整的C++代码实现。

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

CODEVS 3332 数列
【题目描述 Description】
a[1]=a[2]=a[3]=1
a[x]=a[x-3]+a[x-1]  (x>3)
求a数列的第n项对1000000007(10^9+7)取余的值。

【输入描述 Input Description】
第一行一个整数T,表示询问个数。
以下T行,每行一个正整数n。

【输出描述 Output Description】
每行输出一个非负整数表示答案

【样例输入 Sample Input】
3
6
8
10
【样例输出 Sample Output】
4
9
19

【数据范围及提示 Data Size & Hint】
对于30%的数据 n<=100;
对于60%的数据 n<=2*10^7;
对于100%的数据 T<=100,n<=2*10^9


【题解】
对于n的大小,我们可以看出每次搜索预处理都是不可能的;
我们的time和memory遭不住;
又根据题目描述,于是果断想到矩阵乘法:

       

然后用矩阵快速幂就可以快速AC了

下面附上华丽丽の代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int T;
const int mod = 1000000007;
struct node
{
	int m[4][4];
}E,st,F;                      //E为单位矩阵,F是[a,b,c],st好像没用(不要在意这些细节<img alt="吐舌头" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/tongue.gif" />)
void clean()
{
	for(int i=1;i<=3;i++)
	{
		E.m[i][i]=1;
		st.m[i][1]=1;
	}
	F.m[1][2]=F.m[2][3]=F.m[3][1]=F.m[3][3]=1;
}
node cheng(node a,node b)                    //矩阵乘法
{
	node ans;
	for(int i=1;i<4;i++)
	{
		for(int j=1;j<4;j++)
		{
			ans.m[i][j]=0;
			for(int k=1;k<4;k++)
			{
				ans.m[i][j]=(ans.m[i][j]+((long long)a.m[i][k]*b.m[k][j])%mod)%mod;
			}
		}
	}
	return ans;
	
}
void work()
{
	node ans=E,cnt=F;
	while(n)                             //快速幂
	{
		if(n&1)
		{
			ans=cheng(ans,cnt);
		}
		n>>=1;
		cnt=cheng(cnt,cnt);
	}
	printf("%d\n",ans.m[3][1]);
}

int main()
{
	clean();                             //初始化矩阵(貌似可以开在结构体内<img alt="奋斗" src="http://static.blog.youkuaiyun.com/xheditor/xheditor_emot/default/struggle.gif" />)
	scanf("%d",&T);
	for(int i=1;i<=T;i++)
	{
		scanf("%d",&n);
		work();
	}
	return 0;
}
完成了得意

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值