HDU 1992 Tiling a Grid With Dominoes (状压dp)

Tiling a Grid With Dominoes

Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 634    Accepted Submission(s): 482

Problem Description
We wish to tile a grid 4 units high and N units long with rectangles (dominoes) 2 units by one unit (in either orientation). For example, the figure shows the five different ways that a grid 4 units high and 2 units wide may be tiled.



Write a program that takes as input the width, W, of the grid and outputs the number of different ways to tile a 4-by-W grid.
Input
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow.
Each dataset contains a single decimal integer, the width, W, of the grid for this problem instance.
Output
For each problem instance, there is one line of output: The problem instance number as a decimal integer (start counting at one), a single space and the number of tilings of a 4-by-W grid. The values of W will be chosen so the count will fit in a 32-bit integer.
Sample Input
  
  
3 2 3 7
Sample Output
  
  
1 5 2 11 3 781
Source
Recommend
linle   |   We have carefully selected several similar problems for you:  1993 1396 1995 1143 1991 

题解:对于这种铺砖问题,第一想到的应该是递推(dp)。这题我们可以一行一行地分析即一行一行地铺。因为只有1*2的砖。所以当前处理行只会受到上一行的影响。这个画下图就知道了。所以对于当前处理行的状态我们可以用01序列来表示。第 i 位为1表示第i个位置会占用下一行的位置,即砖是竖着放的。0表示不占用下一行的位置,0肯定是成对出现的,因为横放的话需要两个位置。那么我们就可以开始搞了,用dp[ i ][ cur ]表示处理完前 i 行,第 i 行当前状态为 cur 的方法数。cur 为01序列的十进制表示。然后我们可以根据当前状态 cur 用dfs构造出一个下一个可行状态nex。那么dp[ i+1 ][ nex ] += dp[ i ] [ cur ]。所以我们只需要枚举第 i行状态递推到 i+1行就行了。最后只要输出dp[n][0]就行了。因为最后一行不能占用下一行的位置。
明显的状压dp。
因为只有4行,用4个01位表示一行,如果是0表示这一行不会占用下一行,如果是1表示会占用下一行。那么转移状态有3种:
1,当前行的当前位为1,那么占用了下一行,那么直接转移到下一位。
2,当前行的当前位为0,那么可以表示下一行可以为1.
3,当前行的当前位 和 下一位都为00,那么下一行也可以为00。

AC代码:
#include<bits/stdc++.h>
using namespace std;

int dp[1005][16];
//dp[i][s]表示处理完前i行,第i行状态为s的方法数.
void dfs(int r,int c,int cur,int nex)
//分别表示当前行,当前列,当前状态,可转移的状态
{
    if(c>3) //一行已经处理完 
    {
        dp[r+1][nex] += dp[r][cur];
        return;
    }
    if(cur&(1<<c) )
    {
    	dfs(r,c+1,cur,nex);   //位置被上一行的占用    
    }
    else
	{
    	dfs(r,c+1,cur,nex|(1<<c));   //竖着放,用1
        if(c<=2 && !(cur & (1<<(c+1))))
            dfs(r,c+2,cur,nex);  //横着放,两个0
	} 
}

int main()
{
    memset(dp,0,sizeof(dp));
    dp[0][0]=1;
    int i,j;
    for(i=0;i<22;i++)   //22已经爆int32了
        for(j=0;j<16;j++)
            if(dp[i][j])
                dfs(i,0,j,0);

    int t,n;
    int cas=1;
    scanf("%d",&t);
    while(t--)
    {
    	scanf("%d",&n);
    	printf("%d %d\n",cas++,dp[n][0]);
	}
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值