poj2411 Mondriaan's Dream 状压dp 经典入门题

荷兰画家Piet Mondriaan在一次梦境中构想了一个数学问题,即用2x1的小矩形填充一个大的矩形有多少种方式。此问题涉及到动态规划算法,通过递归函数和状态压缩来计算不同填充方式的数量。

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

Source

Ulm Local 2000

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;

typedef long long ll;
int n, m;	//n,m分别代表棋盘的长宽
ll dp[1005][(1<<11)+5];	//dp[I][j]用于存储填充i-1列状态为j时,i列可能出现的方法数
void dfs(int i,int j,int state,int next){//这里I代表列数,j代表当前位数(也可以说是行数-1,初始时为0),state代表状态数,next代表下一列出现的状态
    if (j==n){
        dp[i+1][next]+=dp[i][state];
        return;
    }

    if (((1<<j)&state)>0)
        dfs(i,j+1,state,next);	//如果这个位置已经被上一列所占用,直接跳过
    if (((1<<j)&state)==0)
        dfs(i,j+1,state,next|(1<<j));       //如果这个位置是空的,尝试放一个左右覆盖1*2的木板
    if (j+1<n && ((1<<j)&state)==0 && ((1<<(j+1))&state)==0)
        dfs(i,j+2,state,next); 	//如果这个位置以及下一个位置都是空的,尝试放一个上下覆盖2*1的木板,而此时要跳过下一个木块
    return;
}
int main() {
    while (~scanf("%d%d",&n,&m),n+m) {
        memset(dp,0,sizeof(dp));
        dp[1][0]=1;	//初始化第一列状态为0的方法数等于1
        for (int i=1;i<=m;i++) {	//外层for循环遍历每一列
            for (int j=0;j<(1<<n);j++)	//内层for遍历每一个列的所有状态
                if (dp[i][j]){	//只要dp[i][j]方法数不为空,就执行dfs方法
                    dfs(i,0,j,0);
                }
        }
        printf("%lld\n",dp[m+1][0]);	//最后dp[m+1][0]就是结果
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值