Skip to content

Commit 38b83f4

Browse files
authored
[20260222] BOJ / G4 / 가장 가까운 공통 조상 / 이준희
1 parent d127d3e commit 38b83f4

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
public static void main(String[] args) throws IOException {
7+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
int T = Integer.parseInt(br.readLine());
9+
10+
while (T-- > 0) {
11+
int N = Integer.parseInt(br.readLine());
12+
int[] parent = new int[N + 1];
13+
boolean[] visited = new boolean[N + 1];
14+
15+
for (int i = 0; i < N - 1; i++) {
16+
StringTokenizer st = new StringTokenizer(br.readLine());
17+
int p = Integer.parseInt(st.nextToken());
18+
int c = Integer.parseInt(st.nextToken());
19+
parent[c] = p;
20+
}
21+
22+
StringTokenizer st = new StringTokenizer(br.readLine());
23+
int nodeA = Integer.parseInt(st.nextToken());
24+
int nodeB = Integer.parseInt(st.nextToken());
25+
26+
int current = nodeA;
27+
while (current != 0) {
28+
visited[current] = true;
29+
current = parent[current];
30+
}
31+
32+
current = nodeB;
33+
while (current != 0) {
34+
if (visited[current]) {
35+
System.out.println(current);
36+
break;
37+
}
38+
current = parent[current];
39+
}
40+
}
41+
}
42+
}
43+
```

0 commit comments

Comments
 (0)