|
7 | 7 |
|
8 | 8 | public class BOJ_1068 { |
9 | 9 |
|
10 | | - private static int N; // 노드의 갯수 |
| 10 | + private static int N; |
11 | 11 | private static Node[] nodes; |
12 | 12 |
|
13 | 13 | public static void main(String[] args) throws IOException { |
14 | | - N = readInt(); |
15 | | - |
16 | | - nodes = new Node[N]; |
| 14 | + initNodes(); |
| 15 | + setParents(); |
| 16 | + detachNode(); |
| 17 | + int numberOfLeafNodes = numberOfLeafNodes(); |
| 18 | + System.out.print(numberOfLeafNodes); |
| 19 | + } |
17 | 20 |
|
18 | | - for (int i = 0; i < N; i++) { |
19 | | - nodes[i] = new Node(i); |
20 | | - } |
| 21 | + private static int numberOfLeafNodes() { |
| 22 | + int count = 0; |
21 | 23 |
|
22 | | - for (int i = 0; i < N; i++) { |
23 | | - int parentNodeNumber = readInt(); |
24 | | - if (isNotRootNode(parentNodeNumber)) { |
25 | | - nodes[parentNodeNumber].addChild(nodes[i]); |
| 24 | + for (Node node : nodes) { |
| 25 | + if (node.isLeafNode()) { |
| 26 | + count++; |
26 | 27 | } |
27 | 28 | } |
| 29 | + return count; |
| 30 | + } |
28 | 31 |
|
| 32 | + private static void detachNode() throws IOException { |
29 | 33 | int deleteNodeNumber = readInt(); |
30 | 34 | nodes[deleteNodeNumber].detach(); |
| 35 | + } |
31 | 36 |
|
32 | | - int count = 0; |
33 | | - |
34 | | - for (Node node : nodes) { |
35 | | - if (node.isLeafNode()) { |
36 | | - count++; |
| 37 | + private static void setParents() throws IOException { |
| 38 | + for (int i = 0; i < N; i++) { |
| 39 | + int parentNodeNumber = readInt(); |
| 40 | + if (parentNodeNumber >= 0) { |
| 41 | + nodes[i].changeParent(nodes[parentNodeNumber]); |
37 | 42 | } |
38 | 43 | } |
39 | | - |
40 | | - System.out.print(count); |
41 | 44 | } |
42 | 45 |
|
43 | | - private static boolean isNotRootNode(int parentNodeNumber) { |
44 | | - return parentNodeNumber != -1; |
| 46 | + private static void initNodes() throws IOException { |
| 47 | + N = readInt(); |
| 48 | + nodes = new Node[N]; |
| 49 | + for (int i = 0; i < N; i++) { |
| 50 | + nodes[i] = new Node(i); |
| 51 | + } |
45 | 52 | } |
46 | 53 |
|
47 | 54 | private static int readInt() throws IOException { |
@@ -77,9 +84,9 @@ public int getValue() { |
77 | 84 | return value; |
78 | 85 | } |
79 | 86 |
|
80 | | - public void addChild(Node child) { // 양방향 참조 |
81 | | - childs.add(child); |
82 | | - child.parent = this; |
| 87 | + public void changeParent(Node parent) { // 양방향 참조 |
| 88 | + this.parent = parent; |
| 89 | + parent.childs.add(this); |
83 | 90 | } |
84 | 91 |
|
85 | 92 | public Node getRootNode() { |
|
0 commit comments