Josif_tepe

Untitled

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