-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA.cpp
More file actions
60 lines (54 loc) · 1.4 KB
/
Copy pathLCA.cpp
File metadata and controls
60 lines (54 loc) · 1.4 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
struct LCA {
int n, rt, lg;
std::vector<std::vector<int>> g;
std::vector<std::vector<int>> anc;
std::vector<int> dep;
LCA(int n) : n(n), g(n), anc(n, std::vector<int>(std::__lg(n) + 1, -1)), dep(n), lg(std::__lg(n) + 1) {}
void add(int x, int y) {
g[x].push_back(y);
g[y].push_back(x);
}
void dfs(int u, int fa) {
anc[u][0] = fa;
for (auto v : g[u]) {
if (v != fa) {
dep[v] = dep[u] + 1;
dfs(v, u);
}
}
}
void build(int rt) {
this->rt = rt;
dfs(rt, -1);
for (int i = 1; i < lg; i++) {
for (int j = 0; j < n; j++) {
if (anc[j][i - 1] != -1) {
anc[j][i] = anc[anc[j][i - 1]][i - 1];
}
}
}
}
int kth(int x, int k) {
for (; k; k &= k - 1) {
x = anc[x][__builtin_ctz(k)];
if (x == -1)
return -1;
}
return x;
}
int lca(int x, int y) {
if (dep[x] > dep[y])
std::swap(x, y);
y = kth(y, dep[y] - dep[x]);
if (y == x)
return x;
for (int i = anc[x].size() - 1; i >= 0; i--) {
int px = anc[x][i], py = anc[y][i];
if (px != py) {
x = px;
y = py;
}
}
return anc[x][0];
}
};