forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path5.cpp
More file actions
57 lines (51 loc) ยท 1.38 KB
/
5.cpp
File metadata and controls
57 lines (51 loc) ยท 1.38 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
#include <bits/stdc++.h>
#define MAX 100001
using namespace std;
int n, m;
int parent[MAX]; // ๋ถ๋ชจ์ ๋ํ ์ ๋ณด
int d[MAX]; // ๊ฐ ๋
ธ๋๊น์ง์ ๊น์ด(depth)
int c[MAX]; // ๊ฐ ๋
ธ๋์ ๊น์ด๊ฐ ๊ณ์ฐ๋์๋์ง ์ฌ๋ถ
vector<int> graph[MAX]; // ๊ทธ๋ํ(graph) ์ ๋ณด
// ๋ฃจํธ ๋
ธ๋๋ถํฐ ์์ํ์ฌ ๊น์ด(depth)๋ฅผ ๊ตฌํ๋ ํจ์
void dfs(int x, int depth) {
c[x] = true;
d[x] = depth;
for (int i = 0; i < graph[x].size(); i++) {
int y = graph[x][i];
if (c[y]) continue; // ์ด๋ฏธ ๊น์ด๋ฅผ ๊ตฌํ๋ค๋ฉด ๋๊ธฐ๊ธฐ
parent[y] = x;
dfs(y, depth + 1);
}
}
// A์ B์ ์ต์ ๊ณตํต ์กฐ์์ ์ฐพ๋ ํจ์
int lca(int a, int b) {
// ๋จผ์ ๊น์ด(depth)๊ฐ ๋์ผํ๋๋ก
while (d[a] != d[b]) {
if (d[a] > d[b]) {
a = parent[a];
}
else b = parent[b];
}
// ๋
ธ๋๊ฐ ๊ฐ์์ง๋๋ก
while (a != b) {
a = parent[a];
b = parent[b];
}
return a;
}
int main() {
cin >> n;
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
dfs(1, 0); // ๋ฃจํธ ๋
ธ๋๋ 1๋ฒ ๋
ธ๋
cin >> m;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
cout << lca(a, b) << '\n';
}
}