/
dwite201210p4.java
88 lines (64 loc) · 1.77 KB
/
dwite201210p4.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* DWITE programming contest solutions
* October 2012 - Problem 4: "Trick or Tree'ing"
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/dwite-programming-contest-solutions
* https://github.com/nayuki/DWITE-programming-contest-solutions
*/
public final class dwite201210p4 extends DwiteSolution {
public static void main(String[] args) {
new dwite201210p4().run("DATA4.txt", "OUT4.txt");
}
private String line;
private int candy;
protected void runOnce() {
candy = 0;
line = io.readLine();
index = 0;
Node tree = parseTree();
io.println(minimumWalk(tree) + " " + candy);
}
private int index;
private Node parseTree() {
if (index >= line.length())
throw new IllegalArgumentException();
while (line.charAt(index) == ' ')
index++;
if (line.charAt(index) == '(') {
index++;
Node left = parseTree();
Node right = parseTree();
if (line.charAt(index) != ')')
throw new IllegalArgumentException();
index++;
return new Node(left, right);
} else {
int start = index;
while (index < line.length() && Character.isDigit(line.charAt(index)))
index++;
candy += Integer.parseInt(line.substring(start, index));
return null; // Leaf
}
}
private int minimumWalk(Node node) {
if (node == null)
return 0;
else
return Math.min(fullWalk(node.left) + minimumWalk(node.right), minimumWalk(node.left)+ fullWalk(node.right)) + 3;
}
private int fullWalk(Node node) {
if (node == null)
return 0;
else
return fullWalk(node.left) + fullWalk(node.right) + 4;
}
private static final class Node {
public final Node left;
public final Node right;
public Node(Node left, Node right) {
this.left = left;
this.right = right;
}
}
}