-
Notifications
You must be signed in to change notification settings - Fork 0
/
11438.cpp
66 lines (55 loc) · 1.28 KB
/
11438.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
#include<iostream>
#include<algorithm>
#include<vector>
#define N 100005
using namespace std;
int n, m, parent[N][30], depth[N];
vector<int> tree[N];
void dfs(int index)
{
int i=0;
while(parent[parent[index][i]][i]){
parent[index][i+1] = parent[parent[index][i]][i];
i++;
}
for(int next: tree[index]){
if(!depth[next]){
parent[next][0]=index;
depth[next]=depth[index]+1;
dfs(next);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int i, j, a, b;
cin >> n;
parent[1][0]=0;
depth[1]=1;
for(i=1; i<n; i++){
cin >> a >> b;
tree[a].push_back(b);
tree[b].push_back(a);
}
dfs(1);
cin >> m;
for(i=0; i<m; i++){
cin >> a >> b;
if(depth[a]<depth[b]) swap(a, b);
for(j=20; j>=0; j--){
if(depth[a]==depth[b]) break;
if(depth[parent[a][j]]>=depth[b]) a = parent[a][j];
}
for(j=20; j>=0; j--){
if(a==b) break;
if(parent[a][j]!=parent[b][j]) a=parent[a][j], b=parent[b][j];
}
if(a!=b) a=parent[a][0];
printf("%d\n", a);
}
return 0;
}