-
Notifications
You must be signed in to change notification settings - Fork 1
/
1068.java
67 lines (57 loc) · 1.79 KB
/
1068.java
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class Tree {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int root = 0;
int[] parents = new int[N];
boolean[][] map = new boolean[N][N];
String[] input = br.readLine().split(" ");
for(int i = 0; i < N; i++) {
parents[i] = Integer.parseInt(input[i]);
if(parents[i] != - 1) map[parents[i]][i] = true;
else root = i;
}
int deleteNode = Integer.parseInt(br.readLine());
br.close();
if(deleteNode == root) {
System.out.println(0);
return;
}
for(int i = 0; i < N; i++) {
map[i][deleteNode] = false;
}
delete(deleteNode, map);
int answer = bfs(root, map);
System.out.println(answer);
}
public static void delete(int node, boolean[][] map) {
for(int i = 0; i < map.length; i++) {
if(map[node][i]) {
map[node][i] = false;
delete(i, map);
}
}
}
public static int bfs(int root, boolean[][] map) {
int answer = 0;
Queue<Integer> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int cur = q.poll();
boolean hasChild = false;
for(int i = 0; i < map.length; i++) {
if(map[cur][i]) {
q.add(i);
hasChild = true;
}
}
if(!hasChild) answer++;
}
return answer;
}
}