|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.ArrayDeque; |
| 6 | +import java.util.Deque; |
| 7 | +import java.util.HashMap; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +public class Main{ |
| 11 | + |
| 12 | + private static class Node{ |
| 13 | + int value; |
| 14 | + Node c1; |
| 15 | + Node c2; |
| 16 | + public Node(int v){ |
| 17 | + this.value = v; |
| 18 | + c1 = c2 = null; |
| 19 | + } |
| 20 | + } |
| 21 | + private static Map<Integer, Node> Nodes; |
| 22 | + private static long answer = 0; |
| 23 | + private static Deque<Integer> q = new ArrayDeque<>(); |
| 24 | + public static void main(String[] args) throws IOException { |
| 25 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 26 | + int n = Integer.parseInt(br.readLine()); |
| 27 | + int t = n; |
| 28 | + Nodes = new HashMap<>(); |
| 29 | + Nodes.put(1, new Node(1)); |
| 30 | + while(t-->0){ |
| 31 | + String[] tokens = br.readLine().split(" "); |
| 32 | + int parentValue = Integer.parseInt(tokens[0 ]); |
| 33 | + Node parentNode = Nodes.get(parentValue); |
| 34 | + if(parentNode == null){ |
| 35 | + parentNode = new Node(parentValue); |
| 36 | + Nodes.put(parentValue, parentNode); |
| 37 | + } |
| 38 | + |
| 39 | + int child1Value = Integer.parseInt(tokens[1]); |
| 40 | + if(child1Value != -1){ |
| 41 | + Node child1Node = Nodes.get(child1Value); |
| 42 | + if(child1Node == null){ |
| 43 | + child1Node = new Node(child1Value); |
| 44 | + Nodes.put(child1Value, child1Node); |
| 45 | + } |
| 46 | + parentNode.c1 = child1Node; |
| 47 | + } |
| 48 | + int child2Value = Integer.parseInt(tokens[2 ]); |
| 49 | + if(child2Value != -1){ |
| 50 | + Node child2Node = Nodes.get(child2Value); |
| 51 | + if(child2Node == null){ |
| 52 | + child2Node = new Node(child2Value); |
| 53 | + Nodes.put(child2Value, child2Node); |
| 54 | + } |
| 55 | + parentNode.c2 = child2Node; |
| 56 | + } |
| 57 | + } |
| 58 | + findLastNode(Nodes.get(1)); |
| 59 | + answer--; |
| 60 | + dfs(Nodes.get(1)); |
| 61 | + br.close(); |
| 62 | + } |
| 63 | + |
| 64 | + private static void dfs(Node cur) { |
| 65 | + answer++; |
| 66 | + if(cur.c1 != null){ |
| 67 | + dfs(cur.c1); |
| 68 | + answer++; |
| 69 | + } |
| 70 | + if(q.getLast() == cur.value){ |
| 71 | + System.out.println(answer++); |
| 72 | + System.exit(0); |
| 73 | + } |
| 74 | + if(cur.c2 != null){ |
| 75 | + dfs(cur.c2); |
| 76 | + answer++; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + private static void findLastNode(Node cur) { |
| 81 | + if(cur.c1 != null){ |
| 82 | + findLastNode(cur.c1); |
| 83 | + } |
| 84 | + q.offerLast(cur.value); |
| 85 | + if(cur.c2 != null){ |
| 86 | + findLastNode(cur.c2); |
| 87 | + } |
| 88 | + } |
| 89 | +} |
| 90 | +``` |
0 commit comments