POJ 2411 铺地砖 状态压缩dp入门

来源:互联网 发布:淘宝上传水印图片尺寸 编辑:程序博客网 时间:2024/05/09 19:43
Mondriaan's Dream
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 10402 Accepted: 6035

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 21 31 42 22 32 42 114 110 0

Sample Output

10123514451205

Source

Ulm Local 2000

[Submit]   [Go Back]   [Status]   [Discuss]


给一个长,一个宽,求用1*2的地砖能恰好完全覆盖的方法有多少种。

研究了好久,终于有点理解了,采用状态压缩dp来枚举每一层的状态,然后层层递推,最后就可以得到了答案。

dfs状态压缩代码:

#include <cstdio>#include <cstring> #include <cstdlib> #include <iostream>using namespace std;long long dp[12][(1<<11)+1];int m,n,k;void dfs(int c,int s1,int s2){if(c==n) {dp[k][s1] += dp[k-1][s2]; return;}if(c+1<=n){dfs(c+1,s1<<1,s2<<1|1);dfs(c+1,s1<<1|1,s2<<1);}if(c+2<=n)dfs(c+2,s1<<2|3,s2<<2|3);}int main(){while(~scanf("%d%d", &m ,&n) && m){if(n>m) swap(n,m);memset(dp,0,sizeof(dp));dp[0][(1<<n)-1]=1;for(k=1; k<=m; k++)dfs(0,0,0);printf("%lld\n",dp[m][(1<<n)-1]);}    return 0;}


还有一种写法是采用滚动数组,逐格递推,三层循环,类似于白书的写法,

代码:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;long long dp[2][1<<11];int main(){int n,m;while(scanf("%d%d",&n,&m),(n||m)){int total=1<<m,pre=0,now=1;memset(dp[now],0,sizeof(dp[now]));dp[now][0]=1;for(int i=0;i<n;i++)for(int j=0;j<m;j++){swap(now,pre);memset(dp[now],0,sizeof(dp[now]));for(int S=0;S<total;S++) if( dp[pre][S] ){dp[now][S^(1<<j)]+=dp[pre][S];if( j && S&(1<<(j-1)) && !(S&(1<<j)))dp[now][S^(1<<(j-1))]+=dp[pre][S];}}printf("%lld\n",dp[now][0]);}}



0 0
原创粉丝点击