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)取余的值。
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;
}
完成了