-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11437.cpp
More file actions
89 lines (84 loc) · 1.89 KB
/
11437.cpp
File metadata and controls
89 lines (84 loc) · 1.89 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<bits/stdc++.h>
#define MAX 50001
#define MAX_D 17
using namespace std;
using pii = pair<int,int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vb =vector<bool>;
int d[MAX][MAX_D];
int depth[MAX];
int getHigher(int c , int df){
int cur = c;
int diff = df;
for(int i=MAX_D-1;i>=0;i--){
if((diff-(1<<i))>=0){
diff-=(1<<i);
cur = d[cur][i];
}
}
return cur;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n,m,x,y;
cin>>n;
vvi e(n+1);
for(int i=0;i<n-1;i++){
cin>>x>>y;
e[x].push_back(y);
e[y].push_back(x);
}
vb visit(n+1,false);
queue<pii> q;
q.push({1,1});
visit[1]=true;
depth[1]=1;
while(!q.empty()){
int cur = q.front().first;
int dep = q.front().second;
q.pop();
for(auto next : e[cur]){
if(!visit[next]){
visit[next]=true;
depth[next]=dep+1;
q.push({next,dep+1});
}else{
d[cur][0]=next;
}
}
}
for(int j=1;j<MAX_D;j++){
for(int i=1;i<=n;i++){
if(d[i][j-1]>0)
d[i][j] = d[d[i][j-1]][j-1];
}
}
cin>>m;
while(m--){
cin>>x>>y;
while(depth[x]!=depth[y]){
int diff = abs(depth[x]-depth[y]);
if(depth[x]<depth[y]){
y = getHigher(y,diff);
}else{
x = getHigher(x,diff);
}
}
while(x!=y){
for(int i=MAX_D-1;i>=0;i--){
if(d[x][i]>0&&d[y][i]>0&&d[x][i]!=d[y][i]){
x=d[x][i];
y=d[y][i];
break;
}
}
if(d[x][0]==d[y][0]){
x=d[x][0];
break;
}
}
cout<<x<<"\n";
}
}