Quad Tiling
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3327 | Accepted: 1435 |
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
题意:用2*1的小方格覆盖4*N的长方形,问有多少种组合情况。
思路:如果不用公式的话,就是16*16的矩阵。公式是f(n)=f(n-1)+5*f(n-2)+f(n-3)-f(n-4)。
AC代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
struct node
{
ll f[5][5];
};
node a,b,c,first,ret;
ll MOD;
node mul(node A,node B)
{
node C;
int i,j,k;
for(i=1;i<=4;i++)
for(j=1;j<=4;j++)
{
C.f[i][j]=0;
for(k=1;k<=4;k++)
C.f[i][j]=(C.f[i][j]+A.f[i][k]* B.f[k][j])%MOD;
C.f[i][j]=(C.f[i][j]+MOD*2)%MOD;
}
return C;
}
int main()
{
int n,i,j,p,k;
a.f[1][1]=36;a.f[1][2]=11;a.f[1][3]=5;a.f[1][4]=1;
b.f[1][1]=1;b.f[1][2]=1;
b.f[2][1]=5;b.f[2][3]=1;
b.f[3][1]=1;b.f[3][4]=1;
b.f[4][1]=-1;
while(~scanf("%d %I64d",&n,&MOD) && n>0)
{
if(n<=4)
{
printf("%I64d\n",a.f[1][4-n+1]%MOD);
continue;
}
first=b;ret=b;
p=n-5;
while(p)
{
if(p&1)
ret=mul(ret,first);
first=mul(first,first);
p/=2;
}
ret=mul(a,ret);
printf("%I64d\n",ret.f[1][1]);
}
}