]> git.lizzy.rs Git - rust.git/blob - src/libcollections/priority_queue.rs
9451f2521c89a67e263e7c269405be245cd14aa2
[rust.git] / src / libcollections / priority_queue.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A priority queue implemented with a binary heap.
12 //!
13 //! # Example
14 //!
15 //! This is a larger example which implements [Dijkstra's algorithm][dijkstra]
16 //! to solve the [shortest path problem][sssp] on a [directed graph][dir_graph].
17 //! It showcases how to use the `PriorityQueue` with custom types.
18 //!
19 //! [dijkstra]: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
20 //! [sssp]: http://en.wikipedia.org/wiki/Shortest_path_problem
21 //! [dir_graph]: http://en.wikipedia.org/wiki/Directed_graph
22 //!
23 //! ```
24 //! use std::collections::PriorityQueue;
25 //! use std::uint;
26 //!
27 //! #[deriving(Eq, PartialEq)]
28 //! struct State {
29 //!     cost: uint,
30 //!     position: uint
31 //! }
32 //!
33 //! // The priority queue depends on `Ord`.
34 //! // Explicitly implement the trait so the queue becomes a min-heap
35 //! // instead of a max-heap.
36 //! impl Ord for State {
37 //!     fn cmp(&self, other: &State) -> Ordering {
38 //!         // Notice that the we flip the ordering here
39 //!         other.cost.cmp(&self.cost)
40 //!     }
41 //! }
42 //!
43 //! // `PartialOrd` needs to be implemented as well.
44 //! impl PartialOrd for State {
45 //!     fn partial_cmp(&self, other: &State) -> Option<Ordering> {
46 //!         Some(self.cmp(other))
47 //!     }
48 //! }
49 //!
50 //! // Each node is represented as an `uint`, for a shorter implementation.
51 //! struct Edge {
52 //!     node: uint,
53 //!     cost: uint
54 //! }
55 //!
56 //! // Dijkstra's shortest path algorithm.
57 //!
58 //! // Start at `start` and use `dist` to track the current shortest distance
59 //! // to each node. This implementation isn't memory efficient as it may leave duplicate
60 //! // nodes in the queue. It also uses `uint::MAX` as a sentinel value,
61 //! // for a simpler implementation.
62 //! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: uint, goal: uint) -> uint {
63 //!     // dist[node] = current shortest distance from `start` to `node`
64 //!     let mut dist = Vec::from_elem(adj_list.len(), uint::MAX);
65 //!
66 //!     let mut pq = PriorityQueue::new();
67 //!
68 //!     // We're at `start`, with a zero cost
69 //!     *dist.get_mut(start) = 0u;
70 //!     pq.push(State { cost: 0u, position: start });
71 //!
72 //!     // Examine the frontier with lower cost nodes first (min-heap)
73 //!     loop {
74 //!         let State { cost, position } = match pq.pop() {
75 //!             None => break, // empty
76 //!             Some(s) => s
77 //!         };
78 //!
79 //!         // Alternatively we could have continued to find all shortest paths
80 //!         if position == goal { return cost }
81 //!
82 //!         // Important as we may have already found a better way
83 //!         if cost > dist[position] { continue }
84 //!
85 //!         // For each node we can reach, see if we can find a way with
86 //!         // a lower cost going through this node
87 //!         for edge in adj_list[position].iter() {
88 //!             let next = State { cost: cost + edge.cost, position: edge.node };
89 //!
90 //!             // If so, add it to the frontier and continue
91 //!             if next.cost < dist[next.position] {
92 //!                 pq.push(next);
93 //!                 // Relaxation, we have now found a better way
94 //!                 *dist.get_mut(next.position) = next.cost;
95 //!             }
96 //!         }
97 //!     }
98 //!
99 //!     // Goal not reachable
100 //!     uint::MAX
101 //! }
102 //!
103 //! fn main() {
104 //!     // This is the directed graph we're going to use.
105 //!     // The node numbers correspond to the different states,
106 //!     // and the edge weights symbolises the cost of moving
107 //!     // from one node to another.
108 //!     // Note that the edges are one-way.
109 //!     //
110 //!     //                  7
111 //!     //          +-----------------+
112 //!     //          |                 |
113 //!     //          v   1        2    |
114 //!     //          0 -----> 1 -----> 3 ---> 4
115 //!     //          |        ^        ^      ^
116 //!     //          |        | 1      |      |
117 //!     //          |        |        | 3    | 1
118 //!     //          +------> 2 -------+      |
119 //!     //           10      |               |
120 //!     //                   +---------------+
121 //!     //
122 //!     // The graph is represented as an adjecency list where each index,
123 //!     // corresponding to a node value, has a list of outgoing edges.
124 //!     // Chosen for it's efficiency.
125 //!     let graph = vec![
126 //!         // Node 0
127 //!         vec![Edge { node: 2, cost: 10 },
128 //!              Edge { node: 1, cost: 1 }],
129 //!         // Node 1
130 //!         vec![Edge { node: 3, cost: 2 }],
131 //!         // Node 2
132 //!         vec![Edge { node: 1, cost: 1 },
133 //!              Edge { node: 3, cost: 3 },
134 //!              Edge { node: 4, cost: 1 }],
135 //!         // Node 3
136 //!         vec![Edge { node: 0, cost: 7 },
137 //!              Edge { node: 4, cost: 2 }],
138 //!         // Node 4
139 //!         vec![]];
140 //!
141 //!     assert_eq!(shortest_path(&graph, 0, 1), 1);
142 //!     assert_eq!(shortest_path(&graph, 0, 3), 3);
143 //!     assert_eq!(shortest_path(&graph, 3, 0), 7);
144 //!     assert_eq!(shortest_path(&graph, 0, 4), 5);
145 //!     assert_eq!(shortest_path(&graph, 4, 0), uint::MAX);
146 //! }
147 //! ```
148
149 #![allow(missing_doc)]
150
151 use core::prelude::*;
152
153 use core::default::Default;
154 use core::mem::{zeroed, replace, swap};
155 use core::ptr;
156
157 use {Collection, Mutable};
158 use slice;
159 use vec::Vec;
160
161 /// A priority queue implemented with a binary heap
162 #[deriving(Clone)]
163 pub struct PriorityQueue<T> {
164     data: Vec<T>,
165 }
166
167 impl<T: Ord> Collection for PriorityQueue<T> {
168     /// Returns the length of the queue
169     fn len(&self) -> uint { self.data.len() }
170 }
171
172 impl<T: Ord> Mutable for PriorityQueue<T> {
173     /// Drop all items from the queue
174     fn clear(&mut self) { self.data.truncate(0) }
175 }
176
177 impl<T: Ord> Default for PriorityQueue<T> {
178     #[inline]
179     fn default() -> PriorityQueue<T> { PriorityQueue::new() }
180 }
181
182 impl<T: Ord> PriorityQueue<T> {
183     /// An iterator visiting all values in underlying vector, in
184     /// arbitrary order.
185     pub fn iter<'a>(&'a self) -> Items<'a, T> {
186         Items { iter: self.data.iter() }
187     }
188
189     /// Returns the greatest item in a queue or None if it is empty
190     pub fn top<'a>(&'a self) -> Option<&'a T> {
191         if self.is_empty() { None } else { Some(self.data.get(0)) }
192     }
193
194     #[deprecated="renamed to `top`"]
195     pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
196
197     /// Returns the number of elements the queue can hold without reallocating
198     pub fn capacity(&self) -> uint { self.data.capacity() }
199
200     /// Reserve capacity for exactly n elements in the PriorityQueue.
201     /// Do nothing if the capacity is already sufficient.
202     pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }
203
204     /// Reserve capacity for at least n elements in the PriorityQueue.
205     /// Do nothing if the capacity is already sufficient.
206     pub fn reserve(&mut self, n: uint) {
207         self.data.reserve(n)
208     }
209
210     /// Remove the greatest item from a queue and return it, or `None` if it is
211     /// empty.
212     pub fn pop(&mut self) -> Option<T> {
213         match self.data.pop() {
214             None           => { None }
215             Some(mut item) => {
216                 if !self.is_empty() {
217                     swap(&mut item, self.data.get_mut(0));
218                     self.siftdown(0);
219                 }
220                 Some(item)
221             }
222         }
223     }
224
225     #[deprecated="renamed to `pop`"]
226     pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
227
228     /// Push an item onto the queue
229     pub fn push(&mut self, item: T) {
230         self.data.push(item);
231         let new_len = self.len() - 1;
232         self.siftup(0, new_len);
233     }
234
235     /// Optimized version of a push followed by a pop
236     pub fn push_pop(&mut self, mut item: T) -> T {
237         if !self.is_empty() && *self.top().unwrap() > item {
238             swap(&mut item, self.data.get_mut(0));
239             self.siftdown(0);
240         }
241         item
242     }
243
244     /// Optimized version of a pop followed by a push. The push is done
245     /// regardless of whether the queue is empty.
246     pub fn replace(&mut self, mut item: T) -> Option<T> {
247         if !self.is_empty() {
248             swap(&mut item, self.data.get_mut(0));
249             self.siftdown(0);
250             Some(item)
251         } else {
252             self.push(item);
253             None
254         }
255     }
256
257     #[allow(dead_code)]
258     #[deprecated="renamed to `into_vec`"]
259     fn to_vec(self) -> Vec<T> { self.into_vec() }
260
261     #[allow(dead_code)]
262     #[deprecated="renamed to `into_sorted_vec`"]
263     fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
264
265     /// Consume the PriorityQueue and return the underlying vector
266     pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
267
268     /// Consume the PriorityQueue and return a vector in sorted
269     /// (ascending) order
270     pub fn into_sorted_vec(self) -> Vec<T> {
271         let mut q = self;
272         let mut end = q.len();
273         while end > 1 {
274             end -= 1;
275             q.data.as_mut_slice().swap(0, end);
276             q.siftdown_range(0, end)
277         }
278         q.into_vec()
279     }
280
281     /// Create an empty PriorityQueue
282     pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
283
284     /// Create an empty PriorityQueue with capacity `capacity`
285     pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
286         PriorityQueue { data: Vec::with_capacity(capacity) }
287     }
288
289     /// Create a PriorityQueue from a vector (heapify)
290     pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
291         let mut q = PriorityQueue{data: xs,};
292         let mut n = q.len() / 2;
293         while n > 0 {
294             n -= 1;
295             q.siftdown(n)
296         }
297         q
298     }
299
300     // The implementations of siftup and siftdown use unsafe blocks in
301     // order to move an element out of the vector (leaving behind a
302     // zeroed element), shift along the others and move it back into the
303     // vector over the junk element.  This reduces the constant factor
304     // compared to using swaps, which involves twice as many moves.
305     fn siftup(&mut self, start: uint, mut pos: uint) {
306         unsafe {
307             let new = replace(self.data.get_mut(pos), zeroed());
308
309             while pos > start {
310                 let parent = (pos - 1) >> 1;
311                 if new > *self.data.get(parent) {
312                     let x = replace(self.data.get_mut(parent), zeroed());
313                     ptr::write(self.data.get_mut(pos), x);
314                     pos = parent;
315                     continue
316                 }
317                 break
318             }
319             ptr::write(self.data.get_mut(pos), new);
320         }
321     }
322
323     fn siftdown_range(&mut self, mut pos: uint, end: uint) {
324         unsafe {
325             let start = pos;
326             let new = replace(self.data.get_mut(pos), zeroed());
327
328             let mut child = 2 * pos + 1;
329             while child < end {
330                 let right = child + 1;
331                 if right < end && !(*self.data.get(child) > *self.data.get(right)) {
332                     child = right;
333                 }
334                 let x = replace(self.data.get_mut(child), zeroed());
335                 ptr::write(self.data.get_mut(pos), x);
336                 pos = child;
337                 child = 2 * pos + 1;
338             }
339
340             ptr::write(self.data.get_mut(pos), new);
341             self.siftup(start, pos);
342         }
343     }
344
345     fn siftdown(&mut self, pos: uint) {
346         let len = self.len();
347         self.siftdown_range(pos, len);
348     }
349 }
350
351 /// PriorityQueue iterator
352 pub struct Items <'a, T> {
353     iter: slice::Items<'a, T>,
354 }
355
356 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
357     #[inline]
358     fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
359
360     #[inline]
361     fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
362 }
363
364 impl<T: Ord> FromIterator<T> for PriorityQueue<T> {
365     fn from_iter<Iter: Iterator<T>>(iter: Iter) -> PriorityQueue<T> {
366         let mut q = PriorityQueue::new();
367         q.extend(iter);
368         q
369     }
370 }
371
372 impl<T: Ord> Extendable<T> for PriorityQueue<T> {
373     fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
374         let (lower, _) = iter.size_hint();
375
376         let len = self.capacity();
377         self.reserve(len + lower);
378
379         for elem in iter {
380             self.push(elem);
381         }
382     }
383 }
384
385 #[cfg(test)]
386 mod tests {
387     use std::prelude::*;
388
389     use priority_queue::PriorityQueue;
390     use vec::Vec;
391
392     #[test]
393     fn test_iterator() {
394         let data = vec!(5i, 9, 3);
395         let iterout = [9i, 5, 3];
396         let pq = PriorityQueue::from_vec(data);
397         let mut i = 0;
398         for el in pq.iter() {
399             assert_eq!(*el, iterout[i]);
400             i += 1;
401         }
402     }
403
404     #[test]
405     fn test_top_and_pop() {
406         let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
407         let mut sorted = data.clone();
408         sorted.sort();
409         let mut heap = PriorityQueue::from_vec(data);
410         while !heap.is_empty() {
411             assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
412             assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
413         }
414     }
415
416     #[test]
417     fn test_push() {
418         let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
419         assert_eq!(heap.len(), 3);
420         assert!(*heap.top().unwrap() == 9);
421         heap.push(11);
422         assert_eq!(heap.len(), 4);
423         assert!(*heap.top().unwrap() == 11);
424         heap.push(5);
425         assert_eq!(heap.len(), 5);
426         assert!(*heap.top().unwrap() == 11);
427         heap.push(27);
428         assert_eq!(heap.len(), 6);
429         assert!(*heap.top().unwrap() == 27);
430         heap.push(3);
431         assert_eq!(heap.len(), 7);
432         assert!(*heap.top().unwrap() == 27);
433         heap.push(103);
434         assert_eq!(heap.len(), 8);
435         assert!(*heap.top().unwrap() == 103);
436     }
437
438     #[test]
439     fn test_push_unique() {
440         let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
441         assert_eq!(heap.len(), 3);
442         assert!(*heap.top().unwrap() == box 9);
443         heap.push(box 11);
444         assert_eq!(heap.len(), 4);
445         assert!(*heap.top().unwrap() == box 11);
446         heap.push(box 5);
447         assert_eq!(heap.len(), 5);
448         assert!(*heap.top().unwrap() == box 11);
449         heap.push(box 27);
450         assert_eq!(heap.len(), 6);
451         assert!(*heap.top().unwrap() == box 27);
452         heap.push(box 3);
453         assert_eq!(heap.len(), 7);
454         assert!(*heap.top().unwrap() == box 27);
455         heap.push(box 103);
456         assert_eq!(heap.len(), 8);
457         assert!(*heap.top().unwrap() == box 103);
458     }
459
460     #[test]
461     fn test_push_pop() {
462         let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
463         assert_eq!(heap.len(), 5);
464         assert_eq!(heap.push_pop(6), 6);
465         assert_eq!(heap.len(), 5);
466         assert_eq!(heap.push_pop(0), 5);
467         assert_eq!(heap.len(), 5);
468         assert_eq!(heap.push_pop(4), 5);
469         assert_eq!(heap.len(), 5);
470         assert_eq!(heap.push_pop(1), 4);
471         assert_eq!(heap.len(), 5);
472     }
473
474     #[test]
475     fn test_replace() {
476         let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
477         assert_eq!(heap.len(), 5);
478         assert_eq!(heap.replace(6).unwrap(), 5);
479         assert_eq!(heap.len(), 5);
480         assert_eq!(heap.replace(0).unwrap(), 6);
481         assert_eq!(heap.len(), 5);
482         assert_eq!(heap.replace(4).unwrap(), 5);
483         assert_eq!(heap.len(), 5);
484         assert_eq!(heap.replace(1).unwrap(), 4);
485         assert_eq!(heap.len(), 5);
486     }
487
488     fn check_to_vec(mut data: Vec<int>) {
489         let heap = PriorityQueue::from_vec(data.clone());
490         let mut v = heap.clone().into_vec();
491         v.sort();
492         data.sort();
493
494         assert_eq!(v.as_slice(), data.as_slice());
495         assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
496     }
497
498     #[test]
499     fn test_to_vec() {
500         check_to_vec(vec!());
501         check_to_vec(vec!(5i));
502         check_to_vec(vec!(3i, 2));
503         check_to_vec(vec!(2i, 3));
504         check_to_vec(vec!(5i, 1, 2));
505         check_to_vec(vec!(1i, 100, 2, 3));
506         check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
507         check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
508         check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
509         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
510         check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
511         check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
512         check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
513     }
514
515     #[test]
516     fn test_empty_pop() {
517         let mut heap: PriorityQueue<int> = PriorityQueue::new();
518         assert!(heap.pop().is_none());
519     }
520
521     #[test]
522     fn test_empty_top() {
523         let empty: PriorityQueue<int> = PriorityQueue::new();
524         assert!(empty.top().is_none());
525     }
526
527     #[test]
528     fn test_empty_replace() {
529         let mut heap: PriorityQueue<int> = PriorityQueue::new();
530         heap.replace(5).is_none();
531     }
532
533     #[test]
534     fn test_from_iter() {
535         let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
536
537         let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
538
539         for &x in xs.iter() {
540             assert_eq!(q.pop().unwrap(), x);
541         }
542     }
543 }