-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinaryliftingKthAncestor.cpp
38 lines (38 loc) · 1.01 KB
/
binaryliftingKthAncestor.cpp
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
// Binary Lifting tutorial https://youtu.be/oib-XsjFa-M
class TreeAncestor {
vector<vector<int>> up; // int up[N][20];
vector<int> depth;
int LOG;
public:
TreeAncestor(int n, vector<int>& parent) {
LOG = 0;
while((1 << LOG) <= n) {
LOG++;
}
up = vector<vector<int>>(n, vector<int>(LOG));
depth = vector<int>(n);
// up[v][j] is 2^j -th ancestor of node v
parent[0] = 0;
for(int v = 0; v < n; v++) {
up[v][0] = parent[v];
if(v != 0) {
depth[v] = depth[parent[v]] + 1;
}
for(int j = 1; j < LOG; j++) {
up[v][j] = up[ up[v][j-1] ][j-1];
}
}
}
int getKthAncestor(int node, int k) {
if(depth[node] < k) {
return -1;
}
for(int j = LOG - 1; j >= 0; j--) {
if(k >= (1 << j)) {
node = up[node][j];
k -= 1 << j;
}
}
return node;
}
};