dvjsharma

Untitled

Aug 26th, 2025
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct DSU {
  5.     vector<int> parent, sz;
  6.     stack<pair<int,int>> history;  // store (u, size[u]) before merge
  7.     int components;
  8.  
  9.     DSU(int n) {
  10.         parent.resize(n);
  11.         sz.assign(n, 1);
  12.         iota(parent.begin(), parent.end(), 0);
  13.         components = n;
  14.     }
  15.  
  16.     int find(int x) {
  17.         while (x != parent[x]) x = parent[x];
  18.         return x;
  19.     }
  20.  
  21.     bool unite(int a, int b) {
  22.         a = find(a), b = find(b);
  23.         if (a == b) return false;
  24.  
  25.         if (sz[a] < sz[b]) swap(a, b); // union by size
  26.         history.push({b, sz[a]});      // save state for rollback
  27.         parent[b] = a;
  28.         sz[a] += sz[b];
  29.         components--;
  30.         return true;
  31.     }
  32.  
  33.     void rollback() {
  34.         if (history.empty()) return;
  35.         auto [b, prevSizeA] = history.top();
  36.         history.pop();
  37.         int a = parent[b];
  38.         parent[b] = b;
  39.         sz[a] = prevSizeA;
  40.         components++;
  41.     }
  42. };
  43.  
  44. int main() {
  45.     int n = 5;
  46.     DSU dsu(n);
  47.  
  48.     dsu.unite(0, 1);
  49.     dsu.unite(2, 3);
  50.     cout << "Components: " << dsu.components << "\n"; // 3
  51.  
  52.     dsu.unite(1, 2);
  53.     cout << "Components: " << dsu.components << "\n"; // 2
  54.  
  55.     dsu.rollback(); // undo last union
  56.     cout << "Components after rollback: " << dsu.components << "\n"; // 3
  57.  
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment