blob: d02598fd0c7ea80d4abc9b11f586496f9b1ac90d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
struct lca {
int d[MN], L[MN][20];
void dfs(vector<int> * G, int u = 1, int p = 0) {
d[u] = d[p] + 1, L[u][0] = p;
for (int i = 0; i < 18 && L[u][i]; i++) L[u][i + 1] = L[L[u][i]][i];
for (auto& v : G[u]) if (v != p) dfs(G, v, u);
}
int lca(vector<int> * G, int u, int v) {
if (d[u] > d[v]) swap(u, v);
for (int i = 18; i >= 0; i--) if (d[v] - (1 << i) >= d[u]) v = L[v][i];
if (u == v) return u;
for (int i = 18; i >= 0; i--) if (L[u][i] && L[u][i] != L[v][i]) u = L[u][i], v = L[v][i];
return L[u][0];
}
}
|