-
Notifications
You must be signed in to change notification settings - Fork 0
/
llg.go
117 lines (91 loc) · 1.94 KB
/
llg.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
117
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
content, err := ioutil.ReadAll(reader)
if err != nil {
panic(err)
}
dic := strings.Split(string(content), "\n")
if len(dic) > 0 && dic[len(dic)-1] == "" {
dic = dic[0 : len(dic)-1]
}
result := Sequence(dic)
fmt.Println(result)
}
func Sequence(dic []string) []string {
p := newPathFinder(dic)
result := p.findLongest()
return result
}
func newPathFinder(dic []string) *pathFinder {
return &pathFinder{
dic: dic,
lookup: buildLookup(dic),
visited: make([]bool, len(dic)+1),
result: make([]string, 0, len(dic)),
}
}
type pathFinder struct {
dic []string
result []string
lookup [][]int
visited []bool
}
func buildLookup(dic []string) [][]int {
l := len(dic)
lookup := make([][]int, l+1)
for io, wo := range dic {
if len(lookup[io]) == 0 {
lookup[io] = make([]int, 0, l)
}
for ii, wi := range dic {
if wo[len(wo)-1] == wi[0] && wo != wi {
lookup[io] = append(lookup[io], ii)
}
}
}
lookup[l] = make([]int, l)
for i := 0; i < l; i++ {
lookup[l][i] = i
}
return lookup
}
func (p *pathFinder) enter(i int) {
p.visited[i] = true
}
func (p *pathFinder) exit(index int) {
p.visited[index] = false
}
func (p *pathFinder) isVisited(i int) bool {
return p.visited[i]
}
func (p *pathFinder) setResult(result []string) {
p.result = p.result[:len(result)]
copy(p.result, result)
}
func (p *pathFinder) find(currentIndex int, rest []string) []string {
for _, nextIndex := range p.lookup[currentIndex] {
if p.isVisited(nextIndex) {
continue
}
p.enter(nextIndex)
candidate := append(rest, p.dic[nextIndex])
candidate = p.find(nextIndex, candidate)
p.exit(nextIndex)
if len(candidate) > len(p.result) {
p.setResult(candidate)
}
}
return rest
}
func (p *pathFinder) findLongest() []string {
p.find(len(p.dic), make([]string, 0, len(p.dic)))
return p.result
}