-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11437.cpp
More file actions
64 lines (52 loc) · 1.19 KB
/
11437.cpp
File metadata and controls
64 lines (52 loc) · 1.19 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
#include<iostream>
#include<vector>
#include<algorithm>
#define N 50005
using namespace std;
vector<int> tree[N];
int parent[N][30], level[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(auto iter : tree[index])
{
if(level[iter]) continue;
parent[iter][0]=index;
level[iter]=level[index]+1;
dfs(iter);
}
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int n, i, j, a, b, m;
cin >> n;
for(i=1; i<n; i++){
cin >> a >> b;
tree[a].push_back(b);
tree[b].push_back(a);
}
level[1]=1;
dfs(1);
cin >> m;
for(i=1; i<=m; i++){
cin >> a >> b;
if(level[a]<level[b]) swap(a, b);
for(j=20; j>=0; j--){
if(level[a]==level[b]) break;
if(level[parent[a][j]]>=level[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;
}