-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ1068_2.java
More file actions
74 lines (59 loc) · 1.71 KB
/
BOJ1068_2.java
File metadata and controls
74 lines (59 loc) · 1.71 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
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 BOJ1068_2 {
static int n, target, root;
static List<Integer>[] graph;
static int[] leaf;
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
graph = new List[n];
for(int i = 0 ; i < n; i++){
graph[i] = new ArrayList<>();
}
leaf = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++){
int parentNum = Integer.parseInt(st.nextToken());
if(parentNum == -1){
root = i;
continue;
}
graph[parentNum].add(i);
}
target = Integer.parseInt(br.readLine());
}
public static void main(String[] args) throws IOException {
input();
process();
}
private static void process(){
if(target == root){
System.out.println(0);
return;
}
// disconnect target
for(int i = 0 ; i < n; i++){
if(graph[i].contains(target)){
graph[i].remove(graph[i].indexOf(target));
}
}
dfs(root);
// answer print
System.out.println(leaf[root]);
}
private static void dfs(int node){
if(graph[node].isEmpty()){
leaf[node] = 1;
return;
}
for(int i : graph[node]){
dfs(i);
leaf[node] += leaf[i];
}
}
}