-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
131 lines (113 loc) · 2.28 KB
/
main.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"bufio"
"io"
lib "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
scanner := bufio.NewScanner(input)
ports := make(map[int][]int)
for scanner.Scan() {
line := scanner.Text()
del := lib.NewDelimiter(line, "/")
in := del.GetInt(0)
out := del.GetInt(1)
ports[in] = append(ports[in], out)
ports[out] = append(ports[out], in)
}
p := &Ports{ports}
return best(p, 0, 0)
}
func copy(s []int) []int {
res := make([]int, len(s))
for i := 0; i < len(s); i++ {
res[i] = s[i]
}
return res
}
func best(p *Ports, lastOut int, cur int) int {
v, exists := p.ports[lastOut]
if !exists {
return cur
}
outs := copy(v)
max := cur
for _, out := range outs {
a := p.remove(lastOut, out)
b := p.remove(out, lastOut)
max = lib.Max(max, best(p, out, cur+lastOut+out))
b()
a()
}
return max
}
type Ports struct {
ports map[int][]int
}
func (p *Ports) remove(in, out int) func() {
if len(p.ports[in]) == 1 {
delete(p.ports, in)
return func() {
p.ports[in] = []int{out}
}
}
res := make([]int, 0, len(p.ports[in])-1)
i := 0
s := p.ports[in]
for ; ; i++ {
if s[i] != out {
res = append(res, s[i])
continue
}
i++
break
}
for ; i < len(s); i++ {
res = append(res, s[i])
}
p.ports[in] = res
return func() {
p.ports[in] = append(p.ports[in], out)
}
}
func fs2(input io.Reader) int {
scanner := bufio.NewScanner(input)
ports := make(map[int][]int)
for scanner.Scan() {
line := scanner.Text()
del := lib.NewDelimiter(line, "/")
in := del.GetInt(0)
out := del.GetInt(1)
ports[in] = append(ports[in], out)
ports[out] = append(ports[out], in)
}
p := &Ports{ports}
_, strength := strengthLongest(p, 0, 0, 0)
return strength
}
func strengthLongest(p *Ports, lastOut int, curLength, curStrength int) (int, int) {
v, exists := p.ports[lastOut]
if !exists {
return curLength, curStrength
}
outs := copy(v)
maxLength := 0
maxStrength := 0
for _, out := range outs {
a := p.remove(lastOut, out)
b := p.remove(out, lastOut)
l, s := strengthLongest(p, out, curLength+2, curStrength+lastOut+out)
if l > maxLength {
maxLength = l
maxStrength = s
} else if l == maxLength {
if s > maxStrength {
maxLength = l
maxStrength = s
}
}
b()
a()
}
return maxLength, maxStrength
}