-
Notifications
You must be signed in to change notification settings - Fork 27
/
397.go
107 lines (97 loc) · 1.92 KB
/
397.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// UVa 397 - Equation Elation
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
var out io.WriteCloser
func parse(line string) []string {
var stack []string
var num int
var ch byte
var variable string
r := strings.NewReader(line)
for {
fmt.Fscanf(r, "%d", &num)
stack = append(stack, strconv.Itoa(num))
for {
if fmt.Fscanf(r, "%c", &ch); ch != ' ' {
break
}
}
stack = append(stack, string(ch))
if ch == '=' {
break
}
}
fmt.Fscanf(r, "%s", &variable)
stack = append(stack, variable)
return stack
}
func operations(stack []string) (int, int) {
var md, as int
for _, element := range stack {
switch element {
case "*", "/":
md++
case "+", "-":
as++
}
}
return md, as
}
func pass(times int, ops [2]string, stack []string) []string {
var num1, num2 int
for idx := 0; times > 0; idx++ {
fmt.Sscanf(stack[idx], "%d", &num1)
if idx++; stack[idx] == ops[0] || stack[idx] == ops[1] {
fmt.Sscanf(stack[idx+1], "%d", &num2)
switch stack[idx] {
case "*":
stack[idx-1] = strconv.Itoa(num1 * num2)
case "/":
stack[idx-1] = strconv.Itoa(num1 / num2)
case "+":
stack[idx-1] = strconv.Itoa(num1 + num2)
case "-":
stack[idx-1] = strconv.Itoa(num1 - num2)
}
stack = append(stack[:idx], stack[idx+2:]...)
fmt.Fprintf(out, "%s\n", strings.Join(stack, " "))
idx -= 2
times--
}
}
return stack
}
func solve(line string) {
stack := parse(line)
fmt.Fprintf(out, "%s\n", strings.Join(stack, " "))
md, as := operations(stack)
pass(as, [2]string{"+", "-"}, pass(md, [2]string{"*", "/"}, stack))
}
func main() {
in, _ := os.Open("397.in")
defer in.Close()
out, _ = os.Create("397.out")
defer out.Close()
s := bufio.NewScanner(in)
s.Split(bufio.ScanLines)
var line string
first := true
for s.Scan() {
if line = s.Text(); line == "" {
break
}
if first {
first = false
} else {
fmt.Fprintln(out)
}
solve(line)
}
}