poj3734 Blocks[矩阵优化dp or 组合数学]
Posted 神犇(shenben)
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj3734 Blocks[矩阵优化dp or 组合数学]相关的知识,希望对你有一定的参考价值。
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6578 | Accepted: 3171 |
Description
Panda has received an assignment of painting a line of blocks. Since Panda is such an intelligent boy, he starts to think of a math problem of painting. Suppose there are N blocks in a line and each block can be paint red, blue, green or yellow. For some myterious reasons, Panda want both the number of red blocks and green blocks to be even numbers. Under such conditions, Panda wants to know the number of different ways to paint these blocks.
Input
The first line of the input contains an integer T(1≤T≤100), the number of test cases. Each of the next T lines contains an integer N(1≤N≤10^9) indicating the number of blocks.
Output
For each test cases, output the number of ways to paint the blocks in a single line. Since the answer may be quite large, you have to module it by 10007.
Sample Input
2 1 2
Sample Output
2 6
Source
//f[i]=6*f[i-1]-8*f[i-2]{i>=3,f[1]=2,f[2]=6} #include<cstdio> #include<cstring> typedef long long ll; using namespace std; const ll mod=10007; struct matrix{ ll s[2][2]; matrix(){ memset(s,0,sizeof s); } }A,F;int n,T; matrix operator *(const matrix &a,const matrix &b){ matrix c; for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ for(int k=0;k<2;k++){ c.s[i][j]+=a.s[i][k]*b.s[k][j]; c.s[i][j]%=mod; } } } return c; } matrix fpow(matrix a,int p){ matrix res; for(int i=0;i<2;i++) res.s[i][i]=1; for(;p;p>>=1,a=a*a) if(p&1) res=res*a; return res; } int main(){ for(scanf("%d",&T);T--;){ scanf("%d",&n); if(n==1){puts("2");continue;} if(n==2){puts("6");continue;} A.s[0][0]=6;A.s[0][1]=-8; A.s[1][0]=1;A.s[1][1]=0; F.s[0][0]=6;F.s[0][1]=0; F.s[1][0]=2;F.s[1][1]=0; A=fpow(A,n-2); F=A*F; printf("%lld\n",(F.s[0][0]+mod)%mod); } return 0; }
方法2:
//f(n)=2^(2n-2)+2^(n-1) #include<cstdio> #include<cstring> typedef long long ll; using namespace std; const ll mod=10007; ll ans=0;int T,n; ll fpow(ll a,ll p){ ll res=1; for(;p;p>>=1,a=a*a%mod) if(p&1) res=res*a%mod; return res; } int main(){ for(scanf("%d",&T);T--;){ scanf("%d",&n); ans=fpow(2,n-1<<1)+fpow(2,n-1); printf("%I64d\n",(ans+mod)%mod); } return 0; }
以上是关于poj3734 Blocks[矩阵优化dp or 组合数学]的主要内容,如果未能解决你的问题,请参考以下文章