diff --git a/Graphs/edmonds_karp.cpp b/Graphs/edmonds_karp.cpp new file mode 100644 index 0000000..63627ed --- /dev/null +++ b/Graphs/edmonds_karp.cpp @@ -0,0 +1,47 @@ +int n; +vector > capacity; +vector > adj; + +int bfs(int s, int t, vector& parent) { + fill(parent.begin(), parent.end(), -1); + parent[s] = -2; + queue > q; + q.push(make_pair(s, INF)); + + while (!q.empty()) { + int cur = q.front().first; + int flow = q.front().second; + q.pop(); + + for (int next : adj[cur]) { + if (parent[next] == -1 && capacity[cur][next]) { + parent[next] = cur; + int new_flow = min(flow, capacity[cur][next]); + if (next == t) + return new_flow; + q.push(make_pair(next, new_flow)); + } + } + } + + return 0; +} + +int maxflow(int s, int t) { + int flow = 0; + vector parent(n); + int new_flow; + + while (new_flow = bfs(s, t, parent)) { + flow += new_flow; + int cur = t; + while (cur != s) { + int prev = parent[cur]; + capacity[prev][cur] -= new_flow; + capacity[cur][prev] += new_flow; + cur = prev; + } + } + + return flow; +}