-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpriority_queue.go
56 lines (44 loc) · 940 Bytes
/
priority_queue.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
package main
import "container/heap"
type item struct {
value Node
priority int
}
type PriorityQueue []*item
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
return pq[i].priority < pq[j].priority
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *PriorityQueue) Push(x interface{}) {
it := x.(*item)
*pq = append(*pq, it)
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
it := old[n-1]
old[n-1] = nil
*pq = old[0 : n-1]
return it
}
func NewPriorityQueue() *PriorityQueue {
pq := make(PriorityQueue, 0)
heap.Init(&pq)
return &pq
}
// typed wrappers around heap package
func (pq *PriorityQueue) Insert(node Node, priority int) {
heap.Push(pq, &item{
value: node,
priority: priority,
})
}
func (pq *PriorityQueue) PopMin() (Node, int) {
it := heap.Pop(pq).(*item)
return it.value, it.priority
}