|
| 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>[] edges; |
| 9 | + private static int[] parent; |
| 10 | + private static int N, M, answer; |
| 11 | + public static void main(String[] args) throws IOException { |
| 12 | + init(); |
| 13 | +
|
| 14 | + for (int i = 0; i < N; i++) { |
| 15 | + if (parent[i] == -1 && i != M) { |
| 16 | + DFS(i); |
| 17 | + } |
| 18 | + } |
| 19 | +
|
| 20 | + bw.write(answer + "\n"); |
| 21 | + bw.flush(); |
| 22 | + bw.close(); |
| 23 | + br.close(); |
| 24 | + } |
| 25 | +
|
| 26 | + private static void init() throws IOException { |
| 27 | + N = Integer.parseInt(br.readLine()); |
| 28 | +
|
| 29 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 30 | + parent = new int[N]; |
| 31 | + edges = new List[N]; |
| 32 | +
|
| 33 | + for (int i = 0; i < N; i++) { |
| 34 | + edges[i] = new ArrayList<>(); |
| 35 | + } |
| 36 | +
|
| 37 | + for (int i = 0; i < N; i++) { |
| 38 | + parent[i] = Integer.parseInt(st.nextToken()); |
| 39 | + if (parent[i] == -1) continue; |
| 40 | + edges[parent[i]].add(i); |
| 41 | + } |
| 42 | +
|
| 43 | + M = Integer.parseInt(br.readLine()); |
| 44 | + } |
| 45 | +
|
| 46 | + private static void DFS(int start) { |
| 47 | + if (isLeaf(start)) { |
| 48 | + answer++; |
| 49 | + return; |
| 50 | + } |
| 51 | +
|
| 52 | + for (int next : edges[start]) { |
| 53 | + if (next == M) continue; |
| 54 | + DFS(next); |
| 55 | + } |
| 56 | + } |
| 57 | +
|
| 58 | + private static boolean isLeaf(int node) { |
| 59 | + if (edges[node].isEmpty()) { |
| 60 | + return true; |
| 61 | + } |
| 62 | +
|
| 63 | + if (edges[node].size() == 1 && edges[node].get(0) == M) { |
| 64 | + return true; |
| 65 | + } |
| 66 | +
|
| 67 | + return false; |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments