POJ3420_Quad Tiling_矩阵与递推

Quad Tiling
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 4363 Accepted: 1996

Description

Tired of the Tri Tiling game finally, Michael turns to a more challengeable game, Quad Tiling:

In how many ways can you tile a 4 × N (1 ≤ N ≤ 109) rectangle with 2 × 1 dominoes? For the answer would be very big, output the answer modulo M (0 < M ≤ 105).

Input

Input consists of several test cases followed by a line containing double 0. Each test case consists of two integers, N and M, respectively.

Output

For each test case, output the answer modules M.

Sample Input

1 10000
3 10000
5 10000
0 0

Sample Output

1
11
95

用 1 * 2 的砖铺满 4 * n 的地面,其中砖旋转 90 度,求有多少种铺法。

用递推,观察铺满第 i 列之后,i+1 列总共有 16 种状态。我们要求的是铺满第 n 列后,n + 1 列为空的状态。

因此,从为空的这一状态出发,求状态转移的递推式子。最后发现只有 6 种情况参与了递推,其中有两种还可以合并。由此写处了 5 阶转移方阵。

起始时,铺满第 0 列后第 1 列的状态为空,所以为空的种数是 1, 其他都是 0.

最后用矩阵快速幂进行变换就好了。


#include<cstdio>
#include<iostream>
#include<vector>

using namespace std;

typedef vector<int> vec;
typedef vector<vec> mat;

int n, m;

mat Mul(mat A, mat B)
{
	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 Pow(mat A, int n)
{
	mat B(A.size(), vec(A.size()));
	for(int i= 0; i< A.size(); i++)
		B[i][i] = 1;

	while(n)
	{
		if(n & 1) B = Mul(B, A);
		A = Mul(A, A);
		n = n >> 1;
	}

	return B;
}

int main()
{
	mat A(5, vec(1));
	A[0][0] = 1;

	mat B(5, vec(5));
	B[0][0] = B[0][1] = B[0][2] = B[0][3] = 1;
	B[1][0] = 1;
	B[2][0] = B[2][4] = 1;
	B[3][0] = 2, B[3][3] = 1;
	B[4][2] = 1;

	while(scanf("%d %d", &n, &m), m)
	{
		mat res(5, vec(1));
		res = Mul(Pow(B, n), A);
		printf("%d\n", res[0][0]);
	}

	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值