Josif_tepe

Untitled

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