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
| void dfs(int u, int f) { fa[u][0] = f, dep[u] = dep[f] + 1, vis[u] = 1; for (int i = 1; ; i ++) { fa[u][i] = fa[fa[u][i - 1]][i - 1]; ma[u][i] = min(ma[fa[u][i - 1]][i - 1] , ma[u][i - 1]); if (fa[u][i] == 0) { k = max(k, i - 1); break; } } for (auto v : g[u]) { if (v.to != f) { ma[v.to][0] = v.w; dfs(v.to, u); } } } int lca(int u, int v){ if(dep[u] < dep[v]) swap(u, v); int x = u, y = v; int lu = INF, lv = INF; for (int i = k; i >= 0; i --){ if(dep[fa[u][i]] >= dep[v]) lu = min(ma[u][i], lu), u = fa[u][i]; } if(u == v) return min(lu, lv); for (int i = k; i >= 0; i --){ if(fa[u][i] != fa[v][i]) lu = min(ma[u][i], lu), u = fa[u][i], lv = min(ma[v][i], lv), v = fa[v][i]; } lu = min(ma[u][0], lu), lv = min(ma[v][0], lv); return min(lu, lv); }
|