題目描述#
a[1]=a[2]=a[3]=1
a[x]=a[x-3]+a[x-1] (x>3)
求 a 數列的第 n 項對 1000000007(10^9+7)取餘的值。
輸入輸出格式#
輸入格式:#
第一行一個整數 T,表示詢問個數。
以下 T 行,每行一個正整數 n。
輸出格式:#
每行輸出一個非負整數表示答案。
輸入輸出樣例#
輸入樣例 #1:
3
6
8
10
輸出樣例 #1:
4
9
19
說明#
對於 30% 的數據 n<=100;
對於 60% 的數據 n<=2*10^7;
對於 100% 的數據 T<=100,n<=2*10^9;
解決#
正如標題那樣,模板題
[f[x],f[x-1],f[x-2],f[x-3]]=[f[x-1],f[x-2],f[x-3],f[x-4]]*A
A=[
1 1 0 0
0 0 1 0
1 0 0 1
0 0 0 0
]
可能想不到的地方(我沒想到的地方):
- a [x]=a [x-3]+a [x-1] ,但 x-2,x-4 也可以放進矩陣裡
- n<=3 時會死迴圈,要特判
#include<iostream>
#include<cstring>
#define min(a,b) ((a)>(b)?(b):(a))
#define max(a,b) ((a)<(b)?(b):(a))
using namespace std;
const long long MAXN=10,mo=1e9+7;
struct juzhen{
public:
juzhen(int han,int lin){
h=han,l=lin;
memset(v,0,sizeof(v));
}
juzhen(){
memset(v,0,sizeof(v));
}
void cleanForPow(void){
memset(v,0,sizeof(v));
int p=min(h,l);
for(int i=1;i<=p;++i){
v[i][i]=1;
}
}
friend juzhen operator *(juzhen a,juzhen b){
juzhen c(a.h,b.l);
if(a.l!=b.h)return c;
for(int i=1;i<=a.h;++i){
for(int j=1;j<=b.l;++j){
long long s=0;
for(int k=1;k<=a.l;++k){
s=s%mo+(a.v[i][k]*b.v[k][j]%mo);
}
c.v[i][j]=s;
}
}
return c;
}
juzhen pow(int k){
juzhen res=*this;
juzhen ret(h,l);
ret.cleanForPow();
while(k){
if(k&1){
ret=ret*res;
}
res=res*res;
k>>=1;
}
return ret;
}
void setV(long long t[MAXN][MAXN]){
for(int i=1;i<=h;++i){
for(int j=1;j<=l;++j){
v[i][j]=t[i][j];
}
}
}
long long v[MAXN][MAXN];
private:
int h,l;
};
int main(void){
int T;
cin>>T;
long long tmp[MAXN][MAXN]={{0},{0,2,1,1,1}};
long long tmp2[MAXN][MAXN]={
{0},
{0,1,1,0,0},
{0,0,0,1,0},
{0,1,0,0,1},
{0,0,0,0,0}
};
juzhen a(1,4);
juzhen b(4,4);
a.setV(tmp);
b.setV(tmp2);
while(T--){
int n;
cin>>n;
if(n<=3)cout<<"1\n",continue;
juzhen ans=a*b.pow(n-4);
cout<<ans.v[1][1]<<'\n';
}
return 0;
}