1
+ // source: // source: https://github.com/maneatingape/advent-of-code-rust/blob/2f5d0220ea44f33545f741e307d4481b50d632c7/src/util/heap.rs
2
+
3
+ //! [Min heap] more suitable for algorithms such as [Dijkstra] and [A*] than Rust's default
4
+ //! max heap. Splits the sorting key and value, so that you can order items without having
5
+ //! to implement [`Ord`] on the value type.
6
+ //!
7
+ //! [Min heap]: https://en.wikipedia.org/wiki/Heap_(data_structure)
8
+ //! [Dijkstra]: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
9
+ //! [A*]: https://en.wikipedia.org/wiki/A*_search_algorithm
10
+ use std:: cmp:: Ordering ;
11
+ use std:: collections:: BinaryHeap ;
12
+
13
+ struct Wrapper < K : Ord , V > {
14
+ key : K ,
15
+ value : V ,
16
+ }
17
+
18
+ impl < K : Ord , V > PartialEq for Wrapper < K , V > {
19
+ #[ inline]
20
+ fn eq ( & self , other : & Self ) -> bool {
21
+ self . key == other. key
22
+ }
23
+ }
24
+
25
+ impl < K : Ord , V > Eq for Wrapper < K , V > { }
26
+
27
+ impl < K : Ord , V > PartialOrd for Wrapper < K , V > {
28
+ #[ inline]
29
+ fn partial_cmp ( & self , other : & Self ) -> Option < Ordering > {
30
+ Some ( self . cmp ( other) )
31
+ }
32
+ }
33
+
34
+ impl < K : Ord , V > Ord for Wrapper < K , V > {
35
+ #[ inline]
36
+ fn cmp ( & self , other : & Self ) -> Ordering {
37
+ other. key . cmp ( & self . key )
38
+ }
39
+ }
40
+
41
+ #[ derive( Default ) ]
42
+ pub struct MinHeap < K : Ord , V > {
43
+ heap : BinaryHeap < Wrapper < K , V > > ,
44
+ }
45
+
46
+ impl < K : Ord , V > MinHeap < K , V > {
47
+ pub fn new ( ) -> Self {
48
+ MinHeap { heap : BinaryHeap :: new ( ) }
49
+ }
50
+
51
+ pub fn with_capacity ( capacity : usize ) -> Self {
52
+ MinHeap { heap : BinaryHeap :: with_capacity ( capacity) }
53
+ }
54
+
55
+ #[ inline]
56
+ pub fn push ( & mut self , key : K , value : V ) {
57
+ self . heap . push ( Wrapper { key, value } ) ;
58
+ }
59
+
60
+ #[ inline]
61
+ pub fn pop ( & mut self ) -> Option < ( K , V ) > {
62
+ self . heap . pop ( ) . map ( |w| ( w. key , w. value ) )
63
+ }
64
+ }
0 commit comments