您的位置:首页 > 其它

POJ 3734 Blocks(矩阵快速幂)

2016-09-28 21:01 363 查看
题目链接:http://poj.org/problem?id=3734

Time Limit: 1000MS Memory Limit: 65536K

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个方块排成一列,用红蓝绿黄四种颜色的油漆给方块染色。求红色方块和绿色方块的个数同时为偶数的方案数。

设ai为前i个方块中红绿都是偶数的方案数,bi为红绿当中恰好有一中颜色个数为偶数的方案数,ci为红绿都是奇数的方案数。则ai+1可能是在ai的基础上在i+1的位置涂了蓝色或者黄色,所以这一部分的方案数是2*ai,也有可能是在bi的基础上在i+1的位置涂了红绿当中数量为奇数的那一种,这一部分方案数为bi,而从ci出发,不可能使红绿的个数均为偶数。

由此得到ai+1=2*ai+bi。

同理可以得到bi+1=2*ai+2*bi+2*ci

以及ci+1=bi+1+2*ci

写成矩阵的形式

⎡⎣⎢ai+1bi+1ci+1⎤⎦⎥=⎡⎣⎢220121022⎤⎦⎥⎡⎣⎢aibici⎤⎦⎥

通过矩阵快速幂可以得到答案,具体见代码注释。

AC代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<string>
#include<queue>
#include<sstream>
#include<list>
#include<stack>
#define ll long long
#define ull unsigned long long
#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)
#define rrep(i,a,b) for(int i=(a),_ed=(b);i>=_ed;i--)
#define fil(a,b) memset((a),(b),sizeof(a))
#define cl(a) fil(a,0)
#define PI 3.1415927
#define inf 0x3f3f3f3f
using namespace std;
typedef vector<int> vec;
typedef vector<vec> mat;
const int M = 10007;
mat mul(mat &A, mat &B)//矩阵相乘,答案保存在C矩阵中返回
{
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]) % M;
}
}
}
return C;
}
mat matpow(mat A, ll n)//矩阵快速幂
{
mat B(A.size(), vec(A[0].size()));
for (int i = 0;i < A.size();++i) B[i][i] = 1;
while (n > 0)//运用位运算计算快速幂,答案保存在B数组中
{
if (n & 1) B = mul(B, A);
A = mul(A, A);
n >>= 1;
}
return B;
}
int main(void)
{
int T;
ll n;
cin >> T;
while (T--)
{
cin >> 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 = matpow(A, n);
cout << A[0][0] << endl;
}
return 0;
}


2016年9月28日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 矩阵快速幂 acm