ThegeekKnight16

Union-find semi-persistente

Aug 6th, 2025
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> pai, sub, edge;
  4.  
  5. int find(int v) {return (v == pai[v] ? v : find(pai[v]));}
  6. void une(int x, int y, int t)
  7. {
  8.     x = find(x); y = find(y);
  9.     if (x == y) return;
  10.     if (sub[x] < sub[y]) swap(x, y);
  11.     pai[y] = x; sub[x] += sub[y]; edge[y] = t;
  12. }
  13.  
  14. int main()
  15. {
  16.     ios_base::sync_with_stdio(false);
  17.     cin.tie(NULL);
  18.     int N, M, Q; cin >> N >> M >> Q;
  19.     pai.resize(N+1); iota(pai.begin(), pai.end(), 0);
  20.     sub.resize(N+1); fill(sub.begin(), sub.end(), 1);
  21.     edge.resize(N+1); fill(edge.begin(), edge.end(), 0);
  22.  
  23.     for (int i = 1; i <= M; i++)
  24.     {
  25.         int x, y; cin >> x >> y;
  26.         une(x, y, i);
  27.     }
  28.  
  29.     while (Q--)
  30.     {
  31.         int x, y; cin >> x >> y;
  32.         if (find(x) != find(y)) {cout << -1 << '\n'; continue;}
  33.         int resp = 0;
  34.         while (x != y)
  35.         {
  36.             if (sub[x] < sub[y]) {resp = max(resp, edge[x]); x = pai[x];}
  37.             else {resp = max(resp, edge[y]); y = pai[y];}
  38.         }
  39.         cout << resp << '\n';
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment