模板 - 图论 - 最近公共祖先 - 倍增算法 - LCA
const int MAX = 100000; vector <int> G[MAXN + 5]; int dep[MAXN + 5], fa[MAXN + 5][20 + 1]; void dfs(int u, int p) { dep[u] = depth[p] + 1; fa[u][0] = p; for (int i = 1; i <= 20; i++) fa[u][i] = fa[fa[u][i - 1]][i - 1]; for(auto &v : G[u]) { if(v == p) continue; dfs(v, u); } } int LCA(int x, int y) { if (dep[x] < dep[y]) swap(x, y); for (int i = 20; i >= 0; i--) if (dep[x] - (1 << i) >= dep[y]) x = fa[x][i]; if (x == y) return x; for (int i = 20; i >= 0; i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i]; return fa[x][0]; }
相关推荐
earthhouge 2020-07-19
Happyunlimited 2019-11-01
ResysChina 2018-04-22
ResysChina 2018-04-14
MATLAB 2018-04-12
锦妖和她的小伙伴们 2018-02-21