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
题意
经典覆盖问题,输入n和m表示一个n×m的矩形,用1*2的方块进行覆盖,不能重叠,不能越出矩形边界,问完全覆盖完整个矩形有多少种不同的方案
状压dp:把状态用比特位的形式表示出来
用状压dp解决问题:
- 在横着贴砖的时候,(i, j), (i, j+1) 都是1,这个值其实对下一行如何选择没有影响。
- 竖着贴砖的第二个,我们也选择了1, 因为这个砖头结束了,对下一行如何选择依然没有影响。
- 竖着贴砖的第二个,我们也选择了1, 因为这个砖头结束了,对下一行如何选择依然没有影响。
如图所示
AC代码
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m;
long long dp[15][1<<12];
bool init(int status){//设置初始状态
for(int j=0;j<m;){//前j-1列符合要求,对第j列进行判断
if(status&(1<<j)){//第j列为1
if(j==m-1) return false; //j为最后一列,不可行
if(status&(1<<(j+1))) j+=2;//第j列和第j+1列都为1 则表示横放,可行,考虑 j+2列
else return false; //第j列为1,第j+1列都为0不可行
}
else j++;//第j列为0 ,则为竖放,可行
}
return true;
}
bool check(int now_s,int pre_s){//判断上一次状态和本次状态是否兼容
for(int j=0;j<m;){
if(now_s&(1<<j)){//第i行第j列为1
if(pre_s&(1<<j)){//第i-1行第j列也为1,那么第i行必然是横放
if(j==m-1||!(now_s&1<<(j+1))||!(pre_s&1<<(j+1))) //第i行和第i-1行的第j+1都必须是1,否则是非法的
return false;
else
j+=2;
}
else j++; //第i-1行第j列为0,说明第i行第j列是竖放
}
else{//第i行第j列为0,那么第i-1行的第j列应该是已经填充了的
if(pre_s&(1<<j)) j++;
else return false;
}
}
return true;
}
void solve(){
int to=(1<<m)-1;
memset(dp,0,sizeof(dp));
for(int i=0;i<=to;i++){
if(init(i)) dp[1][i]=1;
}
for(int i=2;i<=n;i++){//按行dp
for(int j=0;j<=to;j++){ //第i行的状态
for(int k=0;k<=to;k++){ //第i-1行的状态
if(check(j,k)) dp[i][j]+=dp[i-1][k];
}
}
}
printf("%lld\n",dp[n][to]);
}
int main(){
while(scanf("%d%d",&n,&m)&&(n||m)){
if(n&1&&m&1){ //n和m均为奇数的话,矩形面积就是奇数,可知是不可能完全覆盖的
printf("0\n");
continue;
}
if(n<m) swap(n,m);//交换n和m使n较大m较小,这样能减少状态数
solve();
}
return 0;
}
参考:https://blog.csdn.net/u014634338/article/details/50015825