Quad Tiling - POJ 3420 矩阵递推

3 篇文章 0 订阅

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

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值