Advertisement
Josif_tepe

Untitled

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