-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11438.cpp
More file actions
66 lines (51 loc) · 1.18 KB
/
11438.cpp
File metadata and controls
66 lines (51 loc) · 1.18 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
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
#define MAXN 100050
int N,M,parent[MAXN][20], depth[MAXN];
vector <int> adj[MAXN];
void dfs(int n, int p, int d){
parent[n][0] = p;
depth[n] = d;
for(auto v: adj[n]){
if(v == p) continue;
dfs(v,n,d+1);
}
}
int lca(int a, int b){
if(depth[a] < depth[b]) swap(a,b);
for(int k=19 ; k>=0 ; k--){
if(depth[a] - depth[b] >= (1<<k)) a = parent[a][k];
}
if(a == b) return a;
for(int k=19 ; k>=0 ; k--){
if(parent[a][k] != parent[b][k]){
a = parent[a][k];
b = parent[b][k];
}
}
return parent[a][0];
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> N;
for(int i=0 ; i<N-1 ; i++){
int a,b; cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1,0,0);
for(int k=1 ; k<20 ; k++){
for(int i=1 ; i<=N ; i++){
parent[i][k] = parent[parent[i][k-1]][k-1];
}
}
cin >> M;
for(int i=0 ; i<M ; i++){
int a,b; cin >> a >> b;
cout << lca(a,b) << '\n';
}
}