Advertisement
Vince14

Max Flow Sample Code

Oct 31st, 2023
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | Source Code | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #define INF 987654321
  7. using namespace std;
  8.  
  9. int n, c[52][52], f[52][52];
  10. vector<int> a[52];
  11.  
  12. int ctoi(char c)
  13. {
  14.     if (c >= 'a' && c <= 'z')
  15.         return c - 'a';
  16.     else
  17.         return c - 'A' + 26;
  18. }
  19.  
  20. // Edmond Karp (BFS)
  21. void network_flow()
  22. {
  23.     int total = 0, s = ctoi('A'), t = ctoi('Z');
  24.     while (true)
  25.     {
  26.         int prev[52];
  27.         memset(prev, -1, sizeof(prev));
  28.         queue<int> q;
  29.         q.push(s);
  30.         while (!q.empty() && prev[t] == -1)
  31.         {
  32.             int now = q.front();
  33.             q.pop();
  34.             for (int next : a[now])
  35.             {
  36.                 if (c[now][next] - f[now][next] > 0 && prev[next] == -1)
  37.                 {
  38.                     q.push(next);
  39.                     prev[next] = now;
  40.                     if (next == t)
  41.                         break;
  42.                 }
  43.             }
  44.         }
  45.  
  46.         if (prev[t] == -1)
  47.             break;
  48.  
  49.         int flow = INF; // 증가경로 중에 최소값
  50.         for (int i = t; i != s; i = prev[i])
  51.             flow = min(flow, c[prev[i]][i] - f[prev[i]][i]);
  52.         for (int i = t; i != s; i = prev[i])
  53.         {
  54.             f[prev[i]][i] += flow; // 정방향 +
  55.             f[i][prev[i]] -= flow; // 역방향 -
  56.         }
  57.         total += flow;
  58.     }
  59.     printf("%d\n", total);
  60. }
  61.  
  62. int main()
  63. {
  64.     scanf("%d", &n);
  65.     while (n--)
  66.     {
  67.         char u, v;
  68.         int w;
  69.         scanf(" %c %c %d", &u, &v, &w);
  70.         u = ctoi(u);
  71.         v = ctoi(v);
  72.         c[u][v] += w;
  73.         c[v][u] += w;
  74.         a[u].push_back(v);
  75.         a[v].push_back(u);
  76.     }
  77.     network_flow();
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement