解题思路:
求和需要小小的处理一下
构造矩阵,一开始定义sum=f[0]+f[1]
sum 1 1 0 0 sum
f[3] 0 3 2 7 f[2]
f[2] = 0 1 0 0 * f[1]
f[1] 0 0 1 0 f[0]
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
#define mod 2009
struct mat
{
int a[4][4];
};
mat mul(mat a,mat b)
{
mat ret;
memset(ret.a,0,sizeof(ret.a));
for(int i=0;i<4;i++)
{
for(int k=0;k<4;k++)
if(a.a[i][k])
{
for(int j=0;j<4;j++)
{
if(b.a[k][j])
ret.a[i][j] = (ret.a[i][j]+a.a[i][k]*b.a[k][j])%mod;
}
}
}
return ret;
}
mat mpower(mat a,int n)
{
mat I;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
I.a[i][j] = (i==j);
}
}
while(n)
{
if(n&1) I = mul(I,a);
n>>=1;
a = mul(a,a);
}
return I;
}
int main()
{
int t;
cin>>t;
int f[4];
f[0] = 1,f[1] =3,f[2] = 5,f[3] = 4;
int cas=1;
while(t--)
{
int n;
cin>>n;
mat tmp;
memset(tmp.a,0,sizeof(tmp.a));
tmp.a[0][0] = tmp.a[0][1] = tmp.a[2][1] = tmp.a[3][2] = 1;
tmp.a[1][1] = 3,tmp.a[1][2] = 2,tmp.a[1][3] = 7;
printf("Case %d: ",cas++);
if(n==0) cout<<1<<endl;
else if(n==1) cout<<3<<endl;
else if(n==2) cout<<5<<endl;
else
{
tmp = mpower(tmp,n-2);
int sum=0;
for(int i=0;i<4;i++)
{
sum = (sum+tmp.a[0][i]*f[3-i])%mod;
sum = (sum+tmp.a[1][i]*f[3-i])%mod;
}
cout<<sum<<endl;
}
}
return 0;
}