Advertisement
Josif_tepe

Untitled

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