F(n, 1)=F(n-1, 2) + 2F(n-3, 1) + 5,
F(n, 2)=F(n-1, 1) + 3F(n-3, 1) + 2F(n-3, 2) + 3.
初始值爲:F(1, 1)=2, F(1, 2)=3, F(2, 1)=1, F(2, 2)=4, F(3, 1)=6, F(3, 2)=5。
輸入n,輸出F(n, 1)和F(n, 2),由於答案可能很大,你只需要輸出答案除以99999999的餘數。
21
0,1,1,0,0,0,0,0,
1,0,0,1,0,0,0,0,
0,0,0,0,1,0,0,0,
0,0,0,0,0,1,0,0,
2,3,0,0,0,0,0,0,
0,2,0,0,0,0,0,0,
1,0,0,0,0,0,1,0,
0,1,0,0,0,0,0,1
之後再利用矩陣快速冪的方法得到結果。
AC代碼:
#include <iostream> #include <cstring> using namespace std; struct matrix { long long a[8][8]; }; matrix multiply(matrix x,matrix y,int m,int n,int s)//m*s s*n 矩陣相乘 { matrix temp; memset(temp.a,0,sizeof(temp.a)); for(int i=0;i<m;i++) for(int j=0;j<n;j++) for(int k=0;k<s;k++) temp.a[i][j]=(temp.a[i][j]+(x.a[i][k]*y.a[k][j])%99999999)%99999999; return temp; } int main() { matrix temp={ 0,1,1,0,0,0,0,0, 1,0,0,1,0,0,0,0, 0,0,0,0,1,0,0,0, 0,0,0,0,0,1,0,0, 2,3,0,0,0,0,0,0, 0,2,0,0,0,0,0,0, 1,0,0,0,0,0,1,0, 0,1,0,0,0,0,0,1 }; matrix res; long long f[8]={6,5,1,4,2,3,5,3},sum1,sum2,n; memset(res.a,0,sizeof(res.a)); for(int i=0;i<8;i++) res.a[i][i]=1; cin>>n; if(n==1) cout<<"2"<<endl<<"3"<<endl; if(n==2) cout<<"1"<<endl<<"4"<<endl; if(n==3) cout<<"6"<<endl<<"5"<<endl; if(n>=4) { n=n-3; while(n)//矩陣快速冪 { if(n&1) { res=multiply(res,temp,8,8,8); } n>>=1; temp=multiply(temp,temp,8,8,8); } sum1=sum2=0; for(int i=0;i<8;i++) { sum1=(sum1+(f[i]*res.a[i][0])%99999999)%99999999; sum2=(sum2+(f[i]*res.a[i][1])%99999999)%99999999; } cout<<sum1<<endl<<sum2<<endl; } return 0; }