题目描述
a[1]=a[2]=a[3]=1
a[x]=a[x-3]+a[x-1] (x>3)
求a数列的第n项对1000000007(10^9+7)取余的值。
Code
// by spli
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<iostream>
#define LL long long
using namespace std;
const int p=1e9+7;
int T,n;
struct Matrix{
LL a[5][5];
Matrix operator * (const Matrix &b)const{
Matrix ret;
for(int i=1;i<=3;++i)
for(int j=1;j<=3;++j){
ret.a[i][j]=0;
for(int k=1;k<=3;++k)
(ret.a[i][j]+=a[i][k]*b.a[k][j])%=p;
}
return ret;
}
}pre,ans;
Matrix exp(Matrix a,int b){
Matrix ret=a,k=a;
b--;
while(b){
if(b&1) ret=ret*k;
b>>=1;
k=k*k;
}
return ret;
}
int main(){
scanf("%d",&T);
pre.a[1][1]=1; pre.a[1][2]=1; pre.a[1][3]=0;
pre.a[2][1]=0; pre.a[2][2]=0; pre.a[2][3]=1;
pre.a[3][1]=1; pre.a[3][2]=0; pre.a[3][3]=0;
while(T--){
scanf("%d",&n);
if(n<=3) puts("1");
else{
ans.a[1][1]=1;
ans.a[1][2]=1;
ans.a[1][3]=1;
ans=ans*exp(pre,n-3);
printf("%lld\n",ans.a[1][1]%p);
}
}
return 0;
}