1+ import java .io .BufferedReader ;
2+ import java .io .IOException ;
3+ import java .io .InputStreamReader ;
4+ import java .util .*;
5+
6+ public class BOJ_1068 {
7+
8+ private static final int ROOT_INDEX = -1 ;
9+
10+ private static int removeTargetIndex ;
11+ private static final List <Node > nodes = new ArrayList <>();
12+ private static List <Node > rootNodes = new ArrayList <>();
13+
14+ public static void main (String [] args ) throws IOException {
15+ readInput ();
16+ solve ();
17+ }
18+
19+ private static void solve () {
20+ nodes .get (removeTargetIndex ).disable ();
21+
22+ int leafCount = findLeafCountDfs ();
23+
24+ System .out .println (leafCount );
25+ }
26+
27+ private static int findLeafCountDfs () {
28+ int leafCount = 0 ;
29+
30+ Stack <Node > nodeStack = new Stack <>();
31+
32+ for (Node rootNode : rootNodes ) {
33+ if (rootNode .isActive ()) {
34+ nodeStack .add (rootNode );
35+ }
36+ }
37+
38+ while (!nodeStack .isEmpty ()) {
39+ Node node = nodeStack .pop ();
40+
41+ if (node .isActive () && !node .hasChild ()) {
42+ leafCount ++;
43+ continue ;
44+ }
45+
46+ for (Node child : node ) {
47+ if (child .isActive ()) {
48+ nodeStack .add (child );
49+ }
50+ }
51+ }
52+
53+ return leafCount ;
54+ }
55+
56+ private static void readInput () throws IOException {
57+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
58+ int nodeCount = Integer .parseInt (br .readLine ());
59+
60+ for (int i = 0 ; i < nodeCount ; i ++) {
61+ nodes .add (new Node (i ));
62+ }
63+
64+ StringTokenizer st = new StringTokenizer (br .readLine ());
65+ for (int i = 0 ; i < nodeCount ; i ++) {
66+ Node currentNode = nodes .get (i );
67+
68+ int parentIndex = Integer .parseInt (st .nextToken ());
69+ if (parentIndex == ROOT_INDEX ) {
70+ rootNodes .add (currentNode );
71+ continue ;
72+ }
73+
74+ nodes .get (parentIndex ).addChildNode (currentNode );
75+ }
76+
77+ removeTargetIndex = Integer .parseInt (br .readLine ());
78+ }
79+ }
80+
81+ class Node implements Iterable <Node > {
82+ private final Set <Node > childs ;
83+ private final int index ;
84+ private boolean isActive = true ;
85+
86+ public Node (int index ) {
87+ childs = new HashSet <>();
88+ this .index = index ;
89+ }
90+
91+ public int getIndex () {
92+ return index ;
93+ }
94+
95+ public boolean isActive () {
96+ return isActive ;
97+ }
98+
99+ public void addChildNode (Node node ) {
100+ childs .add (node );
101+ }
102+
103+ public boolean hasChild () {
104+ if (childs .isEmpty ()) {
105+ return false ;
106+ }
107+
108+ for (Node child : childs ) {
109+ if (child .isActive ()) {
110+ return true ;
111+ }
112+ }
113+
114+ return false ;
115+ }
116+
117+ public void disable () {
118+ this .isActive = false ;
119+ childs .clear ();
120+ }
121+
122+ @ Override
123+ public Iterator <Node > iterator () {
124+ return childs .iterator ();
125+ }
126+ }
127+
128+ // 삽질1 : 2번째 줄에서 노드가 순서대로 나올 것이라고 생각했음
0 commit comments