nrk009

DSU WITHOUT UNION BY SIZE OR RANK

Jul 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 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];
  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.     parent[min(x,y)] = max(x,y);
  44. }
  45. int main()
  46. {
  47.     fast;
  48.     ll n , q;
  49.     cin >> n >> q ;
  50.     for(int i = 1 ;  i <= n ; i++ )
  51.         parent[i] =  i;
  52.    
  53.     ll ans = n*(n+1)/2;
  54.     while(q--)
  55.     {
  56.         ll x , y;
  57.         cin >> x >> y ;
  58.        
  59.         if(find(x) == find(y)){
  60.         cout << ans << "\n";
  61.         continue;
  62.         }
  63.         ans -= min(find(x) , find(y));
  64.         union_set(x,y);
  65.         cout << ans << "\n";
  66.  
  67.  
  68.  
  69.     }
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.    
  93.     return 0;
  94.    
  95. }
Add Comment
Please, Sign In to add comment