0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-09-19 16:25:25 +00:00

B3607 [图论与代数结构 502] 网络流_2

https://www.luogu.com.cn/record/76712076
This commit is contained in:
Baoshuo Ren 2022-05-31 15:51:01 +08:00
parent 02872e62a0
commit 1eb7742cf5
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A

96
Luogu/B3607/B3607.cpp Normal file
View File

@ -0,0 +1,96 @@
#include <cstring>
#include <iostream>
#include <queue>
using std::cin;
using std::cout;
const char endl = '\n';
const int N = 205,
M = 5005;
int n, m, s, t, flow;
long long ans;
// Graph
int idx, head[N], edge[M << 1], ver[M << 1], next[M << 1];
void add(int u, int v, int w) {
next[idx] = head[u];
ver[idx] = v;
edge[idx] = w;
head[u] = idx++;
}
// Dinic
int d[N], cur[N];
bool bfs() {
memset(d, 0x00, sizeof(d));
std::queue<int> q;
d[s] = 1;
q.push(s);
cur[s] = head[s];
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; ~i; i = next[i]) {
int v = ver[i],
w = edge[i];
if (w && !d[v]) {
d[v] = d[u] + 1;
cur[v] = head[v];
if (v == t) return true;
q.push(v);
}
}
}
return false;
}
int dinic(int u, int limit) {
if (u == t) return limit;
int flow = 0;
for (int &i = cur[u]; ~i && flow < limit; i = next[i]) {
int v = ver[i],
w = edge[i];
if (w && d[v] == d[u] + 1) {
int k = dinic(v, std::min(edge[i], limit - flow));
if (!k) d[v] = 0;
edge[i] -= k;
edge[i ^ 1] += k;
flow += k;
}
}
return flow;
}
int main() {
std::ios::sync_with_stdio(false);
memset(head, 0xff, sizeof(head));
cin >> n >> m >> s >> t;
for (int i = 1, u, v, w; i <= m; i++) {
cin >> u >> v >> w;
add(u, v, w);
add(v, u, 0);
}
while (bfs()) {
while (flow = dinic(s, 0x3f3f3f3f)) ans += flow;
}
cout << ans << endl;
return 0;
}