-
Notifications
You must be signed in to change notification settings - Fork 27
/
762.go
66 lines (60 loc) · 1.27 KB
/
762.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
// UVa 762 - We Ship Cheap
package main
import (
"fmt"
"os"
)
type node struct {
n string
path [][2]string
}
func bfs(links map[string][]string, n1, n2 string) [][2]string {
for visited, queue := map[string]bool{n1: true}, []node{{n1, nil}}; len(queue) > 0; queue = queue[1:] {
curr := queue[0]
if curr.n == n2 {
return curr.path
}
next := links[curr.n]
for _, v := range next {
if _, ok := visited[v]; !ok {
visited[v] = true
path := curr.path
path = append(path, [2]string{curr.n, v})
queue = append(queue, node{v, path})
}
}
}
return nil
}
func main() {
in, _ := os.Open("762.in")
defer in.Close()
out, _ := os.Create("762.out")
defer out.Close()
var ln int
var n1, n2, src, dest string
for first := true; ; {
if _, err := fmt.Fscanf(in, "%d", &ln); err != nil {
break
}
links := make(map[string][]string)
for ; ln > 0; ln-- {
fmt.Fscanf(in, "%s%s", &n1, &n2)
links[n1] = append(links[n1], n2)
links[n2] = append(links[n2], n1)
}
if first {
first = false
} else {
fmt.Fprintln(out)
}
fmt.Fscanf(in, "%s%s\n\n", &src, &dest)
if route := bfs(links, src, dest); route == nil {
fmt.Fprintln(out, "No route")
} else {
for _, v := range route {
fmt.Fprintln(out, v[0], v[1])
}
}
}
}