Advertisement
LA77

Untitled

Feb 25th, 2025
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin("disjoint.in");
  6. ofstream fout("disjoint.out");
  7.  
  8. struct DSU
  9. {
  10.     vector<int>father, sz;
  11.  
  12.     DSU(int n)
  13.     {
  14.         father.resize(n + 1);
  15.         sz.resize(n + 1);
  16.  
  17.         for(int i = 1; i <= n; ++ i)
  18.         {
  19.             father[i] = i;
  20.             sz[i] = 1;
  21.         }
  22.     }
  23.  
  24.     int FindFather(int x)
  25.     {
  26.         if(father[x] == x)
  27.             return x;
  28.         return father[x] = FindFather(father[x]);
  29.     }
  30.  
  31.     void Join(int x, int y)
  32.     {
  33.         int father_x = FindFather(x);
  34.         int father_y = FindFather(y);
  35.  
  36.         if(sz[father_x] > sz[father_y])
  37.             swap(father_x, father_y);
  38.  
  39.         father[father_x] = father_y;
  40.         sz[father_y] += sz[father_x];
  41.     }
  42.  
  43.     bool SameSet(int x, int y)
  44.     {
  45.         return FindFather(x) == FindFather(y);
  46.     }
  47. };
  48.  
  49. const int NMAX = 1e5+5;
  50. int n, m;
  51. DSU pdm(NMAX);
  52.  
  53. int main()
  54. {
  55.     ios::sync_with_stdio(false);
  56.     fin.tie(NULL);
  57.     fout.tie(NULL);
  58.  
  59.     fin >> n >> m;
  60.  
  61.     while(m--)
  62.     {
  63.         int op, x, y;
  64.  
  65.         fin >> op >> x >> y;
  66.  
  67.         if(op == 1)
  68.         {
  69.             pdm.Join(x, y);
  70.         }
  71.         else
  72.         {
  73.             if(pdm.SameSet(x, y))
  74.                 fout << "DA\n";
  75.             else
  76.                 fout << "NU\n";
  77.         }
  78.     }
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement