Advertisement
smatskevich

Lesson8

Nov 21st, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class DSU {
  7.  public:
  8.   DSU(int n) : p(n), r(n) { for (int i = 0; i < n; ++i) p[i] = i; cout << "Constructor called\n"; }
  9.   ~DSU() { cout << "Destructor called No ne nuzhen!\n"; }
  10.   int Find(int x) { return p[x] == x ? x : p[x] = Find(p[x]); }
  11.   bool Union(int x, int y) {
  12.     x = Find(x); y = Find(y);
  13.     if (x == y) return false;
  14.     if (r[x] < r[y]) swap(x, y);
  15.     p[y] = x;
  16.     if (r[x] == r[y]) r[x]++;
  17.     return true;
  18.   }
  19.  private:
  20.   vector<int> p;
  21.   vector<int> r;
  22. };
  23.  
  24. int main() {
  25.   {
  26.     DSU dsu(10);
  27.     dsu.Union(1, 2);
  28.     dsu.Union(3, 4);
  29.     dsu.Union(2, 7);
  30.     for (int i = 0; i < 10; ++i)
  31.       cout << dsu.Find(i) << " ";
  32.     cout << "\n";
  33.   }
  34.   cout << "Hello world!\n";
  35.   return 0;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement