题目描述
如题,给出一个网络图,以及其源点和汇点,求出其网络最大流。
1、EK模板
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 2e5 + 10;
int n, m, s, t, h[N], cnt, inq[N];
struct node {
int v, w, nt;
} no[N];
struct Pre {
int v, e;
} pre[N];
void add(int u, int v, int w) {
no[cnt] = node{v, w, h[u]};
h[u] = cnt++;
}
bool bfs() {
queue<int> q;
memset(pre, 0, sizeof pre);
memset(inq, 0, sizeof inq);
inq[s] = 1, q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
for(int i = h[u]; ~i; i = no[i].nt) {
int v = no[i].v;
if(!inq[v] && no[i].w) {
pre[v].v = u;
pre[v].e = i;
if(v == t)
return 1;
inq[v] = 1;
q.push(v);
}
}
}
return 0;
}
int EK() {
int ans = 0;
while(bfs()) {
int mi = 1e9;
for(int i = t; i != s; i = pre[i].v)
mi = min(mi, no[pre[i].e].w);
for(int i = t; i != s; i = pre[i].v) {
no[pre[i].e].w -= mi;
no[pre[i].e + 1].w += mi;
}
ans += mi;
}
return ans;
}
int main() {
memset(h, -1, sizeof h);
scanf("%d%d%d%d", &n, &m, &s, &t);
for(int u, v, w, i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
add(u, v, w), add(v, u, 0);
}
printf("%d\n", EK());
return 0;
}
2、dinic模板(当前弧优化)
#include<bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int N = 2e5 + 10;
int n, m, s, t, h[N], cnt, dep[N], cur[N];
struct node {
int v, w, nt;
} no[N];
void add(int u, int v, int w) {
no[cnt] = node{v, w, h[u]};
h[u] = cnt++;
}
int bfs() {
queue<int> q;
memset(dep, 0, sizeof dep);
dep[s] = 1;
q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
for(int i = h[u]; ~i; i = no[i].nt) {
int v = no[i].v;
if(!dep[v] && no[i].w>0) {
dep[v] = dep[u] + 1;
q.push(v);
}
}
}
return dep[t] > 0;
}
int dfs(int u, int flow) {
if(u == t)
return flow;
for(int &i = cur[u]; ~i; i = no[i].nt) {
int v = no[i].v;
if(dep[v] == dep[u] + 1 && no[i].w) {
int res = dfs(v, min(flow, no[i].w));
if(res > 0) {
no[i].w -= res;
no[i ^ 1].w += res;
return res;
}
}
}
return 0;
}
int dinic() {
int res = 0;
while(bfs()) {
for(int i = 0; i <= t; i++)
cur[i] = h[i];
while(int d = dfs(s, INF))
res += d;
}
return res;
}
int main() {
memset(h, -1, sizeof h);
scanf("%d%d%d%d", &n, &m, &s, &t);
for(int u, v, w, i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
add(u, v, w), add(v, u, 0);
}
printf("%d\n", dinic());
return 0;
}