题目链接:poj 3734
这道题用矩阵乘法优化DP。
考虑到直接转移的话,N太大,会TLE。由于转移的方案数,转移的状态很少,所以可以将转移的方案用矩阵来表示。
设dp[i][k]表示涂到第i个格子,状态为k的方案数。其中状态k的定义为:
k=1:红色和绿色都为奇数,k=2:红奇绿偶,k=3:红偶绿奇,k=4:红偶绿偶
DP方程自己写。
表示为矩阵为:
2 1 1 0
1 2 0 1
1 0 2 1
0 1 1 2
然后做矩阵快速幂即可。
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define mod (10007)
struct node{
int a[10][10];
node(){
memset(a,0,sizeof(a));
}
}S;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
node mut(node x,node y){
node t;
for(int i=1;i<=4;i++)
for(int j=1;j<=4;j++)
for(int p=1;p<=4;p++)
t.a[i][j]=(t.a[i][j]+x.a[i][p]*y.a[p][j])%mod;
return t;
}
node pow(node x,int y){
node t;
for(int i=1;i<=4;i++)t.a[i][i]=1;
while(y){
if(y&1)t=mut(t,x);
y>>=1;
x=mut(x,x);
}
return t;
}
int main(){
freopen("test.in","r",stdin);
freopen("test.out","w",stdout);
S.a[1][1]=2; S.a[1][2]=1; S.a[1][3]=1; S.a[1][4]=0;
S.a[2][1]=1; S.a[2][2]=2; S.a[2][3]=0; S.a[2][4]=1;
S.a[3][1]=1; S.a[3][2]=0; S.a[3][3]=2; S.a[3][4]=1;
S.a[4][1]=0; S.a[4][2]=1; S.a[4][3]=1; S.a[4][4]=2;
int T=read();
while(T--){
int N=read();
node ans=pow(S,N);
printf("%d\n",ans.a[4][4]);
}
return 0;
}