POJ_3734_Blocks_矩阵快速幂

终于够十道题了,险些请队友吃饭,还好我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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值