bhupixb

DSU on matrix

Feb 25th, 2020
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1.  
  2. struct DSU_on_Matrix {
  3. // Don't forget to initialize n and m
  4. int n, m;
  5. vector<int> par, sz;
  6.  
  7. DSU_on_Matrix(int N = 2e5 + 3) {
  8. par.resize(N);
  9. sz.assign(N, 1);
  10. iota(par.begin(), par.end(), 0);
  11. n = -1, m = -1;
  12. }
  13.  
  14. int get(int r, int c) {
  15. return (r - 1) * m + c;
  16. }
  17.  
  18. int find(int x) {
  19. if (x == par[x]) return x;
  20. return par[x] = find(par[par[x]]);
  21. }
  22.  
  23. void join(int x, int y) {
  24. assert(n != -1);
  25. int px = find(x), py = find(y);
  26. if (px == py) return;
  27. if (sz[px] > sz[py]) swap(px, py);
  28. par[px] = py;
  29. sz[py] += sz[px];
  30. }
  31.  
  32. };
Add Comment
Please, Sign In to add comment