-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path571.go
More file actions
80 lines (73 loc) · 2.08 KB
/
571.go
File metadata and controls
80 lines (73 loc) · 2.08 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 571 - Jugs
package main
import (
"fmt"
"os"
"strings"
)
type (
status struct{ a, b int }
node struct {
status
steps []string
}
)
func buildStatus(a, b int) status { return status{a, b} }
func bfs(a, b, n int) []string {
for visited, queue := map[status]bool{{0, 0}: true}, []node{{status{0, 0}, nil}}; len(queue) > 0; queue = queue[1:] {
curr := queue[0]
if curr.a == n || curr.b == n {
return append(curr.steps, "success")
}
if s := buildStatus(a, curr.b); curr.a == 0 && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "fill A")})
}
if s := buildStatus(curr.a, b); curr.b == 0 && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "fill B")})
}
if curr.a < a && curr.b > 0 {
if s := buildStatus(curr.a+curr.b, 0); curr.b < (a-curr.a) && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "pour B A")})
}
if s := buildStatus(a, curr.b-(a-curr.a)); curr.b >= (a-curr.a) && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "pour B A")})
}
}
if curr.a > 0 && curr.b < b {
if s := buildStatus(0, curr.a+curr.b); curr.a < (b-curr.b) && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "pour A B")})
}
if s := buildStatus(curr.a-(b-curr.b), b); curr.a >= (b-curr.b) && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "pour A B")})
}
}
if s := buildStatus(0, curr.b); curr.a > 0 && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "empty A")})
}
if s := buildStatus(curr.a, 0); curr.b > 0 && !visited[s] {
visited[s] = true
queue = append(queue, node{s, append(curr.steps, "empty B")})
}
}
return nil
}
func main() {
in, _ := os.Open("571.in")
defer in.Close()
out, _ := os.Create("571.out")
defer out.Close()
var a, b, n int
for {
if _, err := fmt.Fscanf(in, "%d%d%d", &a, &b, &n); err != nil {
break
}
fmt.Fprintln(out, strings.Join(bfs(a, b, n), "\n"))
}
}