Advertisement
Guest User

Centroid Decomposition

a guest
Aug 18th, 2020
2,353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. struct centroid {
  2. vector<vector<int> > edges;
  3. vector<bool> vis;
  4. vector<int> par;
  5. vector<int> sz;
  6. int n;
  7.  
  8. void init(int s) {
  9. n = s;
  10. edges = vector<vector<int> >(n, vector<int>());
  11. vis = vector<bool>(n, 0);
  12. par = vector<int>(n);
  13. sz = vector<int>(n);
  14. }
  15.  
  16. void edge(int a, int b) {
  17. edges[a].pb(b);
  18. edges[b].pb(a);
  19. }
  20.  
  21. int find_size(int v, int p = -1) {
  22. if (vis[v]) return 0;
  23. sz[v] = 1;
  24.  
  25. for (int x: edges[v]) {
  26. if (x != p) {
  27. sz[v] += find_size(x, v);
  28. }
  29. }
  30.  
  31. return sz[v];
  32. }
  33.  
  34. int find_centroid(int v, int p, int n) {
  35. for (int x: edges[v]) {
  36. if (x != p) {
  37. if (!vis[x] && sz[x] > n / 2) {
  38. return find_centroid(x, v, n);
  39. }
  40. }
  41. }
  42.  
  43. return v;
  44. }
  45.  
  46. void init_centroid(int v = 0, int p = -1) {
  47. find_size(v);
  48.  
  49. int c = find_centroid(v, -1, sz[v]);
  50. vis[c] = true;
  51. par[c] = p;
  52.  
  53. for (int x: edges[c]) {
  54. if (!vis[x]) {
  55. init_centroid(x, c);
  56. }
  57. }
  58. }
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement