Josif_tepe

Untitled

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