poj 1185 炮兵阵地 状压dp

题目链接

题意

(N imes M)(0,1)格子上放东西,只有标记为(1)的格子可以放东西,且每一格的向上两个,向下两个,向左两个,向右两个格子均不能放东西。问整张图上最多能放多少东西。

思路

参考:accry.

因为每一行的状态与上两行有关,所以用(dp[i][j][k])表示放到第(i)行,当前行的状态为(j),上一行的状态为(k)时的情况总数。

转移 以及 初始合法状态的预处理 与上一题 poj 3254 Corn Fields 状压dp入门 类似。

注意 特判 只有一行的状态。

Code

#include <stdio.h>
#include <iostream>
#define F(i, a, b) for (int i = (a); i < (b); ++i)
#define F2(i, a, b) for (int i = (a); i <= (b); ++i)
#define dF(i, a, b) for (int i = (a); i > (b); --i)
#define dF2(i, a, b) for (int i = (a); i >= (b); --i)
#define maxn 110
using namespace std;
typedef long long LL;
int state[maxn], dp[maxn][maxn][maxn], cur[maxn];
char s[12];
inline int count(int x) { int cnt = 0; while (x) ++cnt, x &= x-1; return cnt; }
inline bool match1(int k, int row) { return !(state[k]&~cur[row]); }
inline bool match2(int k1, int k2) { return !(state[k1]&state[k2]); }
int main() {
    int n, m, tot=0, x;
    scanf("%d%d", &n, &m);
    F(i, 0, n) {
        scanf("%s", s);
        F(j, 0, m) {
            if (s[j]=='P') x = 1; else x = 0;
            (cur[i] <<= 1) |= x;
        }
    }
    int ans=0;
    F(i, 0, 1<<m) {
        if (!(i&(i<<1)) && !(i&(i<<2))) {
            if (!(i&~cur[0])) {
                dp[0][tot][0] = count(i);
                if (n==1) ans = max(ans, dp[0][tot][0]);
            }
            state[tot++] = i;
        }
    }
    if (n==1) {
        printf("%d
", ans);
        return 0;
    }
    F(i, 0, tot) {
        if (!match1(i, 1)) continue;
        F(j, 0, tot) {
            if (match1(j, 0) && match2(i, j)) dp[1][i][j] = max(dp[1][i][j], dp[0][j][0]+count(state[i]));
        }
    }
    F(i, 2, n) {
        F(j, 0, tot) {
            if (!match1(j, i)) continue;
            F(k, 0, tot) {
                if (!match1(k, i-1) || !match2(j, k)) continue;
                F(p, 0, tot) {
                    if (!match1(p, i-2) || !match2(j, p) || !match2(k, p)) continue;
                    dp[i][j][k] = max(dp[i][j][k], dp[i-1][k][p]+count(state[j]));
                }
            }
        }
    }
    F(i, 0, tot) {
        if (!match1(i, n-1)) continue;
        F(j, 0, tot) {
            if (match1(j, n-2) && match2(i, j)) ans = max(ans, dp[n-1][i][j]);
        }
    }
    printf("%d
", ans);
    return 0;
}

原文地址:https://www.cnblogs.com/kkkkahlua/p/8448552.html