-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathLowest Common Ancestor.cpp
More file actions
38 lines (34 loc) · 859 Bytes
/
Lowest Common Ancestor.cpp
File metadata and controls
38 lines (34 loc) · 859 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
/* Problem Link - https://www.codechef.com/problems/ENOC1
Solution Link - https://www.codechef.com/viewsolution/27790936
*/
const int MAX = (int)1e5+1, LG = ceil(log2(MAX));
vector<int> G[MAX];
vector<int> lvl(MAX), val;
vector<vector<int>> up(MAX, vector<int>(LG+1)), dp(MAX, vector<int>(LG+1));
void dfs(int u, int par, int h=0){
lvl[u] = h;
up[u][0] = par;
FR(i,1,LG+1){
up[u][i] = up[up[u][i-1]][i-1];
}
for(auto x:G[u]){
if(x != par) dfs(x, u, h+1);
}
}
int lca(int u, int v) {
if(lvl[u] < lvl[v])
swap(u, v);
for(int i = LG; i >= 0; --i) {
if(lvl[u] - (1<<i) >= lvl[v])
u = up[u][i];
}
if(u == v)
return u;
for(int i = LG; i >= 0; --i) {
if(up[u][i] != up[v][i]) {
u = up[u][i];
v = up[v][i];
}
}
return up[u][0];
}