Quad Tiling
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 4057 | Accepted: 1846 |
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
题意:给你4 × N矩形,用2 × 1骨牌填充,求有多少不同的种填充方法?
解题思路:
将矩形竖着看,变为了列为4,行为N的矩形,通过分析我们可以分为如下几种情况:
我们将上面六种情况分别用六个数组代替:A1,A2,A3,A4,A5,A6
针对将第N行填满的情况,A6[n] = A1[n-1]+A2[n-1]+A4[n-1]+A5[n-1]+A6[n-1].
为何?
第一种情况:我们只需要在空白处横着填充一个2 × 1的骨牌就可以了
第二种情况: 我们不需要填充直接传递过来就可以了
第三种情况不能传递
第四种情况:空白部分填充一个2 × 1的骨牌就可以了
第五种情况:空白部分填充一个2 × 1的骨牌就可以了
第六种情况:空白部分填充填充两个2 × 1的骨牌就可以了
如此我们就可以了列出矩阵:
A_mat:{
1 1 1 2 0
1 0 0 0 0
1 0 0 0 1
1 0 0 1 0
0 0 1 0 0
}
初始矩阵B:{1 0 0 0 0};
如此用矩阵快速幂求得结果即可
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; int mod; typedef long long LL; typedef vector<LL>vec; typedef vector<vec>mat; 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]) % mod; } } } return C; } mat pow(mat A, LL 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 >>= 1; } return B; } LL n, m; int main() { while(~scanf("%I64d%I64d",&n, &m), n || m) { mat A(6, vec(6)), B(1, vec(5)); mod = m; A[0][0]=A[0][1]=A[0][2]=1; A[0][3]=2; A[1][0]=A[2][0]=A[2][4]=1; A[3][0]=A[3][3]=1; A[4][2]=1; B[0][0]=1; A = pow(A, n); B = mul(A, B); printf("%I64d\n", B[0][0]); } return 0; }