-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ15681.java
More file actions
89 lines (72 loc) · 2.45 KB
/
BOJ15681.java
File metadata and controls
89 lines (72 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class BOJ15681 {
/**
* 1. set input
* 2. vertex 별로 가지는 본인 포함 자식 vertex 개수 저장
* 3. query Array를 loop 돌며 print
*/
static int n, root, queryCnt;
static int[] childCntArray, queryArray;
static boolean[] visited;
static List<Integer>[] tree;
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
//
n = Integer.parseInt(st.nextToken());
root = Integer.parseInt(st.nextToken());
queryCnt = Integer.parseInt(st.nextToken());
//
childCntArray = new int[n + 1];
visited = new boolean[n + 1];
queryArray = new int[queryCnt];
// set childCntArray
for(int i = 0 ; i < n+1; i++){
childCntArray[i] = 1;
}
// set tree
tree = new List[n + 1];
for (int i = 1; i <= n; i++)
tree[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
st = new StringTokenizer(br.readLine());
int vertex1 = Integer.parseInt(st.nextToken());
int vertex2 = Integer.parseInt(st.nextToken());
// bidirectional
tree[vertex1].add(vertex2);
tree[vertex2].add(vertex1);
}
// set query array
for (int i = 0; i < queryCnt; i++) {
queryArray[i] = Integer.parseInt(br.readLine());
}
}
public static void main(String[] args) throws IOException {
input();
process();
}
private static void process() {
setChildCntArray(root);
// print answer
for (int i : queryArray)
System.out.println(childCntArray[i]);
}
private static void setChildCntArray(int vertex) {
visited[vertex] = true;
boolean isLeaf = true;
for (int i : tree[vertex]) {
if (!visited[i]) {
// 방문할 노드가 있는 경우 leaf 아님
isLeaf = false;
setChildCntArray(i);
childCntArray[vertex] += childCntArray[i];
}
}
if (isLeaf) childCntArray[vertex] = 1;
}
}