POJ 2411 鋪地磚 狀態壓縮dp入門
阿新 • • 發佈:2019-01-07
Mondriaan's Dream
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!
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.
還有一種寫法是採用滾動陣列,逐格遞推,三層迴圈,類似於白書的寫法,
Time Limit: 3000MS | Memory Limit: 65536K |
Total 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
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
給一個長,一個寬,求用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]);
}
}