0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-08 12:58:48 +00:00

P3376 【模板】网络最大流

https://www.luogu.com.cn/record/91932491
This commit is contained in:
Baoshuo Ren 2022-10-28 19:56:00 +08:00
parent 17e280db2a
commit a88a53c97a
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A
3 changed files with 34 additions and 16 deletions

View File

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

BIN
Luogu/P3376/data/P3376_7.in (Stored with Git LFS) Normal file

Binary file not shown.

BIN
Luogu/P3376/data/P3376_7.out (Stored with Git LFS) Normal file

Binary file not shown.