Josif_tepe

Untitled

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