题解 - [POJ 3734] Gaussian Prime Factors

题目链接

原始题面

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

1
2
3
2
1
2

Sample Output

1
2
2
6

Source

PKU Campus 2009 (POJ Monthly Contest – 2009.05.17), Simon

题意简述

\(n\) 个方块排成一排,每个方块都要染上红绿蓝黄四种颜色之一,求红色方块和绿色方块个数均为偶数的染色方案数

解题思路

法一 (容斥 + 二项式 / 多项式定理)

显然答案应为

无限制的方案数 - 红色方块为奇数的方案数 - 绿色方块为奇数的方案数 + 红色和绿色方块均为奇数的方案数

\[ 4^n-2A+B\tag{1} \]

其中

  • \[ A=\sum_{i=1}^{\lceil\frac{n}{2}\rceil} \binom{n}{2i-1}3^{n-2i+1}\tag{2} \]
  • \[ B=\sum_{i=1}^{\lceil\frac{n}{2}\rceil}\sum_{j=1}^{\lceil\frac{n}{2}\rceil} \frac{n!}{(2i-1)!(2j-1)!(n-2i-2j+2)!}2^{n-2i-2j+2}\tag{3} \]

由二项式定理和多项式定理,有

  • \[ A=\frac{(3+1)^n-(3-1)^n}{2}\tag{4} \]
  • \[ B=\frac{(2+1+1)^n-(2+1-1)^n-(2-1+1)^n+(2-1-1)^n}{4}\tag{5} \]

\(\text{(4)}\), \(\text{(5)}\) 代入 \(\text{(1)}\), 则答案为

\[ 4^{n-1}+2^{n-1} \]

法二 (EGF)

设红色,绿色,蓝色,黄色对应的 EGF 分别为 \(F_r,F_g,F_b,F_y\)

  • \[ F_r=F_g=\sum_{i=0}^{\lfloor\frac{n}{2}\rfloor}{x^{2i}\over (2i)!}={e^x+e^{-x}\over2}-o(x^n) \]
  • \[ F_b=F_y=\sum_{i=0}^n\frac{x^i}{i!}=e^x-o(x^n) \]

令合法方案对应的 EGF 为 \(G\), 显然 \(\partial G\leqslant n\), 则有

\[ \begin{aligned} G&=F_rF_gF_bF_y\\ &={e^{4x}+2e^{2x}+1\over4}-o(x^n)\\ &=\frac{1}{4}+\frac{1}{4}\sum_{i=0}^n(4^i+2^{i+1})\frac{x^i}{i!} \end{aligned} \]

由于 \(n\geqslant 1\), 所以我们可以忽略掉 \(G\) 的常数项,则答案为

\[ {4^n+2^{n+1}\over4}=4^{n-1}+2^{n-1} \]

法三 (DP + 矩阵快速幂)

\(F_i=(f_{i1},f_{i2},f_{i3},f_{i4})^T\) 表示染色序列长度为 \(i\) 时的状态,其中

  • \(f_{i1}\): 红色为偶数,绿色为偶数的方案数
  • \(f_{i2}\): 红色为奇数,绿色为偶数的方案数
  • \(f_{i3}\): 红色为偶数,绿色为奇数的方案数
  • \(f_{i4}\): 红色为奇数,绿色为奇数的方案数

\[ F_i=\begin{bmatrix} 2&1&1&0\\ 1&2&0&1\\ 1&0&2&1\\ 0&1&1&2 \end{bmatrix}F_{i-1} \]