# 網絡流_Edmonds-Karp 增廣路算法

EK增廣路算法的簡單思路：

5 4
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10

50

AC代碼：

``````#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int maxn = 205;
const int inf = 0x3f3f3f3f;

int n, m, maxflow, s, t, idx;
int h[maxn], e[maxn * 2], w[maxn * 2], ne[maxn * 2], incf[maxn], pre[maxn];
bool vis[maxn];

inline void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, w[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
}

inline bool bfs(void) {
memset(vis, false, sizeof vis);
queue<int> q;
q.push(s);
vis[s] = true;
incf[s] = inf;

while(q.size()) {
int x = q.front(); q.pop();

for(int i = h[x]; i != -1; i = ne[i]) {
if(w[i]) {
int y = e[i];
if(!vis[y]) {
pre[y] = i;
incf[y] = min(incf[x], w[i]);
q.push(y);
vis[y] = true;
if(y == t) return true;
}
}
}
}

return  false;
}

inline void update(void) {
int x = t;
while(x != s) {
int i = pre[x];
w[i] -= incf[t];
w[i ^ 1] += incf[t];
x = e[i ^ 1];
}

maxflow += incf[t];
}

int main(void) {
//	freopen("in.txt", "r", stdin);

scanf("%d%d", &m, &n);
memset(h, -1, sizeof h);
s = 1, t = n;
for(int i = 1; i <= m; i ++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
}

while(bfs()) update();

printf("%d\n", maxflow);

//	fclose(stdin);
return 0;
}

``````