Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. class QuickUF {
  2. private:
  3.   vector<int> ids;
  4.   vector<size_t> sizes;
  5.   int count; //# of connected components.
  6.  
  7. public:
  8.   QuickUF(int n) {
  9.     ids.resize(n);
  10.     sizes.resize(n);
  11.     count = 0;
  12.     for (int i = 0; i < n; i++) {
  13.       ids[i] = i;
  14.       sizes[i] = 1;
  15.       count++;
  16.     }
  17.   }
  18.    
  19.   int find(int i) { // path compression
  20.     return root(i);
  21.   }
  22.    
  23.   int getCount() {
  24.       return count;
  25.   }
  26.   int root(int a) {
  27.     while (a != ids[a]) {
  28.       ids[a] = ids[ids[a]]; // path compression
  29.       a = ids[a];
  30.     }
  31.  
  32.     return a;
  33.   }
  34.   void union_nodes(int a, int b) {
  35.     int ra = root(a);
  36.     int rb = root(b);
  37.     if(ra != rb) {
  38.         count--;
  39.         if (sizes[ra] >= sizes[rb]) {
  40.             // put in b tree
  41.             ids[ra] = rb;
  42.             sizes[rb] += sizes[ra];
  43.         } else {
  44.             ids[rb] = ra;
  45.             sizes[ra] += sizes[rb];
  46.         }
  47.     }
  48.   }
  49.   bool connected(int a, int b) {
  50.     int ra = root(a);
  51.     int rb = root(b);
  52.     return ra == rb;
  53.   }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement