1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| namespace hld { int siz[maxn], dep[maxn], fa[maxn], son[maxn], top[maxn]; void dfs(int u, int f) { dep[u] = dep[f] + 1; fa[u] = f; siz[u] = 1; son[u] = 0; int m = -1; for (auto& v: edge[u]) { if (v == f) continue; dfs(v, u); siz[u] += siz[v]; if (siz[v] > m) son[u] = v, m = siz[v]; } } void dfs(int u, int f, int tp) { top[u] = tp; if (!son[u]) return; dfs(son[u], u, tp); for (auto& v: edge[u]) { if (v == f || v == son[u]) continue; dfs(v, u, v); } } void build() { dfs(1, 0); dfs(1, 0, 1); } int qlca(int u, int v) { while (top[u] != top[v]){ if (dep[top[u]] < dep[top[v]]) swap(u, v); u = fa[top[u]]; } return dep[u] < dep[v] ? u : v; } }
|