Advertisement
ThegeekKnight16

Union-Find : Remover arestas

Jul 1st, 2025
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int MAXN = 1e5 + 10;
  4. array<int, MAXN> pai, sub;
  5. int qComp = 0;
  6.  
  7. int find(int v) {return pai[v] = (pai[v] == v ? v : find(pai[v]));}
  8. void une(int x, int y)
  9. {
  10.     x = find(x); y = find(y);
  11.     if (x == y) return;
  12.     if (sub[x] < sub[y]) swap(x, y);
  13.     pai[y] = x; sub[x] += sub[y];
  14.     --qComp;
  15. }
  16.  
  17. int main()
  18. {
  19.     ios_base::sync_with_stdio(false);
  20.     cin.tie(NULL);
  21.     int N, M; cin >> N >> M;
  22.     vector<pair<int, int>> edges(M);
  23.     for (auto &[x, y] : edges) cin >> x >> y;
  24.    
  25.     for (int i = 1; i <= N; i++) {pai[i] = i; sub[i] = 1;}
  26.     qComp = N;
  27.    
  28.     vector<int> resp;
  29.     reverse(edges.begin(), edges.end());
  30.     for (auto [x, y] : edges)
  31.     {
  32.         une(x, y);
  33.         //cout << qComp << '\n'; cuidado! estamos fazendo ao contrario!
  34.         resp.push_back(qComp);
  35.     }
  36.     reverse(resp.begin(), resp.end());
  37.    
  38.     for (auto x : resp) cout << x << '\n';
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement