NP-Nidzo

Union Find Disjoint Sets (UFDS) - OOP style

Jul 23rd, 2020
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1.  
  2.  
  3. /**------------------------
  4.     Author : NikolaP
  5.     Compiler : C++
  6. -------------------------*/
  7.  
  8. //{         Setup
  9.  
  10.     #include <bits/stdc++.h>
  11.     using namespace std;
  12.  
  13.     typedef long long int ll;
  14.     typedef long double ld;
  15.     typedef vector<int> vi;
  16.  
  17.     const int inf = INT_MAX;
  18.     const bool debug = 0;
  19.  
  20. //}
  21.  
  22.  
  23. class UFDS /// Union find disjoint sets - OOP
  24. {
  25. private:
  26.     vi parent, rank;
  27.  
  28. public:
  29.  
  30.     UFDS(){  /// Default constructor
  31.         parent.assign(1,0);
  32.         rank.assign(1,0);
  33.     };
  34.  
  35.     ~UFDS(); /// Deconstructor
  36.    
  37.     UFDS(int n){ /// Constructor
  38.         parent.assign(n,0);
  39.         rank.assign(n,0);
  40.  
  41.         for (int i = 0; i < n; ++i)
  42.             parent[i] = i;
  43.     }
  44.  
  45.     /// Find the root of a set + Path compression
  46.     int FindSet(int i) { return (parent[i] == i) ? i : ( parent[i] = FindSet(parent[i]) ); }
  47.  
  48.     /// Check if two elements are in the same set
  49.     bool IsSameSet(int i, int j) { return FindSet(i) == FindSet(j); }
  50.  
  51.     /// Unite two sets - Union by rank
  52.     void Union(int i, int j){
  53.         if(!IsSameSet(i,j)){
  54.             int x = FindSet(i), y = FindSet(j);
  55.  
  56.             if(rank[x] > rank[y]) parent[y] = x;
  57.             else{
  58.                 parent[x] = y;
  59.                 if(rank[x] == rank[y]) ++rank[y];
  60.             }
  61.         }
  62.     }
  63. };
  64.  
  65. int main()
  66. {
  67.     ios::sync_with_stdio(false);
  68.     cin.tie(0);
  69.     cout.precision(8);
  70.     //cout << fixed;
  71.  
  72.  
  73.     return 0;
  74.    
  75. }
Advertisement
Add Comment
Please, Sign In to add comment