Advertisement
Guest User

EK

a guest
Sep 16th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. int res[MAX_V][MAX_V], mf, f, s, t;
  2. // global variables
  3. vi p;
  4. // p stores the BFS spanning tree from s, we use it to find path s -> t
  5. void augment(int v, int minEdge) {
  6. // traverse BFS spanning tree from s to t
  7. if (v == s) { f = minEdge; return; } // record minEdge in a global variable f
  8. else if (p[v] != -1) { augment(p[v], min(minEdge, res[p[v]][v])); // recursive
  9. res[p[v]][v] -= f; res[v][p[v]] += f; }
  10. // update
  11. }
  12. // inside int main()
  13. // set up the 2d AdjMat ‘res’, ‘s’, and ‘t’ with appropriate values
  14. mf = 0;
  15. // mf stands for max_flow
  16. while (1) {
  17. // O(VE^2) (actually O(V^3E) Edmonds Karp’s algorithm
  18. f = 0;
  19. // run BFS, compare with the original BFS shown in Section 4.2.2
  20. vi dist(MAX_V, INF); dist[s] = 0; queue<int> q; q.push(s);
  21. p.assign(MAX_V, -1);
  22. // record the BFS spanning tree, from s to t!
  23. while (!q.empty()) {
  24. int u = q.front(); q.pop();
  25. if (u == t) break;
  26. // immediately stop BFS if we already reach sink t
  27. for (int v = 0; v < MAX_V; v++)
  28. // note: this part is slow
  29. if (res[u][v] > 0 && dist[v] == INF)
  30. dist[v] = dist[u] + 1, q.push(v), p[v] = u;
  31. // three lines in one!
  32. }
  33. augment(t, INF); // find the minimum edge weight ‘f’ along this path, if any
  34. if (f == 0) break;
  35. // we cannot send any more flow (‘f’ = 0), terminate
  36. mf += f;
  37. // we can still send a flow, increase the max flow!
  38. }
  39. printf("%d\n", mf);
  40. // this is the max flow value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement