Skip to content

Commit d6b235f

Browse files
authored
Update 5.cpp
1 parent 171b28e commit d6b235f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

21/5.cpp

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <bits/stdc++.h>
2+
#define MAX 100001
3+
4+
using namespace std;
5+
6+
int n, m;
7+
int parent[MAX]; // 부모에 대한 정보
8+
int d[MAX]; // 각 노드까지의 깊이(depth)
9+
int c[MAX]; // 각 노드의 깊이가 계산되었는지 여부
10+
vector<int> graph[MAX]; // 그래프(graph) 정보
11+
12+
// 루트 노드부터 시작하여 깊이(depth)를 구하는 함수
13+
void dfs(int x, int depth) {
14+
c[x] = true;
15+
d[x] = depth;
16+
for (int i = 0; i < graph[x].size(); i++) {
17+
int y = graph[x][i];
18+
if (c[y]) continue; // 이미 깊이를 구했다면 넘기기
19+
parent[y] = x;
20+
dfs(y, depth + 1);
21+
}
22+
}
23+
24+
// A와 B의 최소 공통 조상을 찾는 함수
25+
int lca(int a, int b) {
26+
// 먼저 깊이(depth)가 동일하도록
27+
while (d[a] != d[b]) {
28+
if (d[a] > d[b]) {
29+
a = parent[a];
30+
}
31+
else b = parent[b];
32+
}
33+
// 노드가 같아지도록
34+
while (a != b) {
35+
a = parent[a];
36+
b = parent[b];
37+
}
38+
return a;
39+
}
40+
41+
int main() {
42+
cin >> n;
43+
for (int i = 0; i < n - 1; i++) {
44+
int a, b;
45+
cin >> a >> b;
46+
graph[a].push_back(b);
47+
graph[b].push_back(a);
48+
}
49+
dfs(1, 0); // 루트 노드는 1번 노드
50+
51+
cin >> m;
52+
for (int i = 0; i < m; i++) {
53+
int a, b;
54+
cin >> a >> b;
55+
cout << lca(a, b) << '\n';
56+
}
57+
}

0 commit comments

Comments
 (0)