Advertisement
Josif_tepe

Untitled

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