Advertisement
Josif_tepe

Untitled

Mar 7th, 2025
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. const int maxn = 1e5 + 10;
  4. int idx[maxn];
  5. int sz[maxn];
  6. void init() {
  7.     for(int i = 0; i < maxn; i++) {
  8.         idx[i] = i;
  9.         sz[i] = 1;
  10.     }
  11. }
  12.  
  13. int find_root(int A) {
  14.     while(idx[A] != A) {
  15.         idx[A] = idx[idx[A]];
  16.         A = idx[A];
  17.     }
  18.     return A;
  19. }
  20. void unite(int A, int B) {
  21.     int root_A = find_root(A);
  22.     int root_B = find_root(B);
  23.     if(root_A != root_B) {
  24.         if(sz[root_A] < sz[root_B]) {
  25.             sz[root_B] += sz[root_A];
  26.             idx[root_A] = idx[root_B];
  27.         }
  28.         else {
  29.             idx[root_B] = idx[root_A];
  30.             sz[root_A] += sz[root_B];
  31.         }
  32.     }
  33. }
  34. bool check_if_they_belong_to_same_set(int A, int B) {
  35.     return find_root(A) == find_root(B);
  36. }
  37. int main()
  38. {
  39.     init();
  40.     while(true) {
  41.         string s;
  42.         cin >> s;
  43.         if(s == "end") {
  44.             break;
  45.         }
  46.         if(s == "union") {
  47.             int a, b;
  48.             cin >> a >> b;
  49.             unite(a, b);
  50.         }
  51.         else {
  52.             int a, b;
  53.             cin >> a >> b;
  54.             cout << check_if_they_belong_to_same_set(a, b) << endl;
  55.         }
  56.     }
  57.  
  58.    
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement