Advertisement
kartikkukreja

Union Find / Disjoint Set Data Structure

May 7th, 2013
1,949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. class UF    {
  2.     int *id, cnt, *sz;
  3. public:
  4.     // Create an empty union find data structure with N isolated sets.
  5.     UF(int N)   {
  6.         cnt = N;
  7.     id = new int[N];
  8.     sz = new int[N];
  9.         for(int i=0; i<N; i++)  {
  10.             id[i] = i;
  11.         sz[i] = 1;
  12.     }
  13.     }
  14.     ~UF()   {
  15.     delete [] id;
  16.     delete [] sz;
  17.     }
  18.     // Return the id of component corresponding to object p.
  19.     int find(int p) {
  20.         int root = p;
  21.         while (root != id[root])
  22.             root = id[root];
  23.         while (p != root) {
  24.             int newp = id[p];
  25.             id[p] = root;
  26.             p = newp;
  27.         }
  28.         return root;
  29.     }
  30.     // Replace sets containing x and y with their union.
  31.     void merge(int x, int y)    {
  32.         int i = find(x);
  33.         int j = find(y);
  34.         if (i == j) return;
  35.        
  36.         // make smaller root point to larger one
  37.         if   (sz[i] < sz[j])    {
  38.         id[i] = j;
  39.         sz[j] += sz[i];
  40.     } else  {
  41.         id[j] = i;
  42.         sz[i] += sz[j];
  43.     }
  44.         cnt--;
  45.     }
  46.     // Are objects x and y in the same set?
  47.     bool connected(int x, int y)    {
  48.         return find(x) == find(y);
  49.     }
  50.     // Return the number of disjoint sets.
  51.     int count() {
  52.         return cnt;
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement