131. Hardwood floor
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
The banquet hall of Computer Scientists' Palace has a rectangular form of the size M x N (1<=M<=9, 1<=N<=9). It is necessary to lay hardwood floors in the hall. There are wood pieces of two forms:
1) rectangles (2x1)
2) corners (squares 2x2 without one 1x1 square)
You have to determine X - the number of ways to cover the banquet hall.
Remarks. The number of pieces is large enough. It is not allowed to leave empty places, or to cover any part of a surface twice, or to saw pieces.
Input
The first line contains natural number M. The second line contains a natural number N.
Output
First line should contain the number X, or 0 if there are no solutions.
Sample Input
2 3
Sample Output
5
一道状态压缩dp题,很明显我们可以枚举某一行的状态来推得下一行的状态。
现在问题是如何枚举这一行的状态。由于sgu坑爹的内存限制,推荐使用dfs构造。
对于每一个block,最多能影响到的列数为2,又由于有两种block,因此有以下几种可能:(摘自周伟《动态规划之状态压缩》)
(强调一点,我们正在求的这一行的前一行是必须要填满的。)
设p为当前列数,s1、s2分别为上下两行当前的状态,b1、b2为上一列对这一列分别上下两行的影响。
(1)当我们不在当前行当前列放block时,s1、s2只受b1、b2的限制,由此得s1=s1*2+b1,s2=s2*2+1-b2(由于下面那行本应该填满,故原始状态为1,受影响后状态为1-b2)
转移后由于没在此放block,所以对后续的列无影响,故b1=0、b2=0;
(2)当横着放block时,即为:
1 1
0 0
要求此时的b1必须为0(不用解释吧),转移得s1=s1*2+1、s2=s2*2+1-b2,转移后的b1=1、b2=0;
(3)当竖着放block时,即为: 1 0
1 0
要求此时b1=b2=0。
注意!第i行的放置方案用到第i-1行的某格时,s2中该格应为0!
因此s1=s1*2+1,s2=s2*2,转移后b1=b2=0;
(4)当L形如此放时,即为:
1 0
1 1
要求此时b1=b2=0。
s1=s1*2+1,s2=s2*2,转移后b1=0、b2=1;
(5)当L形如此放时,即为:
1 1
1 0
要求此时b1=b2=0。
s1=s1*2+1,s2=s2*2,转移后b1=1、b2=0;
(6)当L形如此放时,即为:
0 11 1要求b2=0。
s1=s1*2+b1,s2=s2*2,转移后b1=b2=1;
(7)当L形如此放时,即为:
要求b1=0。1 10 1
s1=s1*2+1,s2=s2*2+1-b2,转移后b1=b2=1;
如此,可以求出答案,而且效率比较可观。#include <cstdio> #include <cstring> using namespace std; const int MAX = 1<<10; int n, m, now = 0; long long f[2][MAX] = {0}; int k = 0; void dfs(int cur, int s1, int s2, bool p1, bool p2) { if(cur == m) { if(!p1 && !p2) f[now][s1] += f[now^1][s2]; return ; } dfs(cur+1, s1<<1|p1, s2<<1|(1^p2), 0, 0); if(!p1) { dfs(cur+1, s1<<1|1, s2<<1|(1^p2), 1, 0); dfs(cur+1, s1<<1|1, s2<<1|(1^p2), 1, 1); } if(!p2) dfs(cur+1, s1<<1|p1, s2<<1, 1, 1); if(!p1&!p2) { dfs(cur+1, s1<<1|1, s2<<1, 0, 0); dfs(cur+1, s1<<1|1, s2<<1, 0, 1); dfs(cur+1, s1<<1|1, s2<<1, 1, 0); } } int main() { scanf("%d%d", &n, &m); f[1][(1<<m)-1] = 1; for(int i = 1; i <= n; ++i) { dfs(0, 0, 0, 0, 0); memset(f[now^1], 0, sizeof(f[now^1])); now ^= 1; } printf("%I64d\n", f[now^1][(1<<m)-1]); return 0; }