Naxocist

Edmon Karp's algorithm [maxFlow]

Apr 20th, 2022
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define INF 1e9
  5.  
  6. int res[40][40], f, s, t;
  7. vector<int> parent;
  8.  
  9. void augment(int v, int bottleNeck){
  10.    
  11.     if(v == s){ // found start node
  12.         f = bottleNeck; return ;
  13.     }
  14.  
  15.     if(parent[v] != -1){
  16.         augment(parent[v], min(bottleNeck, res[parent[v]][v])); // reverse to start node by parent
  17.         res[parent[v]][v] -= f;
  18.         res[v][parent[v]] += f;
  19.     }
  20. }
  21.  
  22.  
  23. int main(){
  24.     int n; scanf("%d %d %d", &n, &s, &t);
  25.  
  26.     for(int i=0; i<n; ++i){
  27.         int m; scanf("%d", &m);
  28.  
  29.         for(int j=0; j<m; ++j){
  30.             int v, w; scanf("%d %d", &v, &w);
  31.             res[i][v] = w;
  32.         }
  33.     }
  34.  
  35.     int mf = 0;
  36.     while(1){
  37.         f = 0;
  38.         vector<int> dist(40, INF);
  39.         dist[s] = 0;
  40.         parent.assign(40, -1);
  41.  
  42.         queue<int> q; q.push(s);
  43.         while(!q.empty()){ // breadth first search
  44.             int u = q.front(); q.pop();
  45.  
  46.             if(u == t) break;
  47.             for(int v=0; v < 40; v++){
  48.                 if(res[u][v] > 0 && dist[v] == INF){
  49.                     dist[v] = dist[u] + 1;
  50.                     q.push(v);
  51.                     parent[v] = u; // set parent for every node
  52.                 }
  53.             }
  54.         }
  55.         augment(t, INF); // maximize flow
  56.         if(f == 0) break;
  57.         mf += f;
  58.     }
  59.  
  60.     printf("%d", mf);
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment