状压DP进阶-POJ2411

本题题解我借鉴了Stephen__的博客的做法。
上题目Mondriaan’s Dream

题目描述

用1×2的长方形铺满一个h×w的大长方形,问有多少种铺法?
Mondriaan’s Dream
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 10549 Accepted: 6135
Description
Squares and rectangles fascinated the famous Dutch painter Piet Mondriaan. One night, after producing the drawings in his ‘toilet series’ (where he had to use his toilet paper to draw on, for all of his paper was filled with squares and rectangles), he dreamt of filling a large rectangle with small rectangles of width 2 and height 1 in varying ways.
Expert as he was in this material, he saw at a glance that he’ll need a computer to calculate the number of ways to fill the large rectangle whose dimensions were integer values, as well. Help him, so that his dream won’t turn into a nightmare!
Input
The input contains several test cases. Each test case is made up of two integer numbers: the height h and the width w of the large rectangle. Input is terminated by h=w=0. Otherwise, 1<=h,w<=11.
Output
For each test case, output the number of different ways the given rectangle can be filled with small rectangles of size 2 times 1. Assume the given large rectangle is oriented, i.e. count symmetrical tilings multiple times.
Sample Input
1 2
1 3
1 4
2 2
2 3
2 4
2 11
4 11
0 0
Sample Output
1
0
1
2
3
5
144
51205

解析

用1×2的长方形铺满h×w的大长方形。对于第i行的第j个点,有3种情况。
一,由i-1行第j个点竖铺将该点铺上。
二,由i行j-1或j点横铺将该点铺上。
三,由i行j点竖铺将该点铺上。
现在将这三种情况用0和1表示:
第i行的第j个点竖铺(也就是第1种情况),则第i行的第j个点为0。
否则第i行的第j个点(也就是第2,3种情况)为1。
听起来很复杂?读多几遍就明白了。
代码中要使用两个位运算符号&和|
一,使用|运算:如果需要达到第i+1行的第j个点状态为0,那么i行该点不能是0,否则两列竖放重叠。所以i行该点只能是1,也就是i|j一定每列都得是1。
二,使用&运算:如果需要达到第i+1行的第j个点状态为1,那么i行该点可以是1或0。但是若两个点状态都是1,那么还需判断i和i+1行的j+1点是否也都是1,因为这样才满足题设1×2横铺。
最终状态必须都达到一行中所有点都为1

代码

#include<cstdio>
#include<cstring>
#define N (1<<11)+1
using namespace std;
int n,m;
long long tmp[N],dp[N],tol;
bool b[N];
bool check(int i)//找出1×2横铺合法状态
{
    while(i)
    {
        if(i&1)
        {
            i>>=1;
            if(!(i&1))return 0;
            i>>=1;
        }else i>>=1;
    }
    return 1;
}
void init()
{
    for(int i=0;i<tol;i++)
        if(check(i))tmp[i]=1,b[i]=1;
}
int main()
{
    while(~scanf("%d%d",&n,&m),n+m)
    {
        memset(b,0,sizeof(b));
        memset(tmp,0,sizeof(tmp));
        memset(dp,0,sizeof(dp));
        tol=(1<<m);
        init();
        for(int k=2;k<=n;k++)
        {
            memset(dp,0,sizeof(dp));
            for(int i=0;i<tol;i++)
                for(int j=0;j<tol;j++)
                {
                    if((i|j)!=(tol-1))continue;//位运算|
                    if(!b[i&j])continue;//位运算&
                    dp[i]+=tmp[j];                 
                }
            for(int i=0;i<tol;i++)tmp[i]=dp[i];
        }
        printf("%lld\n",tmp[tol-1]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值