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;
}