Advertisement
MinhNGUYEN2k4

Disjoin Set Union

Aug 9th, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int long long
  3. using namespace std;
  4. const int N = 100005;
  5.  
  6. int n,m;
  7. int cha[N],hang[N];
  8.  
  9. int getroot(int u)
  10. {
  11.     if (cha[u] != u) cha[u] = getroot(cha[u]);
  12.     return cha[u];
  13. }
  14.  
  15. void join (int u, int v)
  16. {
  17.     u = getroot(u); v = getroot(v);
  18.     if (u==v) return;
  19.     if (hang[u] == hang[v]) hang[u]++;
  20.     if (hang[u] < hang[v]) cha[u] = v;
  21.     else cha[v]=u;
  22. }
  23.  
  24. signed main()
  25. {
  26.     ios_base::sync_with_stdio(false);
  27.     cin.tie(0);cout.tie(0);
  28.     freopen("DISJOINT.INP","r",stdin);
  29.     freopen("DISJOINT.OUT","w",stdout);
  30.     cin >> n >> m;
  31.     for(int i=1; i<=n; ++i)
  32.     {
  33.         cha[i]=i;
  34.         hang[i]=0;
  35.     }
  36.     for(int i=1; i<=m; ++i)
  37.     {
  38.         int type,u,v;
  39.         cin >> type >> u >> v;
  40.         if (type==1)
  41.         {
  42.             join(u,v);
  43.         }
  44.         else
  45.         {
  46.             if (getroot(u) == getroot(v)) cout << 1 << endl;
  47.             else cout << 0 << endl;
  48.         }
  49.     }
  50.     return 0;
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement