Skip to content

Commit 2bbeb64

Browse files
authored
[20250921] BOJ / G4 / 가장 가까운 공통 조상 / 이종환
1 parent 8bf2516 commit 2bbeb64

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
```java
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.*;
7+
8+
class Main {
9+
static BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
10+
static int nodeCnt, num1, num2,ans;
11+
static Node[] nodes;
12+
static HashSet<Node> set = new HashSet<>();
13+
14+
static class Node{
15+
int num;
16+
Node parent;
17+
HashSet<Node> children = new HashSet<>();
18+
19+
}
20+
21+
22+
public static void main(String[] args) throws NumberFormatException, IOException {
23+
int TC = Integer.parseInt(br.readLine());
24+
for (int tc = 1; tc <= TC; tc++) {
25+
init();
26+
process();
27+
print();
28+
29+
}
30+
31+
}
32+
33+
34+
public static void init() throws NumberFormatException, IOException {
35+
36+
nodeCnt = Integer.parseInt(br.readLine());
37+
nodes = new Node[nodeCnt+1];
38+
39+
for (int i = 1; i <= nodeCnt; i++) {
40+
nodes[i] = new Node();
41+
nodes[i].num = i;
42+
}
43+
44+
for (int i = 0; i < nodeCnt-1; i++) {
45+
StringTokenizer st = new StringTokenizer(br.readLine());
46+
int parentNum = Integer.parseInt(st.nextToken());
47+
int childNum = Integer.parseInt(st.nextToken());
48+
49+
nodes[parentNum].children.add(nodes[childNum]);
50+
nodes[childNum].parent = nodes[parentNum];
51+
}
52+
53+
StringTokenizer st = new StringTokenizer(br.readLine());
54+
num1 = Integer.parseInt(st.nextToken());
55+
num2 = Integer.parseInt(st.nextToken());
56+
57+
58+
59+
}
60+
61+
public static void process() {
62+
set.clear();
63+
64+
Node cur = nodes[num1];
65+
set.add(cur);
66+
while(cur.parent != null) {
67+
set.add(cur);
68+
cur = cur.parent;
69+
}
70+
71+
cur = nodes[num2];
72+
while(cur.parent != null) {
73+
if (set.contains(cur)) {
74+
ans = cur.num;
75+
return;
76+
}
77+
cur = cur.parent;
78+
}
79+
80+
ans = cur.num;
81+
82+
}
83+
84+
85+
86+
87+
public static void print() {
88+
System.out.println(ans);
89+
}
90+
}
91+
```

0 commit comments

Comments
 (0)