您的位置:首页 > 其它

POJ_3734_Blocks_矩阵快速幂

2014-11-10 01:10 316 查看
终于够十道题了,险些请队友吃饭,还好我TM机智

题意:

给N个方块排成一列,用红蓝绿黄四种颜色给方块染色。求红色方块与绿色方块的个数同时为偶数的方案个数,输出对10007取模后的答案。

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.

知道是矩阵快速幂以后就十分简单,主要是要会想到矩阵快速幂。

很多时候可以发现数学递推公式,也就是动态规划状态转移方程,如果递推要求步数很多,并且递推方程是线性的,那么就可以用线性代数来解决,用快速幂算法大大缩短时间。利用矩阵实质依赖的是抽象出递推过程中的元素,这样就可以先求出这些作用叠加的效果,再作用在原项上。

不得不说世界的奥秘写在数学里这句话真的很美妙。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
#define mod 10007
int n;
struct matrix{
int a[4][4];
matrix(){
memset(a,0,sizeof(a));
}
matrix operator * (const matrix& in)const{
matrix ret;
for(int i=0;i<4;++i)
for(int j=0;j<4;++j)
for(int k=0;k<4;++k){
ret.a[i][j]+=a[i][k]*in.a[k][j];
ret.a[i][j]%=mod;
}
return ret;
}
}M,N,I;
matrix quick_power(matrix in,int n){
if(!n)	return I;
if(n==1)	return in;
matrix tem=quick_power(in,n/2);
if(n%2)	return tem*tem*in;
return tem*tem;
}
void init(){
for(int i=0;i<4;++i){
M.a[i][i]=2;
I.a[i][i]=1;
}
M.a[0][1]=M.a[0][2]=M.a[1][0]=M.a[1][3]=M.a[2][0]=M.a[2][3]=M.a[3][1]=M.a[3][2]=1;
N.a[0][0]=2;
N.a[1][0]=N.a[2][0]=1;
}
int solve(){
matrix ans=quick_power(M,n-1);
ans=ans*N;
return ans.a[0][0];
}
int main(){
init();
int cs;
scanf("%d",&cs);
while(cs--){
scanf("%d",&n);
printf("%d\n",solve());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: