nrk009

DSU BY UNION BY SIZE OR RANK

Jul 24th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
  4. #define ll long long
  5. #define ld long double
  6. #define pb push_back
  7. #define fe first
  8. #define se second
  9. #define st(x) sort(x.begin(),x.end())
  10. #define rst(x) sort(x.rbegin(), x.rend())
  11. #define all(x) x.begin(),x.end()
  12. long double pi = 3.14159265358979323;
  13.  
  14. const double EPS = 1e-12;
  15. const int N = 1e5 + 1;
  16. const int mod = 1e9 + 7;
  17.  
  18. ll parent[N],sz[N],mx[N],ans;
  19. //dsu
  20. //path compression without union by size or rank;
  21. ll find(ll v)
  22. {
  23.     if(v == parent[v])
  24.         return v;
  25.     return parent[v] = find(parent[v]);
  26. }
  27. //non - recursive implementation of path compression find function
  28. /*ll find(ll v)
  29. {
  30.     while(v != parent[v])
  31.     {
  32.         parent[v] = parent[parent[v]];
  33.         v = parent[v];
  34.     }
  35.     return v;
  36. }*/
  37. void union_set(ll x , ll y)
  38. {
  39.     x = find(x);
  40.     y = find(y);
  41.     if(x == y)
  42.         return;
  43.     if(sz[x] > sz[y])
  44.         swap(x,y);
  45.     ans -= min(mx[x],mx[y]);
  46.     //cout << ans << " ";
  47.     mx[y] = max(mx[x],mx[y]);
  48.     parent[x] = y;
  49.     sz[y] += sz[x];
  50.  
  51.  
  52.    
  53. }
  54. int main()
  55. {
  56.     fast;
  57.     ll n , q;
  58.     cin >> n >> q ;
  59.     for(int i = 1 ;  i <= n ; i++ ){
  60.         parent[i] =  i;
  61.         sz[i] = i ;
  62.         mx[i] =  i;
  63.     }
  64.    
  65.     ans = n*(n+1)/2;
  66.     while(q--)
  67.     {
  68.         ll x , y;
  69.         cin >> x >> y ;
  70.        
  71.         if(find(x) == find(y)){
  72.         cout << ans << "\n";
  73.         continue;
  74.         }
  75.         union_set(x,y);
  76.         cout << ans << "\n";
  77.  
  78.  
  79.  
  80.     }
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103.    
  104.     return 0;
  105.    
  106. }
Add Comment
Please, Sign In to add comment