题目链接 http://poj.org/problem?id=2411
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
题目大意:
在nxm的方格纸上,用1x2的矩形块覆盖方格纸,要求矩形块不能有重叠,并且要刚好完全将纸覆盖,求有多少种覆盖方法。
题解:
经典的状压dp入门题,解法参考自 https://blog.csdn.net/u013480600/article/details/19569291
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
int n,m;
int path[5000000][2];// 存储所有可能情况
int num;// path数组长度
ll dp[15][3000];
// 计算所有可能的path , 1->m列
void CalPath(int col,int pre,int now) {
if(col > m) return;// 不加此行答案是错的,因为在递归的时候会有col+2这种操作使得col越界
if(col >= m) {
path[num][0] = pre;// 前一行状态
path[num++][1] = now;// 后一行状态
return;
}
CalPath(col+1,pre<<1,now<<1|1);
CalPath(col+1,pre<<1|1,now<<1);
CalPath(col+2,pre<<2|3,now<<2|3);
}
int main() {
while(scanf("%d%d",&n,&m) == 2) {
if(n == 0 && m == 0) break;
//if(n > m) swap(n,m);
memset(path,0,sizeof(path));
memset(dp,0,sizeof(dp));
num = 0;
CalPath(0,0,0);
// 初始化第0行
dp[0][(1<<m)-1] = 1;
for(int i = 1;i <= n;i++)
for(int j = 0;j < num;j++) {
dp[i][path[j][1]] += dp[i-1][path[j][0]];
}
printf("%lld\n",dp[n][(1<<m)-1]);
}
return 0;
}