Skip to content

Instantly share code, notes, and snippets.

@yurahuna
Last active July 25, 2018 06:37
Show Gist options
  • Save yurahuna/e4bda3cd1d4f0c18c9c42cdb0871dd0e to your computer and use it in GitHub Desktop.
Save yurahuna/e4bda3cd1d4f0c18c9c42cdb0871dd0e to your computer and use it in GitHub Desktop.
FordFulkerson
// http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_A
#include <vector>
#include <iostream>
#include <algorithm>
class FordFulkerson {
struct edge { int from, to, cap, rev; };
static const int INF = 1 << 30;
private:
int n;
std::vector<std::vector<edge> > G; // adj list
std::vector<bool> used;
public:
FordFulkerson (int n) : n(n), G(n) {}
void addEdge(int from, int to, int cap) {
G[from].push_back((edge){from, to, cap, static_cast<int>(G[to].size())});
G[to].push_back((edge){to, from, 0, static_cast<int>(G[from].size()) - 1});
}
int dfs(int v, int t, int f) {
if (v == t) return f;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if (!used[e.to] && e.cap > 0) {
int d = dfs(e.to, t, std::min(f, e.cap));
if (d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int calc(int s, int t) {
int flow = 0;
while (true) {
used.clear();
used.resize(n, false);
int f = dfs(s, t, INF);
if (f == 0) return flow;
flow += f;
}
}
};
int main() {
int n, m;
std::cin >> n >> m;
FordFulkerson ff(n);
for (int i = 0; i < m; i++) {
int u, v, c;
std::cin >> u >> v >> c;
ff.addEdge(u, v, c);
}
std::cout << ff.calc(0, n-1) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment