Alex_tz307

DSU

Feb 24th, 2021 (edited)
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. struct edge {
  2.   int u, v, w;
  3.  
  4.   void read() {
  5.     fin >> u >> v >> w;
  6.   }
  7.  
  8.   bool operator < (const edge &A) const {
  9.     return w < A.w;
  10.   }
  11. };
  12.  
  13. struct DSU {
  14.   vector<int> p, r;
  15.  
  16.   DSU(int N) {
  17.     p.resize(N + 1);
  18.     iota(p.begin(), p.end(), 0);
  19.     r.assign(N + 1, 1);
  20.   }
  21.  
  22.   int get(int x) {
  23.     if (x == p[x])
  24.       return x;
  25.     return p[x] = get(p[x]);
  26.   }
  27.    
  28.   int get_size(int u) {
  29.     return r[get(u)];
  30.   }
  31.    
  32.   bool unite(int u, int v) {
  33.     int x = get(u), y = get(v);
  34.     if (x == y)
  35.       return false;
  36.     if (r[x] > r[y])
  37.       swap(x, y);
  38.     p[x] = y;
  39.     r[y] += r[x];
  40.     return true;
  41.   }
  42. };
Add Comment
Please, Sign In to add comment