-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlca.cpp
More file actions
85 lines (79 loc) · 1.68 KB
/
Copy pathlca.cpp
File metadata and controls
85 lines (79 loc) · 1.68 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#define N 200200
#define LN 20
int table[N][LN];
vector<int> dis;
vector<int> par(N);
vector<int> po(LN);
vector<int> bfs(int x)
{
vector<int> d(n+1, -1);
queue<int> qu;
qu.push(x);
d[x] = 0;
while(!qu.empty()){
int u = qu.front();
qu.pop();
for(int i=0; i<adj[u].size(); i++){
int v = adj[u][i];
if(d[v] == -1){
d[v] = d[u]+1;
qu.push(v);
par[v] = u;
}
}
}
return d;
}
void sptb()
{
par[1] = -1;
dis = bfs(1);
po[0] = 1;
for(int i=1; i<LN; i++){
po[i] = po[i-1]<<1;
}
for(int i=1; i<=n; i++){
table[i][0] = par[i];
}
for(int i=1; i<LN; i++){
for(int j=1; j<=n; j++){
if(dis[j] >= po[i]){
table[j][i] = table[table[j][i-1]][i-1];
}
else{
table[j][i] = -1;
}
}
}
}
int lca(int u, int v)
{
if(dis[u] < dis[v]){
int x = dis[v]-dis[u];
for(int i=LN-1; i>=0; i--){
if(po[i]<=x){
v = table[v][i];
x -= po[i];
}
}
}
else if(dis[u] > dis[v]){
int x = dis[u] - dis[v];
for(int i=LN-1; i>=0; i--){
if(po[i]<=x){
u = table[u][i];
x -= po[i];
}
}
}
if(u == v){
return u;
}
for(int i=LN-1; i>=0; i--){
if(dis[u] >= po[i] && table[u][i] != table[v][i]){
u = table[u][i];
v = table[v][i];
}
}
return par[u];
}