Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. vector<vector<int>> capacity; // storing the capacity of each edge
  2. vector<vector<int>> mat; // graph representation in adjacency matrix
  3.  
  4. // utilizing Breadth First Search (BFS) algorithm
  5. int bfs(int s, int t, vector<int>& prev) {
  6.     fill(prev.begin(), prev.end(), -1); // initalize previous nodes with -1
  7.     prev[s] = -2;
  8.     queue<pair<int, int>> q;
  9.     q.push({s, INF});
  10.  
  11.     // while queue is not empty
  12.     while (!q.empty()) {
  13.         int cur = q.front().first;
  14.         int flow = q.front().second;
  15.         q.pop();
  16.  
  17.         for (int next : mat[cur]) {
  18.             if (prev[next] == -1 && capacity[cur][next]) {
  19.                 prev[next] = cur;
  20.                 int new_flow = min(flow, capacity[cur][next]);
  21.                 if (next == t)
  22.                     return new_flow;
  23.                 q.push({next, new_flow});
  24.             }
  25.         }
  26.     }
  27.  
  28.     return 0;
  29. }
  30.  
  31. // computing maximum flow in the graph
  32. int maxflow(int s, int t) {
  33.     int flow = 0;
  34.     vector<int> prev(n);
  35.     int new_flow;
  36.  
  37.     // doing BFS in each iteration, finding the shortest path available from 's' to 't'
  38.     while (new_flow = bfs(s, t, prev)) {
  39.         flow += new_flow;
  40.         int cur = t;
  41.         while (cur != s) {
  42.             int prev = prev[cur];
  43.             capacity[prev][cur] -= new_flow;
  44.             capacity[cur][prev] += new_flow;
  45.             cur = prev;
  46.         }
  47.     }
  48.  
  49.     return flow;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement