Advertisement
milon34

Disjoint Set Union

Apr 3rd, 2025 (edited)
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.45 KB | None | 0 0
  1. struct DSU {
  2.     vector<int> par, rnk;
  3.     DSU(int n) : par(n + 1), rnk(n + 1, 1) {
  4.         for (int i = 0; i < par.size(); i++) par[i] = i;
  5.     }
  6.     int find(int v) {
  7.         return (par[v] == v) ? v : (par[v] = find(par[v]));
  8.     }
  9.     void uni(int a, int b) {
  10.         a = find(a), b = find(b);
  11.         if (a != b) {
  12.             if (rnk[a] < rnk[b]) swap(a, b);
  13.             par[b] = a;
  14.             rnk[a] += rnk[b];
  15.         }
  16.     }
  17. };
  18.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement