eynizadeMurad

Union Find (DSU)

Oct 10th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3. #define fast_read ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  4. #define SIZE 100001
  5. using namespace std;
  6. ll n,m,q,x,y,par[SIZE],sze[SIZE];
  7. char ty;
  8. void init() {
  9.     for (int i = 1;i<=n;i++) {
  10.         sze[i] = 1;
  11.         par[i] = i;
  12.     }
  13. }
  14. ll f_root(ll a) {
  15.     while (par[a] != a) {
  16.         par[a] = par[par[a]];
  17.         a = par[a];
  18.     }
  19.     return a;
  20. }
  21. void _union(ll a,ll b) {
  22.     ll roota = f_root(a);
  23.     ll rootb = f_root(b);
  24.     if (sze[roota] + sze[rootb] > m || roota == rootb)return;
  25.     if (sze[roota] < sze[rootb]) {
  26.         par[roota] = par[rootb];
  27.         sze[rootb] += sze[roota];
  28.     }
  29.     else {
  30.         par[rootb] = par[roota];
  31.         sze[roota] += sze[rootb];
  32.     }
  33. }
  34. string check(ll a,ll b) {
  35.     ll roota = f_root(a);
  36.     ll rootb = f_root(b);
  37.     if (roota == rootb)return "Yes";
  38.     return "No";
  39. }
  40. int main()
  41. {
  42.     cin>>n>>m>>q;
  43.     init();
  44.     while (q--) {
  45.         cin>>ty;
  46.         if (ty == 'A') {
  47.             cin>>x>>y;
  48.             _union(x,y);
  49.             /*cout<<endl;
  50.             for (int i = 1;i<=n;i++)
  51.                 cout<<par[i]<<" ";
  52.             cout<<endl;
  53.             for (int i = 1;i<=n;i++)
  54.                 cout<<sze[i]<<" ";
  55.             cout<<endl<<endl;*/
  56.         }
  57.         else if (ty == 'E') {
  58.             cin>>x>>y;
  59.             cout<<check(x,y)<<endl;
  60.         }
  61.         else {
  62.             cin>>x;
  63.             cout<<sze[f_root(x)]<<endl;
  64.         }
  65.     }
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment