forked from jokj624/PSTeamNote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCA(최소공통조상찾기).cpp
55 lines (55 loc) · 878 Bytes
/
LCA(최소공통조상찾기).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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define NODE 50002
vector<int> tree[NODE];
int depth[NODE];
int parent[NODE];
bool check[NODE];
int lca(int a, int b){
if(depth[a]<depth[b]){
swap(a,b);
}
while(depth[a]!=depth[b]){
a= parent[a];
}
while(a!=b){
a=parent[a];
b=parent[b];
}
return a;
}
int main(){
int n, m;
cin >> n;
for(int i=0; i<n-1; i++){
int a, b;
scanf("%d %d", &a, &b);
tree[a].push_back(b);
tree[b].push_back(a);
}
queue<int> q;
check[1] = true;
q.push(1);
while(!q.empty()){
int x = q.front();
q.pop();
for(int i=0; i<tree[x].size(); i++){
int y =tree[x][i];
if(!check[y]){
parent[y] = x;
depth[y] = depth[x]+1;
q.push(y);
check[y] = true;
}
}
}
cin >> m;
for(int i=0; i<m; i++){
int a, b;
scanf("%d %d", &a,&b);
printf("%d\n",lca(a,b));
}
return 0;
}