-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlca.cpp
More file actions
62 lines (49 loc) · 1.16 KB
/
lca.cpp
File metadata and controls
62 lines (49 loc) · 1.16 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
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
// LCA (Lowest Common Ancestor) - Sparse Table (Binary Lifting)
const int MAX = 100005;
const int LOG = 20; // 2^20 > 100000
vector<int> adj[MAX];
int parent[MAX][LOG];
int depth[MAX];
void dfs(int cur, int p, int d) {
depth[cur] = d;
parent[cur][0] = p;
for (int next : adj[cur]) {
if (next != p) {
dfs(next, cur, d + 1);
}
}
}
void build_lca(int n, int root) {
dfs(root, 0, 0); // root의 부모는 0
for (int j = 1; j < LOG; j++) {
for (int i = 1; i <= n; i++) {
if (parent[i][j - 1] != 0)
parent[i][j] = parent[parent[i][j - 1]][j - 1];
}
}
}
int lca(int u, int v) {
if (depth[u] < depth[v])
swap(u, v);
// 깊이 맞추기
for (int j = LOG - 1; j >= 0; j--) {
if (depth[u] - (1 << j) >= depth[v]) {
u = parent[u][j];
}
}
if (u == v)
return u;
// 공통 조상 찾기
for (int j = LOG - 1; j >= 0; j--) {
if (parent[u][j] != parent[v][j]) {
u = parent[u][j];
v = parent[v][j];
}
}
return parent[u][0];
}
int dist(int u, int v) { return depth[u] + depth[v] - 2 * depth[lca(u, v)]; }