Blocks
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 3997 |
|
Accepted: 1775 |
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
PKU Campus 2009 (POJ Monthly Contest ? 2009.05.17), Simon
题目大意: 有一排砖,数量为N。现要将砖全部染上色,有红、蓝、绿、黄四种颜色。要求被染成红色和绿色的砖块数量必须为偶数,问一共有多少种染色方案。(由于答案较大,模10007)
解题思路: 这道题有两种思路,一个是采用dp的思想,然后转化为矩阵。另一个是组合数学的思想。 dp: 用dp[N][4]来表示N块砖块的染色情况,一共有四种状态。 1. dp[N][0] :表示N块中红色绿色的数量均为偶数。 2. dp[N][1] :表示N块中红色为偶数,绿色为奇数。 3. dp[N][2] :表示N块中红色为奇数,绿色为偶数。
4. dp[N][3] :表示N块中红色绿色的数量均为奇数。
而状态转移方程为: dp[N+1][0] = 2 * dp[N][0] + 1 * dp[N][1] + 1 * dp[N][2] + 0 * dp[N][3] dp[N+1][1] = 1 * dp[N][0] + 2 * dp[N][1] + 0 * dp[N][2] + 1 * dp[N][3]
dp[N+1][2] = 1 * dp[N][0] + 0 * dp[N][1] + 2 * dp[N][2] + 1 * dp[N][3]
dp[N+1][3] = 0 * dp[N][0] + 1 * dp[N][1] + 1 * dp[N][2] + 2 * dp[N][3]
上述的转移方程可以转化为矩阵: |2 1 1 0| |1 2 0 1| |1 0 2 1| |0 1 1 2|
代码:
/*
ID: wuqi9395@126.com
PROG:
LANG: C++
*/
#include
组合数学: 如果没有限制,一共有4 ^ n 次。现在考虑有 k 块被染为红色或绿色,且在k块中,一定有红色或绿色或两者均为奇数的情况。将这些情况减去,即是想要的答案。(1<= k <= n) 从n块中选择k块,为c(n, k)。 而从k块中选择不符合的情况染色,需要对k进行奇偶讨论。 如果k为奇数,红色和绿色的数量为一奇一偶:2 * (c(k, 1) + c(k, 3) + c(k, 5) +……)* c(n, k) * 2^(n - k) (其中要乘以2,是因为可以分别选择红、绿色为奇数) 如果k为偶数,红色和绿色的数量全部为奇数:(c(k, 1) + c(k, 3) + c(k, 5) +……)* c(n, k) * 2^(n - k) (这里不需要乘以2) 而 c(k, 1) + c(k, 3) + c(k, 5) +…… = 2^(k - 1) 所以,最后的表达式为: 4^n - 2^n*c(n, 1) - 2^(n - 1)*c(n, 2) - 2^n*c(n, 3) - 2^(n-1)*c(n, 4)-…… = 4^n - 2^n*2^(n-1) - 2^(n-1)*(2^(n-1)-1) = 4^(n-1) + 2^(n-1)
代码:
/*
ID: wuqi9395@126.com
PROG:
LANG: C++
*/
#include