-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA.cpp
More file actions
68 lines (61 loc) · 1.25 KB
/
LCA.cpp
File metadata and controls
68 lines (61 loc) · 1.25 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
66
67
68
class lca_t {
public:
int n;
int max_log, t;
vector<int> h, in, rin, out;
vector<vector<int>> adj, up;
lca_t (int _n) : n(_n) {
max_log = 0;
while ((1 << max_log) <= n)
max_log++;
h.resize(n);
in.resize(n);
rin.resize(n);
out.resize(n);
adj.resize(n);
up.resize(n, vector<int>(max_log));
t = 0;
}
int walk (int x, int k) {
for (int i = max_log - 1; i >= 0; i--) {
if (k & (1<<i)) x = up[x][i];
}
return x;
}
bool anc (int x, int y) {
return in[x] <= in[y] && out[x] >= out[y];
}
int lca(int x, int y) {
if (anc(x, y))
return x;
if (anc(y, x))
return y;
for (int i = max_log - 1; i >= 0; i--)
if (!anc(up[x][i], y))
x = up[x][i];
return up[x][0];
}
void add(int x, int y) {
adj[x].push_back(y);
adj[y].push_back(x);
}
void dfs (int v, int p) {
in[v] = t++;
rin[in[v]] = v;
up[v][0] = p;
for (int i = 1; i < max_log; i++)
up[v][i] = up[up[v][i - 1]][i - 1];
for (int i = 0; i < (int) adj[v].size(); i++) {
int u = adj[v][i];
if (u == p)
continue;
h[u] = h[v] + 1;
dfs(u, v);
}
out[v] = t;
};
void set_root (int x) {
h[x] = 0;
dfs(x, x);
}
};