-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path120.go
71 lines (62 loc) · 1.4 KB
/
120.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
// UVa 120 - Stacks of Flapjacks
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
func find(pancake string, pancakes []string) int {
for i, v := range pancakes {
if pancake == v {
return i
}
}
return -1
}
func flip(pos int, pancakes []string) {
for i := 0; i <= pos/2; i++ {
pancakes[i], pancakes[pos-i] = pancakes[pos-i], pancakes[i]
}
}
func process(idx int, sorted, pancakes []string) []string {
var steps []string
switch {
case sorted[idx] == pancakes[idx]:
case pancakes[0] == sorted[idx]:
steps = append(steps, strconv.Itoa(len(pancakes)-idx))
flip(idx, pancakes)
default:
maxPos := find(sorted[idx], pancakes)
flip(maxPos, pancakes)
steps = append(steps, strconv.Itoa(len(pancakes)-maxPos))
flip(idx, pancakes)
steps = append(steps, strconv.Itoa(len(pancakes)-idx))
}
return steps
}
func solve(pancakes []string) []string {
sorted := make([]string, len(pancakes))
copy(sorted, pancakes)
sort.Strings(sorted)
var steps []string
for i := len(sorted) - 1; i >= 0; i-- {
steps = append(steps, process(i, sorted, pancakes)...)
}
return append(steps, "0")
}
func main() {
in, _ := os.Open("120.in")
defer in.Close()
out, _ := os.Create("120.out")
defer out.Close()
s := bufio.NewScanner(in)
s.Split(bufio.ScanLines)
for s.Scan() {
line := s.Text()
fmt.Fprintln(out, line)
fmt.Fprintln(out, strings.Join(solve(strings.Fields(line)), " "))
}
}