-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy path200.go
100 lines (91 loc) · 1.72 KB
/
200.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
// UVa 200 - Rare Order
package main
import (
"fmt"
"io"
"os"
)
var (
order []int
visited map[int]bool
)
func buildMatrix(chars map[byte]int, words []string) [][]bool {
matrix := make([][]bool, len(chars))
for i := range matrix {
matrix[i] = make([]bool, len(chars))
}
for i := range words {
if i+1 < len(words) {
minLen := min(len(words[i]), len(words[i+1]))
for j := 0; j < minLen; j++ {
if words[i][j] != words[i+1][j] {
matrix[chars[words[i][j]]][chars[words[i+1][j]]] = true
break
}
}
}
}
return matrix
}
func dfs(matrix [][]bool, route []int) bool {
if len(route) == len(matrix) {
order = make([]int, len(route))
copy(order, route)
return true
}
for i := range matrix {
if !visited[i] && matrix[route[len(route)-1]][i] {
visited[i] = true
if dfs(matrix, append(route, i)) {
return true
}
visited[i] = false
}
}
return false
}
func output(out io.Writer, chars map[byte]int) {
for _, v := range order {
for k, idx := range chars {
if v == idx {
fmt.Fprintf(out, "%c", k)
break
}
}
}
fmt.Fprintln(out)
}
func main() {
in, _ := os.Open("200.in")
defer in.Close()
out, _ := os.Create("200.out")
defer out.Close()
chars := make(map[byte]int)
var words []string
var word string
for {
if fmt.Fscanf(in, "%s", &word); word == "#" {
break
}
for i := range word {
if _, ok := chars[word[i]]; !ok {
chars[word[i]] = len(chars)
}
}
words = append(words, word)
}
matrix := buildMatrix(chars, words)
first := 0
here:
for first = range matrix {
for j := range matrix[first] {
if matrix[j][first] {
continue here
}
}
break
}
visited = map[int]bool{first: true}
dfs(matrix, []int{first})
output(out, chars)
}