diff --git a/algorithms/graph/edmonds_karp.cpp b/algorithms/graph/edmonds_karp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5c55bbe20cd4681e2d601172c29141f7f1ada32 --- /dev/null +++ b/algorithms/graph/edmonds_karp.cpp @@ -0,0 +1,66 @@ +/** + * Edmonds-Karp + * + * Complexity (time): O(V*E^2) + * Complexity (space): O(V^2) + */ + +int N; +int par[MAX]; +int graph[MAX][MAX], rg[MAX][MAX]; + +bool cont[MAX]; + +// Finds if there's a path between s and t using non-full +// residual edges +bool path(int s, int t) { + queue<int> Q; + Q.push(s); + cont[s] = true; + + while (!Q.empty()) { + int u = Q.front(); Q.pop(); + + if (u == t) + return true; + + for (int i = 0; i < N; ++i) + if (!cont[i] && rg[u][i]) { + cont[i] = true; + par[i] = u; + Q.push(i); + } + } + + return false; +} + + +// Returns maximum flow between s (source) and t (sink) +int edmonds_karp(int s, int t) { + int ans = 0; + par[s] = -1; + + mset(cont, 0); + memcpy(rg, graph, sizeof(graph)); + + // Repeat while there's a valid path between s and t + while (path(s, t)) { + int flow = inf; + + // Get the minimum capacity among all edges of the chosen path + for (int i = t; par[i] != -1; i = par[i]) + flow = min(f, rg[par[i]][i]); + + // Update residual graph + for (int i = t; par[i] != -1; i = par[i]) { + rg[par[i]][i] -= flow; + rg[i][par[i]] += flow; + } + + ans += flow; + mset(cont, 0); + } + + return ans; +} diff --git a/algorithms/graph/ford_fulkerson.cpp b/algorithms/graph/ford_fulkerson.cpp index 0507b51d7c169ac89e02caeb07d7a0f8de397fa1..4e87378944fd75358add61569d09513e13fb6a9a 100644 --- a/algorithms/graph/ford_fulkerson.cpp +++ b/algorithms/graph/ford_fulkerson.cpp @@ -2,7 +2,7 @@ * Ford-Fulkerson * * Complexity (time): O(Ef) - * Complexity (space): O(V + E) + * Complexity (space): O(V^2) */ int N; diff --git a/testing.py b/testing.py index 74cd7163281ca9dfd88553a7942a4260bae7f6c4..51b14e2649083a79d8fd8f8dd0007e768ca6f53e 100644 --- a/testing.py +++ b/testing.py @@ -32,6 +32,7 @@ def gen_code_latex(arr, depth): for i in arr: print('\\' + depth + '{' + i + '}') + def gen_latex(tree): stack = [ (tree, 0) ] depth = ['chapter', 'section', 'subsection']