-
Notifications
You must be signed in to change notification settings - Fork 0
/
最近公共祖先
61 lines (55 loc) · 1.24 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
#include <bits/stdc++.h>
#define N 500005
#define M 1000010
using namespace std;
int n,m,s,x,y,tot;
int head[N],edge[M],nxt[M];
int depth[N],fa[N][22],lg[N];
void add(int x,int y) {
edge[++tot] = y;
nxt[tot] = head[x];
head[x] = tot;
}
void dfs(int x,int y) {
depth[x] = depth[y] + 1;
fa[x][0] = y;
for(int i = 1; (1 << i) <= depth[x]; i++)
fa[x][i] = fa[ fa[x][i-1] ][i-1];
for(int i = head[x]; i != 0; i = nxt[i]) {
if(edge[i] != y) {
dfs(edge[i],x);
}
}
}
int lca(int x,int y) {
if(depth[x] < depth[y]) {
swap(x,y);
}
for(int i = 1; i <= n; i++) {
lg[i] = lg[i-1] + (1 << lg[i-1] == i);
}
while(depth[x] > depth[y]) {
x = fa[x][ lg[depth[x]-depth[y]]-1 ];
}
if(x == y) return x;
for(int k = lg[ depth[x] ]-1; k >= 0; k--) {
if(fa[x][k] != fa[y][k]) {
x = fa[x][k];
y = fa[y][k];
}
}
return fa[x][0];
}
int main() {
int n,m,s; scanf("%d%d%d",&n,&m,&s);
for(int i = 1; i < n; i++) {
scanf("%d%d",&x,&y);
add(x,y); add(y,x);
}
dfs(s,0);
for(int i = 1; i <= m; i++) {
scanf("%d%d",&x,&y);
printf("%d\n",lca(x,y));
}
return 0;
}