-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA.cpp
More file actions
70 lines (56 loc) · 1.04 KB
/
LCA.cpp
File metadata and controls
70 lines (56 loc) · 1.04 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
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<cmath>
#define MAX 50005
using namespace std;
int n, k, MD;
int table[MAX] = {-1}, dp[MAX][505];
vector<int>v[MAX];
void f(int x, int y){
table[x] = table[y] + 1;
dp[x][0] = y;
for(int i = 1; i <= MD; i++){
int tmp = dp[x][i-1];
dp[x][i] = dp[tmp][i-1];
}
for(int i = 0; i < v[x].size(); i++){
int next = v[x][i];
if(next != y){
f(next,x);
}
}
}
int main(){
MD = (int)floor(log2(MAX));
scanf("%d", &n);
for(int i = 0; i < n-1; i++){
int a, b;
scanf("%d %d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
f(1,0);
scanf("%d", &k);
while(k--){
int a, b;
scanf("%d %d", &a, &b);
if(table[a] != table[b]){
if(table[a] > table[b]) swap(a,b);
for(int i = MD; i >= 0; i--){
if(table[a] <= table[dp[b][i]]) b = dp[b][i];
}
}
int lca = a;
if(a != b){
for(int i = MD; i >= 0; i--){
if(dp[a][i] != dp[b][i]){
a = dp[a][i];
b = dp[b][i];
}
lca = dp[a][i];
}
}
printf("%d\n", lca);
}
}