-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlca.cpp
More file actions
43 lines (40 loc) · 760 Bytes
/
lca.cpp
File metadata and controls
43 lines (40 loc) · 760 Bytes
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
int parent[MAX_N][20];
// 2^0, 2^1, ..., 2^19
// O(log(N))
void dfs(int a) {
for(int b : edges[a]) {
if(b == parent[a][0]) {
continue;
}
parent[b][0] = a;
for(int k = 1; k <= 19; ++k) {
parent[b][k] = parent[ parent[b][k-1] ][k-1];
}
depth[b] = depth[a] + 1;
dfs(b);
}
}
int lca(int a, int b) {
if(depth[a] < depth[b]) {
swap(a, b);
}
// difference = 1
// ..., 64, 32, 16, 8, 4, 2, 1
for(int k = 19; k >= 0; k--) {
if(depth[a] - depth[b] >= (1 << k)) {
a = parent[a][k];
}
}
if(a == b) {
return a;
}
// depth[a] == depth[b]
for(int k = 19; k >= 0; k--) {
if(parent[a][k] != parent[b][k]) {
a = parent[a][k];
b = parent[b][k];
}
}
// a and b are both children of the same LCA
return parent[a][0];
}