Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. struct HLDecomposition {
  2. int n;
  3. vector<vector<int>> es;
  4. vector<int> par;
  5. vector<int> dep;
  6. vector<int> head;
  7. vector<int> next;
  8. vector<int> vid;
  9. HLDecomposition(int n)
  10. : n(n), es(n), par(n), dep(n), head(n), next(n, -1), vid(n) {}
  11. void add_edge(int v, int u) {
  12. es[v].push_back(u);
  13. es[u].push_back(v);
  14. }
  15. int dfs(int v = 0, int d = 0, int p = -1) {
  16. if (p != -1) par[v] = p;
  17. dep[v] = d;
  18. int mx = 0;
  19. int cnt = 1;
  20. for (int u : es[v]) {
  21. if (u == p) continue;
  22. int c = dfs(u, d + 1, v);
  23. cnt += c;
  24. if (mx < c) mx = c, next[v] = u;
  25. }
  26. return cnt;
  27. }
  28. void bfs(int v = 0) {
  29. int k = 0;
  30. queue<int> q;
  31. q.emplace(v);
  32. while (!q.empty()) {
  33. int h = q.front(); q.pop();
  34. for (int v = h; v != -1; v = next[v]) {
  35. vid[v] = k++;
  36. head[v] = h;
  37. for (int u : es[v]) {
  38. if (u == par[v] || u == next[v]) continue;
  39. q.push(u);
  40. }
  41. }
  42. }
  43. }
  44. void build() {
  45. dfs();
  46. bfs();
  47. }
  48. int lca(int v, int u) {
  49. while (true) {
  50. if (vid[u] > vid[v]) swap(u, v);
  51. if (head[u] == head[v]) return u;
  52. v = par[head[v]];
  53. }
  54. }
  55. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement