-
Notifications
You must be signed in to change notification settings - Fork 0
/
LCA (with Time Traversal DFS).cpp
68 lines (62 loc) · 1.03 KB
/
LCA (with Time Traversal DFS).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
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
int tim=0;
int parent[LG][N];
int tin[N], tout[N], level[N];
void dfs(int k, int par, int lvl)
{
tin[k]=++tim;
parent[0][k]=par;
level[k]=lvl;
for(auto it:g[k])
{
if(it==par)
continue;
dfs(it, k, lvl+1);
}
tout[k]=tim;
}
int walk(int u, int h)
{
for(int i=LG-1;i>=0;i--)
{
if((h>>i) & 1)
u = parent[i][u];
}
return u;
}
void precompute()
{
for(int i=1;i<LG;i++)
for(int j=1;j<=n;j++)
if(parent[i-1][j])
parent[i][j]=parent[i-1][parent[i-1][j]];
}
int LCA(int u, int v)
{
if(level[u]<level[v])
swap(u,v);
int diff=level[u]-level[v];
for(int i=LG-1;i>=0;i--)
{
if((1<<i) & diff)
{
u=parent[i][u];
}
}
if(u==v)
return u;
for(int i=LG-1;i>=0;i--)
{
if(parent[i][u] && parent[i][u]!=parent[i][v])
{
u=parent[i][u];
v=parent[i][v];
}
}
return parent[0][u];
}
int dist(int u, int v)
{
return level[u] + level[v] - 2 * level[LCA(u, v)];
}
//Problem 1 (Dynamic Diameter): https://codeforces.com/problemset/problem/379/F
//Solution 1: https://codeforces.com/contest/379/submission/45960185