解题报告——状压dp

用二进制来表示状态,用位运算来转移状态

1.Mondriaan's Dream

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.

这题有两种解法,记录比较简单的轮廓线法。

状态是 i 行 j 列的这个单位 在 k 的状态下的方案数, 满足 i-1, j-1前的每一个都放满了

我们用滚动数组优化, 上一个状态存的是左边一个点在各个方法下的方案数。

枚举该矩形的每一个点,用(1<<m)-1种状态来转移有三种转移方法。

1、竖着放 要求不在顶行并且状态的首位为0

2、横着放 要求不在行头且状态的尾为 0

3、不放 要求必须状态的首位不为0 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int MAXN=11;
ll dp[2][1<<MAXN];
int main()
{
    int m,n;
    while (scanf("%d%d",&m,&n))
    {
        if (m==n && n==0) break;
        int cur=0;
        memset(dp,0,sizeof(dp));
        dp[cur][(1<<n)-1]=1;
        for (int i=1;i<=m;i++)
        for (int j=1;j<=n;j++)
        {
            cur^=1;
            memset(dp[cur],0,sizeof(dp[cur]));
            for (int k=0;k<=(1<<n)-1;k++)
            {
                if (i!=1 && !(k&(1<<(n-1)))) // 竖放
                {
                    int now=(((k<<1)|1)&((1<<n)-1));
                    dp[cur][now]+=dp[1-cur][k];
                }   
                if (k&(1<<(n-1)))  //  不放
                {
                    int now=((k<<1)&((1<<n)-1));
                    dp[cur][now]+=dp[1-cur][k];
                }
                if (j!=1 && (k&(1<<(n-1))) && !(k&1)) //横放
                {
                    int now=(((k<<1)|3)&((1<<n)-1));
                    dp[cur][now]+=dp[1-cur][k];
                } 
            }
        }
    cout<<dp[cur][(1<<n)-1]<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/gjc2561571372/article/details/81121346