Skip to content

Commit 28afdee

Browse files
authored
[20260122] BOJ / G5 / 트리와 쿼리 / 한종욱
1 parent 38c1c60 commit 28afdee

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static List<Integer>[] graph;
9+
private static int[] nodes;
10+
private static boolean[] visited;
11+
private static int N, R, Q;
12+
13+
public static void main(String[] args) throws IOException {
14+
init();
15+
16+
countSubNodes(R);
17+
while (Q-->0) {
18+
int q = Integer.parseInt(br.readLine());
19+
bw.write(nodes[q] + "\n");
20+
}
21+
22+
bw.flush();
23+
bw.close();
24+
br.close();
25+
}
26+
27+
private static void init() throws IOException {
28+
StringTokenizer st = new StringTokenizer(br.readLine());
29+
N = Integer.parseInt(st.nextToken());
30+
R = Integer.parseInt(st.nextToken());
31+
Q = Integer.parseInt(st.nextToken());
32+
33+
graph = new List[N+1];
34+
nodes = new int[N+1];
35+
visited = new boolean[N+1];
36+
37+
for (int i = 1; i <= N; i++) {
38+
graph[i] = new ArrayList<>();
39+
}
40+
41+
Arrays.fill(nodes, 1);
42+
43+
for (int i = 0; i < N-1; i++) {
44+
st = new StringTokenizer(br.readLine());
45+
int U = Integer.parseInt(st.nextToken());
46+
int V = Integer.parseInt(st.nextToken());
47+
48+
graph[U].add(V);
49+
graph[V].add(U);
50+
}
51+
}
52+
53+
private static void countSubNodes(int start) {
54+
visited[start] = true;
55+
56+
for (int next : graph[start]) {
57+
if (visited[next]) continue;
58+
countSubNodes(next);
59+
nodes[start] += nodes[next];
60+
}
61+
}
62+
}
63+
```

0 commit comments

Comments
 (0)