P1939 【模板】矩陣加速(數列)
阿新 • • 發佈:2017-08-16
include algo pid str ostream 格式 矩陣加速 continue pri
鏈接: P1939 【模板】矩陣加速(數列)
題目描述 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;題幹
#include<iostream> #include代碼<cstdio> #include<queue> #include<vector> #include<algorithm> #include<math.h> #include<cstring> using namespace std; #define LL unsigned long long #define MOD 1000000007 struct node{ LL v[3][3]; }x,b,ans,p; LL T,n; node cheng(node x,node y) { for(int i=0;i<=2;i++)for(int j=0;j<=2;j++) { p.v[i][j]=0; for(int k=0;k<=2;k++) p.v[i][j]=(p.v[i][j]+x.v[i][k]*y.v[k][j])%MOD; } return p; } void fastlow() { while(n) { if(n%2) ans=cheng(ans,x); x=cheng(x,x);n/=2; } } int main() { scanf("%lld",&T); b.v[0][1]=b.v[0][2]=b.v[0][0]=1; x.v[0][0]=x.v[0][1]=1; x.v[1][2]=1; x.v[2][0]=1; ans=cheng(b,x); for(int i=1;i<=T;i++) { scanf("%lld",&n); x.v[0][0]=x.v[0][1]=1;x.v[0][2]=0; x.v[1][2]=1;x.v[1][0]=x.v[1][1]=0; x.v[2][0]=1;x.v[2][1]=x.v[2][2]=0; ans=cheng(b,x); if(n<=3) { printf("1\n"); continue; } n-=4;fastlow(); printf("%lld\n",ans.v[0][0]); } return 0; }
要註意的問題:
因為有T組數據,所以要初始化“乘數單元“(0,1都要初始化!)。
記得要調用函數名,只寫括號是不對但能編譯過的。這個錯誤最難找。
P1939 【模板】矩陣加速(數列)