Mondriaan's Dream
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
题意: 用长为2, 宽为1的小矩形, 铺满n*m的大矩形, 计算有多少种方法.
解题思路:
1. 题目做法很直接, 就是从左上角的状态一直递推到右下角, 最后统计总数.
状态: 设dp[i][j]: 表示前i-1层已经确定, 在当前第i层摆放完成状态j的总数.
状态方程: dp[i][j] += dp[i-1][k]
2. 完成状态j这个是关键, 显然, 用状态压缩: 二进制的方法.
假设: 当前层用0和1表示在上一层已经摆放和在当前层摆放. 这样二进制发挥作用.
设d表示列数, from表示上一层状态, to表示当前层状态.
小矩形的放置方法有3种----水平放置(长(列)2,宽(行)1), 竖直放置(长(列)1,宽(行)2).
问题分析:
(1). 竖直放置: 同样又分为2种情况, 因为每次摆放一层都必须放满, 所以如下图:
状态可以从DP(d, from, to) --> DP(d+1, (from<<1)+1, (to<<1))和 DP(d+1, (from<<1), (to<<1)+1);
(2). 水平放置: 这个只有一种状态, 就是在上一层已经水平放置之后, 当前才能水平放置.
状态DP(d, from, to) --> DP(d+2, (from<<2)+3, (to<<2)+3);
3. 最后因为每次只讨论2行的问题, 滚动数组可以节省空间.
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 12
int n, m, e;
__int64 dp[2][1<<MAX];
void init(int d, int mm)
{
if(d == m)
{
dp[0][mm]++;
return ;
}
if(d+1 <= m)
init(d+1, mm<<1);
if(d+2 <= m)
init(d+2, (mm<<2)+3);
}
void DP(int d, int from, int to)
{
if(d == m)
{
dp[e][to] += dp[e^1][from];
return ;
}
if(d+1 <= m)
{
DP(d+1, (from<<1)+1, (to<<1));
DP(d+1, (from<<1), (to<<1)+1);
}
if(d+2 <= m)
{
DP(d+2, (from<<2)+3, (to<<2)+3);
}
}
int main()
{
// freopen("input.txt", "r", stdin);
while(scanf("%d %d",&n, &m) != EOF)
{
if(n ==0 && m == 0) break;
if( (n*m) % 2 != 0 )
printf("0\n");
else
{
if(n > m)
{
int temp = n;
n = m;
m = temp;
}
memset(dp, 0, sizeof(dp));
init(0, 0);
e = 0;
for(int i = 2; i <= n; ++i)
{
e ^= 1;
DP(0,0,0);
memset(dp[e^1], 0 , sizeof(dp[e^1]));
}
printf("%I64d\n", dp[e][(1<<m)-1]);
}
}
return 0;
}