-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path622.go
More file actions
80 lines (71 loc) · 1.54 KB
/
622.go
File metadata and controls
80 lines (71 loc) · 1.54 KB
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
// UVa 622 - Grammar Evaluation
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func parse(token string) (bool, int64) {
if n, err := strconv.Atoi(token); err == nil {
return true, int64(n)
}
return false, -1
}
func isFactor(token string) (bool, int64) {
if strings.HasPrefix(token, "(") && strings.HasSuffix(token, ")") {
return isExpression(token[1 : len(token)-1])
}
return parse(token)
}
func indices(token string, sep byte) []int {
var indexes []int
for i := range token {
if token[i] == sep {
indexes = append(indexes, i)
}
}
return indexes
}
func isComponent(token string) (bool, int64) {
if indexes := indices(token, '*'); len(indexes) > 0 {
for _, index := range indexes {
if ok, v1 := isFactor(token[:index]); ok {
if ok, v2 := isComponent(token[index+1:]); ok {
return true, v1 * v2
}
}
}
return false, -1
}
return isFactor(token)
}
func isExpression(token string) (bool, int64) {
if indexes := indices(token, '+'); len(indexes) > 0 {
for _, index := range indexes {
if ok, v1 := isComponent(token[:index]); ok {
if ok, v2 := isExpression(token[index+1:]); ok {
return true, v1 + v2
}
}
}
return false, -1
}
return isComponent(token)
}
func main() {
in, _ := os.Open("622.in")
defer in.Close()
out, _ := os.Create("622.out")
defer out.Close()
var kase int
var line string
for fmt.Fscanf(in, "%d", &kase); kase > 0; kase-- {
fmt.Fscanf(in, "%s", &line)
if ok, v := isExpression(line); ok {
fmt.Fprintln(out, v)
} else {
fmt.Fprintln(out, "ERROR")
}
}
}