-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgreedy_rounds.go
More file actions
109 lines (94 loc) · 2.16 KB
/
Copy pathgreedy_rounds.go
File metadata and controls
109 lines (94 loc) · 2.16 KB
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
package fsp
import (
"container/heap"
"math"
// "sort"
"time"
)
type GreedyRounds struct {
graph Graph
currentBest Money
}
func (d GreedyRounds) Name() string {
return "GreedyRounds"
}
func NewGreedyRounds(g Graph) GreedyRounds {
return GreedyRounds{graph, Money(math.MaxInt32)}
}
func initStart(g Graph, problem Problem) []fd {
h := fdHeap(make([]fd, 0, 10))
for _, fromList := range g.data {
for _, flights := range fromList {
for _, f := range flights {
stat := problem.stats.ByDest[f.From][f.To]
discount := stat.AvgPrice - float32(f.Cost)
if len(h) < cap(h) {
h = append(h, fd{f, discount})
if len(h) == cap(h) {
heap.Init(&h)
}
} else {
if h[0].d < discount {
heap.Pop(&h)
heap.Push(&h, fd{f, discount})
}
}
}
}
}
return h
}
func (d GreedyRounds) Solve(comm comm, problem Problem) {
flights := make([]*Flight, 0, problem.n)
visited := make(map[City]bool)
partial := partial{visited, flights, problem.n, 0}
for i, f := range initStart(d.graph, problem) {
printInfo("GreedyRounds start", i, f)
partial.fly(f.f)
d.dfs(comm, &partial, time.After(3*time.Second))
partial.backtrack()
}
}
func (d *GreedyRounds) dfs(comm comm, partial *partial, timeout <-chan time.Time) bool {
if expired(timeout) {
return true
}
if partial.cost > d.currentBest {
return false
}
if partial.roundtrip() {
d.currentBest = comm.sendSolution(NewSolution(partial.solution()))
}
lf := partial.lastFlight()
if partial.hasVisited(lf.To) {
return false
}
dst := d.graph.fromDaySortedCost[lf.To][int(lf.Day+1)%d.graph.size]
for _, f := range dst {
partial.fly(f)
expired := d.dfs(comm, partial, timeout)
partial.backtrack()
if expired {
return true
}
}
return false
}
type fd struct {
f *Flight
d float32
}
type fdHeap []fd
func (h fdHeap) Len() int { return len(h) }
func (h fdHeap) Less(i, j int) bool { return h[i].d < h[j].d }
func (h fdHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *fdHeap) Push(x interface{}) {
*h = append(*h, x.(fd))
}
func (h *fdHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}