/
heap.jl
58 lines (45 loc) · 1.47 KB
/
heap.jl
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
"""
HeapPriorityQueue{K,V}
Min priority queue with keys of type `K` and priority values of type `V`, stored using a binary heap from DataStructures.jl.
# Fields
- `heap::BinaryHeap{K,V}`: heap of key-value pairs `k => v` ordered by increasing `v`
"""
struct HeapPriorityQueue{K,V}
pairs::BinaryHeap{Pair{K,V},Base.Order.By{typeof(last),Base.Order.ForwardOrdering}}
end
function HeapPriorityQueue{K,V}() where {K,V}
pairs = BinaryHeap(Base.By(last), Pair{K,V}[])
return HeapPriorityQueue{K,V}(pairs)
end
## Vector behavior
Base.length(pq::HeapPriorityQueue) = length(pq.pairs)
Base.isempty(pq::HeapPriorityQueue) = isempty(pq.pairs)
Base.first(pq::HeapPriorityQueue) = first(pq.pairs)
Base.peek(pq::HeapPriorityQueue) = first(pq)
## Queue behavior
"""
enqueue!(pq::HeapPriorityQueue, k, v)
Insert `k => v` into the queue `pq`.
Amortized complexity `O(log n)`.
"""
function DataStructures.enqueue!(pq::HeapPriorityQueue{K,V}, k::K, v::V) where {K,V}
push!(pq.pairs, k => v)
return nothing
end
"""
dequeue!(pq::HeapPriorityQueue)
Remove and return the key `k` with lowest priority value `v`.
Amortized complexity `O(1)`.
"""
function DataStructures.dequeue!(pq::HeapPriorityQueue)
k, _ = pop!(pq.pairs)
return k
end
"""
dequeue_pair!(pq::HeapPriorityQueue)
Remove and return the pair `k => v` with lowest priority value `v`.
Amortized complexity `O(1)`.
"""
function DataStructures.dequeue_pair!(pq::HeapPriorityQueue)
return pop!(pq.pairs)
end