-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLCA.cpp
More file actions
65 lines (54 loc) · 1.38 KB
/
LCA.cpp
File metadata and controls
65 lines (54 loc) · 1.38 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
61
62
63
64
65
class Lca {
int n, lg;
vector<int> depth;
vector<vector<int>> up;
void fill(int v, int p, const vector<vector<int>> &g) {
for (auto u: g[v]) {
if (u == p) continue;
depth[u] = depth[v] + 1;
up[u][0] = v;
for (int i = 1; i < lg; i++) {
up[u][i] = up[up[u][i - 1]][i - 1];
}
fill(u, v, g);
}
}
public:
Lca(const vector<vector<int>> &g, int root = 0): n(g.size()), lg(__lg(n) + 1),
depth(g.size()), up(n, vector<int>(lg)) {
fill(root, -1, g);
}
int getKth(int v, int k) {
for (int i = lg - 1; i >= 0; i--) {
if (k & (1 << i)) {
v = up[v][i];
}
}
return v;
}
int getLca(int v, int u) {
if (depth[v] > depth[u]) {
swap(v, u);
}
u = getKth(u, depth[u] - depth[v]);
if (u == v) {
return v;
}
for (int i = lg - 1; i >= 0; i--) {
if (up[v][i] != up[u][i]) {
v = up[v][i];
u = up[u][i];
}
}
return up[v][0];
}
int getDistance(int v, int u) {
return depth[v] + depth[u] - 2 * depth[getLca(v, u)];
}
int getDepth(int v) {
return depth[v];
}
int parent(int v) {
return up[v][0];
}
};