Blocks(POJ 3734)
- 原题如下:
Blocks
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8020 Accepted: 3905 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
- 题解:从最左边开始染色,设染到第i个方块为止,红绿都是偶数的方案数为ai,红绿恰有一个是偶数的方案数为bi,红绿都是奇数的方案数为ci。这样,染到第i+1个方块为止,红绿都是偶数的方案数有两种可能:①到第i个方块为止红绿都是偶数,并且第i+1个方块染成了蓝色或者黄色 ② 到第i个方块为止红绿恰有一个是奇数, 并且第i+1个方块染成了奇数个对应的那种颜色。因此有递推式ai+1=2*ai+bi,同样地,有bi+1=2*ai+2*bi+2*ci,ci+1=bi+2*ci,把ai,bi,ci的递推式用矩阵表示如下:
因此就有:
- 代码:
1 #include <cstdio> 2 #include <cctype> 3 #define number s-'0' 4 #include <cstring> 5 #include <vector> 6 7 using namespace std; 8 9 typedef vector<int> vec; 10 typedef vector<vec> mat; 11 12 const int M=10007; 13 int N; 14 15 void read(int &x) 16 { 17 char s; 18 x=0; 19 bool flag=0; 20 while (!isdigit(s=getchar())) 21 (s=='-')&&(flag=true); 22 for (x=number; isdigit(s=getchar());x=x*10+number); 23 (flag)&&(x=-x); 24 } 25 26 void write(int x) 27 { 28 if (x<0) 29 { 30 putchar('-'); 31 x=-x; 32 } 33 if (x>9) write(x/10); 34 putchar(x%10+'0'); 35 } 36 37 mat mul(mat &A, mat &B) 38 { 39 mat C(A.size(), vec(B[0].size())); 40 for (int i=0; i<A.size(); i++) 41 { 42 for (int j=0; j<B[0].size(); j++) 43 { 44 for (int k=0; k<B.size(); k++) 45 { 46 C[i][j]=(C[i][j]+A[i][k]*B[k][j])%M; 47 } 48 } 49 } 50 return C; 51 } 52 53 mat pow(mat A, int n) 54 { 55 mat B(A.size(), vec(A.size())); 56 for (int i=0; i<A.size(); i++) B[i][i]=1; 57 while (n>0) 58 { 59 if (n&1) B=mul(B, A); 60 A=mul(A, A); 61 n>>=1; 62 } 63 return B; 64 } 65 66 int main(int argc, char * argv[]) 67 { 68 int t; 69 read(t); 70 while (t>0) 71 { 72 t--; 73 read(N); 74 mat A(3, vec(3)); 75 A[0][0]=2;A[0][1]=1;A[0][2]=0; 76 A[1][0]=2;A[1][1]=2;A[1][2]=2; 77 A[2][0]=0;A[2][1]=1;A[2][2]=2; 78 A=pow(A, N); 79 printf("%d\n",A[0][0]); 80 } 81 }