bzoj 2561 最小生成树 最小割建图

题面

题目传送门

解法

应该是比较显然的最小割了吧

问题可以转化为,只使用边权\(<w\)的边,最少去掉几条边,使得\(x,y\)不连通

显然的最小割问题

最大生成树同理

最后答案为最小生成树的答案+最大生成树的答案

代码

#include <bits/stdc++.h>
#define N 20010
using namespace std;
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 Node {
    int x, y, v;
    bool operator < (const Node &a) const {
        return v < a.v;
    }
} a[N * 10];
struct Flow {
    struct Edge {
        int next, num, c;
    } e[N * 41];
    int n, s, t, cnt, l[N], cur[N];
    void Clear(int tn, int x, int y) {
        cnt = n = tn, s = x, t = y;
        if (cnt % 2 == 0) cnt++;
        for (int i = 1; i <= n; i++)
            e[i].next = 0;
    }
    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);
    }
    void build(int m, int key, int tx) {
        for (int i = 1; i <= m; i++) {
            int x = a[i].x, y = a[i].y, v = a[i].v;
            if (key == 1 && v >= tx) break;
            if (key == 2 && v <= tx) continue;
            Add(x, y, 1), Add(y, x, 1);
        }
    }
    bool bfs(int s) {
        for (int i = 1; i <= n; i++) l[i] = -1;
        l[s] = 0; 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)
                    l[k] = l[x] + 1, q.push(k);
            }
        }
        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 (l[k] == l[x] + 1 && c) {
                int w = dfs(k, min(c, lim - used));
                e[p].c -= w, e[p ^ 1].c += w;
                if (e[p].c) cur[x] = p;
                used += w;
                if (used == lim) return lim;
            }
        }
        if (!used) l[x] = -1;
        return used;
    }
    int dinic() {
        int ret = 0;
        while (bfs(s)) {
            for (int i = 1; i <= n; i++)
                cur[i] = e[i].next;
            ret += dfs(s, INT_MAX);
        }
        return ret;
    }
} sol;
int main() {
    int n, m, ans = 0; read(n), read(m);
    for (int i = 1; i <= m; i++)
        read(a[i].x), read(a[i].y), read(a[i].v);
    sort(a + 1, a + m + 1);
    int x, y, v; read(x), read(y), read(v);
    sol.Clear(n, x, y); sol.build(m, 1, v); ans += sol.dinic();
    sol.Clear(n, x, y); sol.build(m, 2, v); ans += sol.dinic();
    cout << ans << "\n";
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/copperoxide/p/9478722.html