#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;
}
有源汇有上下界最小流 模板
最新推荐文章于 2024-02-22 00:39:16 发布