有源汇有上下界最小流 模板

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 51000;
const int M = 402000;
const ll inf = 0x3f3f3f3f;
template <class Ruby>
inline void read(Ruby &x) {
    x = 0;
    char ch = getchar(), w = 0;
    while (!isdigit(ch)) w = (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
    x = w ? -x : x;
}
int hd[N], nxt[M], to[M], n, m, ss, tt, dep[N], cur[N], cnt = 1, flow[N], lower[M], s, t;
ll maxflow, tot, val[M];
inline void addedge(int u, int v, int w) { nxt[++cnt] = hd[u], to[cnt] = v, val[cnt] = w, hd[u] = cnt; }
queue<int>q;
inline int bfs() {
    memset(dep, 0, sizeof(dep));
    memcpy(cur, hd, sizeof(hd));
    while (!q.empty()) q.pop();
    dep[ss] = 1;
    q.push(ss);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for ( int i = hd[u]; i; i = nxt[i]) {
            int v = to[i];
            if (!dep[v] && val[i]) {
                dep[v] = dep[u] + 1;
                if (v == tt)
                    return 1;
                q.push(v);
            }
        }
    }
    return 0;
}
inline int dinic(int u, ll sum) {
    if (u == tt || !sum)
        return sum;
    int res = 0;
    for (int i = cur[u]; i; i = nxt[i]) {
        cur[u] = i;
        int v = to[i];
        if (dep[v] == dep[u] + 1 && val[i]) {
            int tmp = dinic(v, min(sum - res, val[i]));
            val[i] -= tmp, val[i ^ 1] += tmp;
            res += tmp;
        }
        if (res == sum)
            return res;
    }
    if (!res)
        dep[u] = -1;
    return res;
}
int main() {
    read(n), read(m);
    read(s), read(t);
    ss = n + 1, tt = n + 2;
    for (int i = 1, u, v, l, r; i <= m; i++) {
        read(u), read(v), read(l), read(r);
        flow[u] -= l, flow[v] += l;
        lower[i] = l;
        addedge(u, v, r - l), addedge(v, u, 0);
    }
    for (int i = 1; i <= n; i++) {
        if (flow[i] > 0) addedge(ss, i, flow[i]), addedge(i, ss, 0), tot += flow[i];
        if (flow[i] < 0) addedge(i, tt, -flow[i]), addedge(tt, i, 0);
    }
    addedge(t, s, inf), addedge(s, t, 0);
    while (bfs()) maxflow += dinic(ss, inf);
    if (maxflow != tot)
        printf("please go home to sleep\n");
    else {
        maxflow = val[cnt];
        hd[t] = nxt[hd[t]], hd[s] = nxt[hd[s]];
        tt = s;
        ss = t;
        while (bfs()) maxflow -= dinic(ss, inf);
        cout << maxflow;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值