Advertisement
Guest User

Untitled

a guest
Nov 26th, 2014
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <vector>
  4. #include <fstream>
  5. #include <queue>
  6. #include <limits.h>
  7.  
  8. bool bfs(std::vector<std::vector<int> >& capacities, int s, int f, std::vector<int>& parents, int n) {
  9. std::queue<int> queue;
  10. std::vector<bool> visited(n, false);
  11. parents[s] = -1;
  12. visited[s] = true;
  13. queue.push(s);
  14. while (!queue.empty()){
  15. int from = queue.front();
  16. queue.pop();
  17. for (int i = 0; i < n; i++){
  18. if (!visited[i] && capacities[from][i] > 0) {
  19. queue.push(i);
  20. parents[i] = from;
  21. visited[i] = true;
  22. }
  23. }
  24. }
  25. return visited[f];
  26. }
  27.  
  28. int edmonds_karp(std::vector<std::vector<int> >& capacities, int s, int f, int n){
  29. int u, v;
  30. std::vector<int> parents(n, -1);
  31. int max_flow = 0;
  32. while (bfs(capacities, s, f, parents, n)){
  33. int path_flow = INT_MAX;
  34. for (v = f; v != s; v = parents[v]){
  35. u = parents[v];
  36. path_flow = std::min(path_flow, capacities[u][v]);
  37. }
  38. for (v = f; v != s; v = parents[v]) {
  39. u = parents[v];
  40. capacities[u][v] -= path_flow;
  41. capacities[v][u] += path_flow;
  42. }
  43. max_flow += path_flow;
  44. }
  45. return max_flow;
  46. }
  47.  
  48. int main() {
  49. #ifndef DEBUG
  50. std::ifstream in("maxflow.in");
  51. std::ofstream out("maxflow.out");
  52. #endif
  53. #ifdef DEBUG
  54. std::ifstream in("input.txt");
  55. std::ofstream out("output.txt");
  56. #endif
  57. int n, m;
  58. in >> n >> m;
  59. std::vector<std::vector<int> > adjacency_list(n, std::vector<int>(n, 0));
  60. for (int i = 0; i < m; i++) {
  61. int from, to, cost;
  62. in >> from >> to >> cost;
  63. adjacency_list[from - 1][to - 1] = cost;
  64. }
  65. out << edmonds_karp(adjacency_list, 0, n - 1, n);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement