bzoj 4485 [Jsoi2015]圈地 最小割

题面

题目传送门

解法

比较容易想到模型的最小割

  • 可以发现,这显然就是一个最小割的模型
  • 不妨将卖给第一个人的全部与 S 连边,卖给另一个人的与 T 连边,容量分别为各自格子里的价格
  • 然后将相邻格子连边,容量为两个格子之间建墙的代价,然后用所有价格-最小割就是答案
  • 考虑一下这个算法的正确性,显然一个点要么不取,要么就一定会分配给 S 集或 T 集。建造围墙的时候就保证了 S 集的点不会和 T 集的点在同一个连通块中,因为我们求的是最小割
  • 尽管看上去点数为 400 × 400 ,但是用 d i n i c 算法加上当前弧优化就能轻松通过此题

代码

#include <bits/stdc++.h>
#define N 410
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
    x = 0; int f = 1; char c = getchar();
    while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Edge {
    int next, num, c;
} e[N * N * 16];
int n, m, s, t, cnt, l[N * N], cur[N * N];
int calc(int x, int y) {return (x - 1) * m + y;}
void add(int x, int y, int c) {
    e[++cnt] = (Edge) {e[x].next, y, c};
    e[x].next = cnt;
}
void Add(int x, int y, int c) {
    add(x, y, c), add(y, x, 0);
}
bool bfs(int s) {
    for (int i = 1; i <= t; i++) l[i] = -1;
    queue <int> q; q.push(s);
    while (!q.empty()) {
        int x = q.front(); q.pop();
        for (int p = e[x].next; p; p = e[p].next) {
            int k = e[p].num, c = e[p].c;
            if (c && l[k] == -1)
                q.push(k), l[k] = l[x] + 1;
        }
    }
    return l[t] != -1;
}
int dfs(int x, int lim) {
    if (x == t) return lim;
    int used = 0;
    for (int p = cur[x]; p; p = e[p].next) {
        int k = e[p].num, c = e[p].c;
        if (c && l[k] == l[x] + 1) {
            int w = dfs(k, min(c, lim - used));
            e[p].c -= w, e[p ^ 1].c += w, used += w;
            if (e[p].c) cur[x] = p;
            if (lim == used) return lim;
        }
    }
    if (!used) l[x] = -1; return used;
}
int dinic() {
    int ret = 0;
    while (bfs(s)) {
        for (int i = 0; i <= t; i++) cur[i] = e[i].next;
        ret += dfs(s, INT_MAX);
    }
    return ret;
}
int main() {
    read(n), read(m);
    s = 0, t = cnt = n * m + 1;
    if (cnt % 2 == 0) cnt++;
    int ans = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) {
            int x; read(x); ans += abs(x);
            if (x < 0) Add(s, calc(i, j), -x);
                else if (x > 0) Add(calc(i, j), t, x);
        }
    for (int i = 1; i < n; i++)
        for (int j = 1; j <= m; j++) {
            int x; read(x);
            Add(calc(i, j), calc(i + 1, j), x);
            Add(calc(i + 1, j), calc(i, j), x);
        }
    for (int i = 1; i <= n; i++)
        for (int j = 1; j < m; j++) {
            int x; read(x);
            Add(calc(i, j), calc(i, j + 1), x);
            Add(calc(i, j + 1), calc(i, j), x);
        }
    cout << ans - dinic() << "\n";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/emmmmmmmmm/article/details/81950052