Alex_tz307

Edmonds-Karp

Oct 15th, 2020 (edited)
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define INF 0x3f3f3f3f
  3.  
  4. using namespace std;
  5.  
  6. ifstream fin("maxflow.in");
  7. ofstream fout("maxflow.out");
  8.  
  9. int N;
  10. vector < vector < int > > Capacity, Graph;
  11.  
  12. inline void min_self(int& a, int b) {
  13.     a = min(a, b);
  14. }
  15.  
  16. bool BFS(int source, int sink, vector < int >& parent) {
  17.     parent.assign(N + 1, -1);
  18.     parent[source] = -2;
  19.     queue < int > Q;
  20.     Q.emplace(source);
  21.     while(!Q.empty()) {
  22.         int curr = Q.front();
  23.         Q.pop();
  24.         for(int next : Graph[curr])
  25.             if(parent[next] == -1 && Capacity[curr][next]) {
  26.                 parent[next] = curr;
  27.                 if(next == sink)
  28.                     return true;
  29.                 Q.emplace(next);
  30.             }
  31.     }
  32.     return false;
  33. }
  34.  
  35. int max_flow(int source, int sink) {
  36.     int flow = 0;
  37.     vector < int > parent;
  38.     while(BFS(source, sink, parent))
  39.         for(int prev : Graph[sink])
  40.             if(parent[prev] != -1 && Capacity[prev][sink]) {
  41.                 parent[sink] = prev;
  42.                 int new_flow = INF;
  43.                 for(int node = sink; node != source; node = parent[node])
  44.                     min_self(new_flow, Capacity[parent[node]][node]);
  45.                 if(new_flow == 0)
  46.                     continue;
  47.                 flow += new_flow;
  48.                 for(int node = sink; node != source; node = parent[node])  {
  49.                     Capacity[parent[node]][node] -= new_flow;
  50.                     Capacity[node][parent[node]] += new_flow;
  51.                 }
  52.             }
  53.     return flow;
  54. }
  55.  
  56. int main() {
  57.     fin.sync_with_stdio(false);
  58.     fout.sync_with_stdio(false);
  59.     fin.tie(nullptr);
  60.     fout.tie(nullptr);
  61.     int M;
  62.     fin >> N >> M;
  63.     Capacity = vector < vector < int > >(N + 1, vector < int >(N + 1));
  64.     Graph.resize(N + 1);
  65.     while(M--) {
  66.         int u, v, capacity;
  67.         fin >> u >> v >> capacity;
  68.         Capacity[u][v] = capacity;
  69.         Graph[u].emplace_back(v);
  70.         Graph[v].emplace_back(u);
  71.     }
  72.     fout << max_flow(1, N);
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment