-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeta_engine.go
135 lines (124 loc) · 2.51 KB
/
meta_engine.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
132
133
134
135
package fsp
import (
//"container/heap"
"math"
"sync"
)
type penalty struct {
init Money
m *sync.Mutex
}
func (p *penalty) save(s partial, q float64) {
p.m.Lock()
if p.init == 0 {
p.init = s.cost
}
normalized := float64(s.cost) / float64(p.init)
fraction := (normalized*q) / 5000
for _, f := range s.flights {
f.Penalty += fraction
}
p.m.Unlock()
}
type heuristics func(*Flight) float64
type MetaEngine struct {
weight []float64
q float64
name string
graph Graph
h heuristics
p *penalty
}
func (m MetaEngine) Name() string {
return m.name
}
func (m MetaEngine) Solve(comm comm, problem Problem) {
flights := make([]*Flight, 0, problem.n)
visited := make(map[City]bool)
partial := partial{visited, flights, problem.n, 0}
for {
f := nextFlight(m.graph.fromDaySortedCost[0][0], &partial, m.weight[0], m.h)
partial.fly(f)
partial.visited[0] = false
if ok := m.run(&partial); ok {
comm.sendSolution(NewSolution(partial.solution()))
}
m.p.save(partial, m.q)
partial.flights = partial.flights[0:0]
for k, _ := range partial.visited {
partial.visited[k] = false
}
partial.cost = 0
}
}
func (m *MetaEngine) run(partial *partial) bool {
for {
if partial.roundtrip() {
return true
}
lf := partial.lastFlight()
d := lf.Day + 1
dst := m.graph.fromDaySortedCost[lf.To][d]
nextFlight := nextFlight(dst, partial, m.weight[d], m.h)
if nextFlight == nil {
return false
}
partial.fly(nextFlight)
}
}
func nextFlight(flights []*Flight, partial *partial, weight float64, h heuristics) *Flight {
var cMax Money
var pMax float64
var hMax float64
valid := false
for _, f := range flights {
if partial.hasVisited(f.To) {
continue
}
valid = true
if cMax < f.Cost {
cMax = f.Cost
}
if pMax < f.Penalty {
pMax = f.Penalty
}
hVal := h(f)
if hMax < hVal {
hMax = hVal
}
}
if !valid {
return nil
}
if pMax == 0 {
pMax = 1
}
best := float64(math.MaxFloat32)
var bestFlight *Flight
for _, f := range flights {
if partial.hasVisited(f.To) {
continue
}
ncost := float64(f.Cost) / float64(cMax)
npen := f.Penalty / pMax
nheur := h(f) / hMax
val := (1-weight)*ncost + weight*(npen+nheur)
if best > val {
best = val
bestFlight = f
}
}
return bestFlight
}
func initWeight(size int, max float64) []float64 {
last := size - 2
diff := max / float64(last)
weight := make([]float64, size)
weight[0] = max
weight[last] = 0
weight[last+1] = 0
for i := 1; i < last; i++ {
weight[i] = weight[i-1] - diff
}
return weight
}