Skip to content

Commit 6c422f3

Browse files
authored
Merge pull request #1997 from AlgorithmWithGod/Ukj0ng
[20260306] BOJ / G3 / LCA / 한종욱
2 parents 7233006 + ba5128a commit 6c422f3

1 file changed

Lines changed: 95 additions & 0 deletions

File tree

Ukj0ng/202603/06 BOJ G3 LCA.md

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
```
2+
import java.io.*;
3+
4+
import java.util.ArrayDeque;
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
import java.util.Queue;
8+
import java.util.StringTokenizer;
9+
10+
public class Main {
11+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
12+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
13+
private static List<Integer>[] graph;
14+
private static int[][] depth;
15+
private static boolean[] visited;
16+
private static int N, M;
17+
18+
public static void main(String[] args) throws IOException {
19+
init();
20+
bw.flush();
21+
bw.close();
22+
br.close();
23+
}
24+
25+
private static void init() throws IOException {
26+
N = Integer.parseInt(br.readLine());
27+
28+
graph = new List[N+1];
29+
depth = new int[N+1][2];
30+
visited = new boolean[N+1];
31+
32+
for (int i = 1; i <= N; i++) {
33+
graph[i] = new ArrayList<>();
34+
}
35+
36+
for (int i = 0; i < N-1; i++) {
37+
StringTokenizer st = new StringTokenizer(br.readLine());
38+
int node1 = Integer.parseInt(st.nextToken());
39+
int node2 = Integer.parseInt(st.nextToken());
40+
41+
graph[node1].add(node2);
42+
graph[node2].add(node1);
43+
}
44+
45+
BFS();
46+
47+
M = Integer.parseInt(br.readLine());
48+
for (int i = 0; i < M; i++) {
49+
StringTokenizer st = new StringTokenizer(br.readLine());
50+
int node1 = Integer.parseInt(st.nextToken());
51+
int node2 = Integer.parseInt(st.nextToken());
52+
53+
int depth1 = depth[node1][0];
54+
int depth2 = depth[node2][0];
55+
56+
while (depth1 != depth2) {
57+
if (depth1 > depth2) {
58+
node1 = depth[node1][1];
59+
depth1 = depth[node1][0];
60+
} else {
61+
node2 = depth[node2][1];
62+
depth2 = depth[node2][0];
63+
}
64+
}
65+
66+
while (node1 != node2) {
67+
node1 = depth[node1][1];
68+
node2 = depth[node2][1];
69+
}
70+
71+
bw.write(node1 + "\n");
72+
}
73+
}
74+
75+
private static void BFS() {
76+
Queue<int[]> q = new ArrayDeque<>();
77+
depth[1][0] = 1;
78+
depth[1][1] = -1;
79+
visited[1] = true;
80+
q.add(new int[] {1, 1});
81+
82+
while (!q.isEmpty()) {
83+
int[] current = q.poll();
84+
85+
for (int next : graph[current[0]]) {
86+
if (visited[next]) continue;
87+
depth[next][0] = current[1]+1;
88+
depth[next][1] = current[0];
89+
visited[next] = true;
90+
q.add(new int[]{next, current[1]+1});
91+
}
92+
}
93+
}
94+
}
95+
```

0 commit comments

Comments
 (0)