-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path112.go
91 lines (81 loc) · 1.45 KB
/
112.go
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
89
90
91
// UVa 112 - Tree Summing
package main
import (
"fmt"
"os"
)
type node struct {
n int
l, r *node
}
func buildTree(line string) node {
if len(line) == 0 {
return node{}
}
var l, r, count, value int
for idx, v := range line {
if l == 0 && v == '(' {
l = idx
}
switch v {
case '(':
count++
case ')':
count--
}
if r == 0 && l != 0 && count == 0 {
r = idx
}
}
left := buildTree(line[l+1 : r])
right := buildTree(line[r+2 : len(line)-1])
fmt.Sscanf(line[:l], "%d", &value)
tree := node{value, &left, &right}
return tree
}
func dfs(sum int, node *node, ssf int) bool {
if node == nil {
return false
}
if ssf+node.n > sum {
return false
}
if ssf+node.n == sum && node.l == nil && node.r == nil {
return true
}
return dfs(sum, node.l, ssf+node.n) || dfs(sum, node.r, ssf+node.n)
}
func main() {
in, _ := os.Open("112.in")
defer in.Close()
out, _ := os.Create("112.out")
defer out.Close()
var sum, count int
var c byte
for {
if _, err := fmt.Fscanf(in, "%d (", &sum); err != nil {
break
}
count++
chars := []byte{'('}
for count > 0 {
fmt.Fscanf(in, "%c", &c)
if c >= '0' && c <= '9' || c == '(' || c == ')' {
chars = append(chars, c)
switch c {
case '(':
count++
case ')':
count--
}
}
}
fmt.Fscanln(in)
tree := buildTree(string(chars[1 : len(chars)-1]))
if dfs(sum, &tree, 0) {
fmt.Fprintln(out, "yes")
} else {
fmt.Fprintln(out, "no")
}
}
}