Skip to content

Commit e1836c0

Browse files
authored
Merge pull request #383 from AlgorithmWithGod/lkhyun
[20250624] BOJ / G5 / 트리와 쿼리 / 이강현
2 parents 812e273 + f8bb64b commit e1836c0

File tree

1 file changed

+55
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)