-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlca.cpp
More file actions
42 lines (39 loc) · 933 Bytes
/
Copy pathlca.cpp
File metadata and controls
42 lines (39 loc) · 933 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
39
40
41
42
const int LIM =18;
vector<int> adj[ maxn + 5];
int depth[maxn + 5] ;
int par[maxn + 5][LIM+5 ];
// 1 based indexing
void build(int cur, int p)
{
int i;
depth[cur] = depth[p] + 1;
par[cur][0] = p;
for (i = 1; i <= LIM; i++)
par[cur][i] = par[par[cur][i - 1]][i - 1];
for(int i=0 ;i< adj[cur ].size() ;i++ ) {
int x = adj[cur][i] ;
if (x != p)
build(x, cur);
}
}
// return parent or distance
int lca(int a, int b){
int i, len = 0;
if (depth[a] > depth[b])
swap(a, b);
for (i = LIM; i >= 0; i--) {
if (depth[par[b][i]] >= depth[a]) {
b = par[b][i];
len += (1 << i);
}
}
if (a == b) return len;
for (i = LIM; i >= 0; i--) {
if (par[a][i] != par[b][i]) {
a = par[a][i];
b = par[b][i];
len += (1 << (i + 1));
}
}
return len + 2;
}