-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_priority.go
88 lines (69 loc) · 1.62 KB
/
template_priority.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
package main
import (
"container/heap"
"fmt"
)
func main() {
var queue PriorityQueue
item := &PriorityItem{Priority: 100}
queue.Push(&PriorityItem{Priority: 1})
queue.Push(&PriorityItem{Priority: 6})
queue.Push(item)
queue.Push(&PriorityItem{Priority: 9})
queue.Push(&PriorityItem{Priority: 3})
queue.Push(&PriorityItem{Priority: 4})
queue.Push(&PriorityItem{Priority: 2})
queue.Push(&PriorityItem{Priority: 8})
queue.Push(&PriorityItem{Priority: 7})
item.Priority = 5
queue.Update(item)
for !queue.Empty() {
fmt.Println(queue.Pop().Priority)
}
}
type PriorityItem struct {
Priority int
Index int
}
type PriorityStorage []*PriorityItem
func (s PriorityStorage) Len() int {
return len(s)
}
func (s PriorityStorage) Less(i, j int) bool {
// Highest priority is popped first.
return s[i].Priority > s[j].Priority
}
func (s PriorityStorage) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
s[i].Index, s[j].Index = i, j
}
func (s *PriorityStorage) Push(x interface{}) {
item := x.(*PriorityItem)
item.Index = len(*s)
*s = append(*s, item)
}
func (s *PriorityStorage) Pop() interface{} {
len := len(*s)
item := (*s)[len-1]
item.Index = -1
*s = (*s)[:len-1]
return item
}
type PriorityQueue struct {
storage PriorityStorage
}
func (q *PriorityQueue) Len() int {
return len(q.storage)
}
func (q *PriorityQueue) Empty() bool {
return len(q.storage) == 0
}
func (q *PriorityQueue) Push(item *PriorityItem) {
heap.Push(&q.storage, item)
}
func (q *PriorityQueue) Pop() *PriorityItem {
return heap.Pop(&q.storage).(*PriorityItem)
}
func (q *PriorityQueue) Update(item *PriorityItem) {
heap.Fix(&q.storage, item.Index)
}