Advertisement
Fronzilla

coconuts

Jun 20th, 2023
1,065
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. #define INF 9999999
  6.  
  7. using namespace std;
  8.  
  9. int n;
  10. vector<vector<int>> capacity;
  11. vector<vector<int>> adj;
  12.  
  13. int bfs(int s, int t, vector<int>& parent) {
  14.     fill(parent.begin(), parent.end(), -1);
  15.     parent[s] = -2;
  16.     queue<pair<int, int>> q;
  17.     q.push({s, INF});
  18.  
  19.     while (!q.empty()) {
  20.         int cur = q.front().first;
  21.         int flow = q.front().second;
  22.         q.pop();
  23.  
  24.         for (int next : adj[cur]) {
  25.             if (parent[next] == -1 && capacity[cur][next]) {
  26.                 parent[next] = cur;
  27.                 int new_flow = min(flow, capacity[cur][next]);
  28.                 if (next == t)
  29.                     return new_flow;
  30.                 q.push({next, new_flow});
  31.             }
  32.         }
  33.     }
  34.     return 0;
  35. }
  36.  
  37. int maxflow(int s, int t) {
  38.     int flow = 0;
  39.     vector<int> parent(n+3);
  40.     int new_flow;
  41.  
  42.     while (new_flow = bfs(s, t, parent)) {
  43.         flow += new_flow;
  44.         int cur = t;
  45.         while (cur != s) {
  46.             int prev = parent[cur];
  47.             capacity[prev][cur] -= new_flow;
  48.             capacity[cur][prev] += new_flow;
  49.             cur = prev;
  50.         }
  51.     }
  52.  
  53.     return flow;
  54. }
  55.  
  56. int main()
  57. {
  58.     int m;
  59.     scanf("%d%d",&n,&m);
  60.     while (n != 0 || m != 0)
  61.     {
  62.         adj.resize(n+3);
  63.         capacity = vector< vector<int> > (n+3, vector<int> (n+3, 0));
  64.         int a, b, v;
  65.         for(int i = 1; i <= n; i++)
  66.         {
  67.             scanf("%d", &v);
  68.             if(v == 0)
  69.             {
  70.                 adj[0].push_back(i);
  71.                 capacity[0][i] = 1;
  72.             }
  73.             else if(v == 1)
  74.             {
  75.                 adj[i].push_back(n+1);
  76.                 capacity[i][n+1] = 1;
  77.             }
  78.         }
  79.         for(int i = 0; i < m; i++)
  80.         {
  81.             scanf("%d%d", &a, &b);
  82.             adj[a].push_back(b);
  83.             capacity[a][b] = 1;
  84.             adj[b].push_back(a);
  85.             capacity[b][a] = 1;
  86.         }
  87.         int corte = maxflow(0,n+1);
  88.         printf("%d\n", corte);
  89.         adj.clear();
  90.         scanf("%d%d",&n,&m);
  91.     }
  92.    
  93.     return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement