-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path208.go
116 lines (105 loc) · 1.88 KB
/
208.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
108
109
110
111
112
113
114
115
116
// UVa 208 - Firetruck
package main
import (
"fmt"
"io"
"os"
)
const max = 21
var (
out io.WriteCloser
matrix [][]bool
total, n, fire int
visited []bool
streetCorners []int
)
func unionFind(x int, f []int) int {
if f[x] != x {
f[x] = unionFind(f[x], f)
}
return f[x]
}
func clear() {
matrix = make([][]bool, max)
for i := range matrix {
matrix[i] = make([]bool, max)
}
}
func output(path []int) {
for _, s := range path {
fmt.Fprintf(out, " %d", s)
}
fmt.Fprintln(out)
}
func dfs(curr int, path []int) {
if curr == fire {
output(path)
total++
return
}
for _, s := range streetCorners {
if !visited[s] && matrix[curr][s] {
visited[s] = true
dfs(s, append(path, s))
visited[s] = false
}
}
}
func solve() {
matrix = matrix[:n+1]
for i := range matrix {
matrix[i] = matrix[i][:n+1]
}
f := make([]int, n+1)
for i := range f {
f[i] = i
}
for i := 1; i < n; i++ {
for j := i + 1; j <= n; j++ {
if matrix[i][j] {
if s1, s2 := unionFind(i, f), unionFind(j, f); s1 != s2 {
f[s1] = s2
}
}
}
}
streetCorners = nil
for i := 1; i <= n; i++ {
if unionFind(i, f) == unionFind(fire, f) {
streetCorners = append(streetCorners, i)
}
}
visited = make([]bool, n+1)
visited[1] = true
total = 0
dfs(1, []int{1})
fmt.Fprintf(out, "There are %d routes from the firestation to streetcorner %d.\n", total, fire)
}
func main() {
in, _ := os.Open("208.in")
defer in.Close()
out, _ = os.Create("208.out")
defer out.Close()
var from, to int
for kase := 1; ; kase++ {
if _, err := fmt.Fscanf(in, "%d", &fire); err != nil {
break
}
clear()
n = 0
for {
if fmt.Fscanf(in, "%d%d", &from, &to); from == 0 && to == 0 {
break
}
matrix[from][to], matrix[to][from] = true, true
if from > n {
n = from
}
if to > n {
n = to
}
}
fmt.Fprintf(out, "CASE %d:\n", kase)
solve()
}
}