Advertisement
slash0t

dsu

Aug 2nd, 2024 (edited)
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.46 KB | None | 0 0
  1. struct dsu {
  2.     int n, unions;
  3.     vector<int> t, count;
  4.  
  5.     dsu(int nn) {
  6.         n = nn;
  7.         unions = n;
  8.  
  9.         t.assign(n, 0);
  10.         for (int i = 0; i < n; i++) t[i] = i;
  11.         count.assign(n, 1);
  12.     }
  13.  
  14.     int find(int i) {
  15.         if (i == t[i]) return i;
  16.         return t[i] = find(t[i]);
  17.     }
  18.  
  19.     bool unite(int a, int b) {
  20.         a = find(a);
  21.         b = find(b);
  22.  
  23.         if (a == b) return 0;
  24.         unions--;
  25.  
  26.         if (count[a] > count[b]) swap(a, b);
  27.  
  28.         t[a] = b;
  29.         count[b] += count[a];
  30.         return 1;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement