BZOJ 1565 NOI 2009 植物大战僵尸 最小割 拓扑排序

相互保护的植物不可能被吃。即形成环的点全部删去。
剩下的即最大权闭合子图。。。

#include <cstdio>
#include <cstring>
#include <algorithm>
#define FOR(i,j,k) for(i=j;i<=k;++i)
using namespace std;
const int inf = 0x3f3f3f3f, N = 660, M = 800005;

int level[N], cnt = 1, cur[N], v[M], p[M], h[N], q[M], s = 0, t, w[M], a[N], in[N];
void add(int a, int b, int c) {
    p[++cnt] = h[a]; v[cnt] = b; w[cnt] = c; h[a] = cnt; ++in[a];
    p[++cnt] = h[b]; v[cnt] = a; w[cnt] = 0; h[b] = cnt;
}

bool bfs() {
    int f = 0, r = 0, u, i;
    for (i = s; i <= t; ++i) if (level[i] != -2) level[i] = -1;
    q[r++] = s; level[s] = 1;
    while (f < r) {
        u = q[f++];
        for (i = h[u]; i; i = p[i]) {
            if (w[i] && level[v[i]] == -1) {
                level[v[i]] = level[u] + 1;
                q[r++] = v[i];
            }
        }
    }
    return level[t] > 0;
}

int dfs(int u, int low) {
    int i, tmp = 0; int res = 0;
    if (u == t) return low;
    for (i = cur[u]; i && res < low; i = p[i]) {
        if (w[i] && level[v[i]] == level[u] + 1) {
            tmp = dfs(v[i], min(w[i], low - res));
            w[i] -= tmp; w[i ^ 1] += tmp; res += tmp;
            if (w[i]) cur[u] = i;
        }
    }
    if (!res) level[u] = -1;
    return res;
}

int dinic() {
    int ans = 0, i;
    while (bfs()) {
        for (i = s; i <= t; ++i) cur[i] = h[i];
        ans += dfs(s, inf);
    }
    return ans;
}

int main() {
    int i, b, c, d, n, m, ss = 0;
    scanf("%d%d", &m, &n);
    t = n * m + 1;
    FOR(i,1,n*m) {
        scanf("%d", &a[i]);
        if (a[i] > 0) add(s, i, a[i]);
        else add(i, t, -a[i]);
        scanf("%d", &b);
        while (b--) {
            scanf("%d%d", &c, &d);
            add(c*n+d+1,i,inf);
        }
        if (i % n) add(i, i + 1, inf);
    }
    c = d = 0;
    for (i = s; i <= t; ++i) {
        if (!in[i]) q[d++] = i;
        level[i] = -2;
    }
    while (c < d) {
        b = q[c++]; level[b] = 0;
        if (a[b] > 0) ss += a[b];
        for (i = h[b]; i; i = p[i]) if (i & 1)
            if (!--in[v[i]]) q[d++] = v[i];
    }
    printf("%d\n", ss - dinic());
    return 0;
}

你可能感兴趣的:(拓扑排序,最小割,OI,NOI,bzoj)