POJ 3734 Blocks(矩阵快速幂)

来源:互联网 发布:淘宝关键词top100 编辑:程序博客网 时间:2024/05/29 16:39

Blocks
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 6321 Accepted: 3037

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


题意: 给出n个方块排成一列。现在要用红,黄,蓝,绿四种颜色给这些方块上色。 求染成红色的方块和染成绿色的方块的个数同时为偶数的染色方案的个数?



啊啊啊,又懒又蠢的纯真啊 (╯‵□′)╯︵┻━┻   乱刷了1000+的题,还是蔡茹苟啊,赶紧补一补知识点。


先说说怎么学矩阵快速幂吧:

① 了解矩阵和矩阵乘法,(弱线代没去过/(ㄒoㄒ)/~~)

②了解快速幂,推荐《挑战》P.122       

③可以直接看快速幂啦,推荐 《挑战》 P.199

  

在矩阵快速幂求解问题时,最重要的是找到递推矩阵。找递推矩阵时有常用到dp的思想。 



题解:我们从左往右开始依次染色。 设染到第 i 个方块为止,红绿都是偶数的方案数为ai, 红绿恰有一个是偶数的方案数为bi,  红绿都是奇数的方案数为ci。 这样到 i+1 个方块为止,红绿都是偶数的方案有如下几种可能:


1.到第 i 个方块为止红绿都是偶数,并且第 i+1 个方块染成了蓝色或者黄色

2.到第i个方块为止红绿恰好有一个是奇数,并且第 i+1 个方块染成了奇数个对应的那种颜色

因此可以得到递推式为:  ai+1 = 2*a+ bi      同理可得:   bi+1= 2*ai + 2*bi+2*ci      ci+1 = bi + 2*ci  


递推式用矩阵表示为    ai                               2     1    0          ai-1

                                     bi         =                   2     2    2     *    bi-1

                                     ci                              0     1    2            ci-1


a=  2              b0 =0              c0 = 0  


代码如下: 


#include <iostream>#include <stdio.h>#include <cstring>#include <vector>#include <algorithm>using namespace std;typedef vector<int> vec;typedef vector<vec> mat;const int mod = 10007;#define LL long longmat mul(mat &A, mat &B)//矩阵乘法 {mat C(A.size(), vec(B[0].size()));for(int i=0; i<A.size(); ++i){for(int k=0; k<B.size(); ++k){for(int j=0; j<B[0].size(); ++j)C[i][j] = (C[i][j] + A[i][k]*B[k][j]) % mod;}}return C;}mat quick_pow(mat A, LL n)//快速幂 {mat B(A.size(), vec(A.size()));for(int i=0; i<A.size(); ++i)B[i][i]=1;while(n>0){if(n&1)B = mul(B, A);A = mul(A, A);n>>=1;}return B;}int main(){int t;LL n;scanf("%d",&t);while(t--){scanf("%lld",&n);mat A(3, vec(3));A[0][0]=2; A[0][1]=1; A[0][2]=0;A[1][0]=2; A[1][1]=2; A[1][2]=2;A[2][0]=0; A[2][1]=1; A[2][2]=2;A = quick_pow(A, n);printf("%d\n",A[0][0]);}return 0;}




 

0 0