Jarif_Rahman

Untitled

Feb 18th, 2021
219
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. struct dsu{
  2.     stack<tuple<int, int, int>> st;
  3.     int n;
  4.     vector<int> id;
  5.     vector<vector<int>> comp;
  6.     dsu(int nn){
  7.         n = nn;
  8.         for(int i = 0; i < n;  i++) id.pb(i), comp.pb({i});
  9.     }
  10.     int unite(int a, int b){
  11.         a = id[a], b = id[b];
  12.         if(a == b) return 0;
  13.         if(comp[a].size() > comp[b].size()) swap(a, b);
  14.         st.push({a, b, (int)comp[a].size()});
  15.         while(!comp[a].empty()){
  16.             int x = comp[a].back(); comp[a].pop_back();
  17.             id[x] = b;
  18.             comp[b].pb(x);
  19.         }
  20.         return 1;
  21.     }
  22.     void rollback(){
  23.         auto [a, b, sz] = st.top(); st.pop();
  24.         while(sz--){
  25.             int x = comp[b].back(); comp[b].pop_back();
  26.             id[x] = a;
  27.             comp[a].pb(x);
  28.         }
  29.     }
  30. };
Advertisement
Comments
Add Comment
Please, Sign In to add comment