Advertisement
tuki2501

NKFLOW.cpp

Oct 24th, 2022
754
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1005;
  5.  
  6. int n, m, s, t;
  7. vector<int> adj[N];
  8. int capa[N][N], flow[N][N], level[N];
  9.  
  10. bool bfs(int f) {
  11.   memset(level, 0, sizeof(level));
  12.   queue<pair<int,int>> q;
  13.   q.push({1, s});
  14.   while (q.size()) {
  15.     auto [d, i] = q.front(); q.pop();
  16.     if (level[i]) continue;
  17.     level[i] = d;
  18.     if (i == t) return true;
  19.     for (auto &j : adj[i]) {
  20.       if (!level[j] && capa[i][j] - flow[i][j] >= f) {
  21.         q.push({d + 1, j});
  22.       }
  23.     }
  24.   }
  25.   return false;
  26. }
  27.  
  28. bool dfs(int i, int f) {
  29.   if (i == t) return true;
  30.   for (auto &j : adj[i]) {
  31.     if (level[j] == level[i] + 1 && capa[i][j] - flow[i][j] >= f) {
  32.       flow[i][j] += f;
  33.       flow[j][i] -= f;
  34.       if (dfs(j, f)) return true;
  35.       flow[i][j] -= f;
  36.       flow[j][i] += f;
  37.     }
  38.   }
  39.   return false;
  40. }
  41.  
  42. int main() {
  43.   cin >> n >> m >> s >> t;
  44.   for (int i = 1; i <= m; i++) {
  45.     int u, v, c;
  46.     cin >> u >> v >> c;
  47.     adj[u].push_back(v);
  48.     adj[v].push_back(u);
  49.     capa[u][v] += c;
  50.     // capa[v][u] += c;
  51.   }
  52.   int ans = 0;
  53.   for (int f = (1 << 30); f; f >>= 1) {
  54.     while (bfs(f)) {
  55.       while (dfs(s, f)) ans += f;
  56.     }
  57.   }
  58.   cout << ans << '\n';
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement