POJ 2411 Mondriaan's Dream (dp + 狀態壓縮),pojmondriaan

來源:互聯網
上載者:User

POJ 2411 Mondriaan's Dream (dp + 狀態壓縮),pojmondriaan

連結:http://poj.org/problem?id=2411

題意:題目描述:用1*2 的矩形通過組合拼成大矩形,求拼成指定的大矩形有幾種拼法。

參考部落格:http://blog.csdn.net/shiwei408/article/details/8821853

思路:我看了上面的部落格,想了很久才明白是如何處理狀態的。

由於是1 * 2,所以可以通過相鄰兩行的轉化關係來推導。

兩行鋪不鋪磚可以用二進位來表示,但是如果暴力枚舉,大概有2^10 * 2 ^ 10 次那麼多狀態(雖然其中有很多狀態是沒有用的)。

所以採用dfs來枚舉各種可行狀態:

狀態標記 橫放和豎放的下一個均為1,豎放的上一個和不放置為0 ,每行可以轉化為1個2進位數。當這一行訪問結束時,就會得到上一行狀態,和該行狀態,因為所有情況都是我們設定的,所以pre狀態一定會轉化為now狀態

對於每一個位置,我們有三种放置方法:1. 豎直放置2. 水平放置3. 不放置

d為當前列號 ,初始化d, now, pre都為0。now為當前行,pre為當前行的上一行

1. d = d + 1, now << 1 | 1, pre << 1;   // 豎直放置,當前行該列為1,上一行該列置為0

2. d = d + 2, now << 2 | 3, pre<< 2 | 3;  // 橫放 都為11(因為當兩行的狀態往下推時,必須要保證pre這一行擺滿,所以pre也都為11)

3. d = d + 1, now << 1, pre<< 1 | 1;    // 上一行該列置為1,不能豎放,不放置的狀態

因為轉移狀態有很多種,所以用dfs去枚舉各種可行的狀態。

最後在轉移的時候,dp[0][(1 << w) - 1] = 1 表示只有第0行全部鋪滿才行。只需要算到 h - 1 行,然後 h 行全部鋪滿為答案。

代碼:

/*ID: wuqi9395@126.comPROG:LANG: C++*/#include<map>#include<set>#include<queue>#include<stack>#include<cmath>#include<cstdio>#include<vector>#include<string>#include<fstream>#include<cstring>#include<ctype.h>#include<iostream>#include<algorithm>#define INF (1<<30)#define PI acos(-1.0)#define mem(a, b) memset(a, b, sizeof(a))#define rep(i, n) for (int i = 0; i < n; i++)#define debug puts("===============")#define eps (1e-6)typedef long long ll;using namespace std;const int maxn = 13;int w, h, cnt;ll dp[13][2100];int sta[14000][2];void dfs(int l, int now, int pre) {    if (l > w) return ;    if (l == w) {        sta[cnt][0] = pre, sta[cnt++][1] = now;        return ;    }    dfs(l + 2, (now << 2) | 3, (pre << 2) | 3);    dfs(l + 1, (now << 1) | 1, pre << 1);    dfs(l + 1, now << 1, (pre << 1) | 1);}int main () {    while(~scanf("%d%d", &h, &w), h || w) {        if (h < w) swap(h, w);        cnt = 0;        dfs(0, 0, 0);        memset(dp, 0, sizeof(dp));        dp[0][(1 << w) - 1] = 1;        rep(i, h) {            rep(j, cnt) {                dp[i + 1][sta[j][1]] += dp[i][sta[j][0]];            }        }        printf("%lld\n", dp[h][(1 << w) - 1]);    }    return 0;}






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.