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⁹) 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
Problem Analysis:
Because the number of different ways to paint the blocks is large, we can use dynamic programming to count it.
Support we have count the number of paint i blocks, let A(i) denote the number of ways that red and green blocks be even, let B(i) denote the number of ways that one of red and green blocks is even, let C(i) denote red and green blocks be odd.
Then A(i+1) = 2A(i) + B(i), B(i+1) = 2A(i)+2B(i)+2C(i), C(i+1) = B(i)+2C(i).
Solution
#include <cstdio>
#include <vector>
#include <algorithm>#define M 10007using namespace std;vector<vector<int>> multiply(vector<vector<int>>& a, vector<vector<int>>& b) {
vector<vector<int>> res(3 ,vector<int>(3, 0));
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
res[i][j] += a[i][k] * b[k][j];
res[i][j] %= M;
}
}
} return res;
}int main(int argc, char *argv[]) {
int times;
scanf("%d", ×);
while (times--) {
getchar();
int n;
scanf("%d", &n); vector<vector<int>> a(3 ,vector<int>(3, 0));
a[0][0] = 2;
a[0][1] = 1;
a[1][0] = 2;
a[1][1] = 2;
a[1][2] = 2;
a[2][1] = 1;
a[2][2] = 2; vector<vector<int>> res(3 ,vector<int>(3, 0));
res[0][0] = 1;
res[1][1] = 1;
res[2][2] = 1; while (n > 0) {
if (n & 1) res = multiply(res, a);
n >>= 1;
a = multiply(a, a);
} printf("%d\n", res[0][0]);
} return 0;
}
time complexity is O(logn)
space complexity is O(1)