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.
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.
11 //! A priority queue implemented with a binary heap.
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.
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
24 //! use std::collections::PriorityQueue;
27 //! #[deriving(Eq, PartialEq)]
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)
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))
50 //! // Each node is represented as an `uint`, for a shorter implementation.
56 //! // Dijkstra's shortest path algorithm.
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);
66 //! let mut pq = PriorityQueue::new();
68 //! // We're at `start`, with a zero cost
69 //! *dist.get_mut(start) = 0u;
70 //! pq.push(State { cost: 0u, position: start });
72 //! // Examine the frontier with lower cost nodes first (min-heap)
74 //! let State { cost, position } = match pq.pop() {
75 //! None => break, // empty
79 //! // Alternatively we could have continued to find all shortest paths
80 //! if position == goal { return cost }
82 //! // Important as we may have already found a better way
83 //! if cost > dist[position] { continue }
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 };
90 //! // If so, add it to the frontier and continue
91 //! if next.cost < dist[next.position] {
93 //! // Relaxation, we have now found a better way
94 //! *dist.get_mut(next.position) = next.cost;
99 //! // Goal not reachable
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.
111 //! // +-----------------+
114 //! // 0 -----> 1 -----> 3 ---> 4
118 //! // +------> 2 -------+ |
120 //! // +---------------+
122 //! // The graph is represented as an adjacency 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![
127 //! vec![Edge { node: 2, cost: 10 },
128 //! Edge { node: 1, cost: 1 }],
130 //! vec![Edge { node: 3, cost: 2 }],
132 //! vec![Edge { node: 1, cost: 1 },
133 //! Edge { node: 3, cost: 3 },
134 //! Edge { node: 4, cost: 1 }],
136 //! vec![Edge { node: 0, cost: 7 },
137 //! Edge { node: 4, cost: 2 }],
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);
149 #![allow(missing_doc)]
151 use core::prelude::*;
153 use core::default::Default;
154 use core::mem::{zeroed, replace, swap};
157 use {Mutable, MutableSeq};
161 /// A priority queue implemented with a binary heap.
163 /// This will be a max-heap.
165 pub struct PriorityQueue<T> {
169 impl<T: Ord> Collection for PriorityQueue<T> {
170 /// Returns the length of the queue.
171 fn len(&self) -> uint { self.data.len() }
174 impl<T: Ord> Mutable for PriorityQueue<T> {
175 /// Drops all items from the queue.
176 fn clear(&mut self) { self.data.truncate(0) }
179 impl<T: Ord> Default for PriorityQueue<T> {
181 fn default() -> PriorityQueue<T> { PriorityQueue::new() }
184 impl<T: Ord> PriorityQueue<T> {
185 /// Creates an empty `PriorityQueue` as a max-heap.
190 /// use std::collections::PriorityQueue;
191 /// let pq: PriorityQueue<uint> = PriorityQueue::new();
193 pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
195 /// Creates an empty `PriorityQueue` with a specific capacity.
196 /// This preallocates enough memory for `capacity` elements,
197 /// so that the `PriorityQueue` does not have to be reallocated
198 /// until it contains at least that many values.
203 /// use std::collections::PriorityQueue;
204 /// let pq: PriorityQueue<uint> = PriorityQueue::with_capacity(10u);
206 pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
207 PriorityQueue { data: Vec::with_capacity(capacity) }
210 /// Creates a `PriorityQueue` from a vector. This is sometimes called
211 /// `heapifying` the vector.
216 /// use std::collections::PriorityQueue;
217 /// let pq = PriorityQueue::from_vec(vec![9i, 1, 2, 7, 3, 2]);
219 pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
220 let mut q = PriorityQueue{data: xs,};
221 let mut n = q.len() / 2;
229 /// An iterator visiting all values in underlying vector, in
235 /// use std::collections::PriorityQueue;
236 /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4]);
238 /// // Print 1, 2, 3, 4 in arbitrary order
239 /// for x in pq.iter() {
240 /// println!("{}", x);
243 pub fn iter<'a>(&'a self) -> Items<'a, T> {
244 Items { iter: self.data.iter() }
247 /// Returns the greatest item in a queue, or `None` if it is empty.
252 /// use std::collections::PriorityQueue;
254 /// let mut pq = PriorityQueue::new();
255 /// assert_eq!(pq.top(), None);
260 /// assert_eq!(pq.top(), Some(&5i));
263 pub fn top<'a>(&'a self) -> Option<&'a T> {
264 if self.is_empty() { None } else { Some(&self.data[0]) }
267 #[deprecated="renamed to `top`"]
268 pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
270 /// Returns the number of elements the queue can hold without reallocating.
275 /// use std::collections::PriorityQueue;
277 /// let pq: PriorityQueue<uint> = PriorityQueue::with_capacity(100u);
278 /// assert!(pq.capacity() >= 100u);
280 pub fn capacity(&self) -> uint { self.data.capacity() }
282 /// Reserves capacity for exactly `n` elements in the `PriorityQueue`.
283 /// Do nothing if the capacity is already sufficient.
288 /// use std::collections::PriorityQueue;
290 /// let mut pq: PriorityQueue<uint> = PriorityQueue::new();
291 /// pq.reserve_exact(100u);
292 /// assert!(pq.capacity() == 100u);
294 pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }
296 /// Reserves capacity for at least `n` elements in the `PriorityQueue`.
297 /// Do nothing if the capacity is already sufficient.
302 /// use std::collections::PriorityQueue;
304 /// let mut pq: PriorityQueue<uint> = PriorityQueue::new();
305 /// pq.reserve(100u);
306 /// assert!(pq.capacity() >= 100u);
308 pub fn reserve(&mut self, n: uint) {
312 /// Removes the greatest item from a queue and returns it, or `None` if it
318 /// use std::collections::PriorityQueue;
320 /// let mut pq = PriorityQueue::from_vec(vec![1i, 3]);
322 /// assert_eq!(pq.pop(), Some(3i));
323 /// assert_eq!(pq.pop(), Some(1i));
324 /// assert_eq!(pq.pop(), None);
326 pub fn pop(&mut self) -> Option<T> {
327 match self.data.pop() {
330 if !self.is_empty() {
331 swap(&mut item, self.data.get_mut(0));
339 #[deprecated="renamed to `pop`"]
340 pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
342 /// Pushes an item onto the queue.
347 /// use std::collections::PriorityQueue;
349 /// let mut pq = PriorityQueue::new();
354 /// assert_eq!(pq.len(), 3);
355 /// assert_eq!(pq.top(), Some(&5i));
357 pub fn push(&mut self, item: T) {
358 self.data.push(item);
359 let new_len = self.len() - 1;
360 self.siftup(0, new_len);
363 /// Pushes an item onto a queue then pops the greatest item off the queue in
364 /// an optimized fashion.
369 /// use std::collections::PriorityQueue;
371 /// let mut pq = PriorityQueue::new();
375 /// assert_eq!(pq.push_pop(3i), 5);
376 /// assert_eq!(pq.push_pop(9i), 9);
377 /// assert_eq!(pq.len(), 2);
378 /// assert_eq!(pq.top(), Some(&3i));
380 pub fn push_pop(&mut self, mut item: T) -> T {
381 if !self.is_empty() && *self.top().unwrap() > item {
382 swap(&mut item, self.data.get_mut(0));
388 /// Pops the greatest item off a queue then pushes an item onto the queue in
389 /// an optimized fashion. The push is done regardless of whether the queue
395 /// use std::collections::PriorityQueue;
397 /// let mut pq = PriorityQueue::new();
399 /// assert_eq!(pq.replace(1i), None);
400 /// assert_eq!(pq.replace(3i), Some(1i));
401 /// assert_eq!(pq.len(), 1);
402 /// assert_eq!(pq.top(), Some(&3i));
404 pub fn replace(&mut self, mut item: T) -> Option<T> {
405 if !self.is_empty() {
406 swap(&mut item, self.data.get_mut(0));
416 #[deprecated="renamed to `into_vec`"]
417 fn to_vec(self) -> Vec<T> { self.into_vec() }
420 #[deprecated="renamed to `into_sorted_vec`"]
421 fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
423 /// Consumes the `PriorityQueue` and returns the underlying vector
424 /// in arbitrary order.
429 /// use std::collections::PriorityQueue;
431 /// let pq = PriorityQueue::from_vec(vec![1i, 2, 3, 4, 5, 6, 7]);
432 /// let vec = pq.into_vec();
434 /// // Will print in some order
435 /// for x in vec.iter() {
436 /// println!("{}", x);
439 pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
441 /// Consumes the `PriorityQueue` and returns a vector in sorted
442 /// (ascending) order.
447 /// use std::collections::PriorityQueue;
449 /// let mut pq = PriorityQueue::from_vec(vec![1i, 2, 4, 5, 7]);
453 /// let vec = pq.into_sorted_vec();
454 /// assert_eq!(vec, vec![1i, 2, 3, 4, 5, 6, 7]);
456 pub fn into_sorted_vec(self) -> Vec<T> {
458 let mut end = q.len();
461 q.data.as_mut_slice().swap(0, end);
462 q.siftdown_range(0, end)
467 // The implementations of siftup and siftdown use unsafe blocks in
468 // order to move an element out of the vector (leaving behind a
469 // zeroed element), shift along the others and move it back into the
470 // vector over the junk element. This reduces the constant factor
471 // compared to using swaps, which involves twice as many moves.
472 fn siftup(&mut self, start: uint, mut pos: uint) {
474 let new = replace(self.data.get_mut(pos), zeroed());
477 let parent = (pos - 1) >> 1;
478 if new > self.data[parent] {
479 let x = replace(self.data.get_mut(parent), zeroed());
480 ptr::write(self.data.get_mut(pos), x);
486 ptr::write(self.data.get_mut(pos), new);
490 fn siftdown_range(&mut self, mut pos: uint, end: uint) {
493 let new = replace(self.data.get_mut(pos), zeroed());
495 let mut child = 2 * pos + 1;
497 let right = child + 1;
498 if right < end && !(self.data[child] > self.data[right]) {
501 let x = replace(self.data.get_mut(child), zeroed());
502 ptr::write(self.data.get_mut(pos), x);
507 ptr::write(self.data.get_mut(pos), new);
508 self.siftup(start, pos);
512 fn siftdown(&mut self, pos: uint) {
513 let len = self.len();
514 self.siftdown_range(pos, len);
518 /// `PriorityQueue` iterator.
519 pub struct Items <'a, T> {
520 iter: slice::Items<'a, T>,
523 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
525 fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
528 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
531 impl<T: Ord> FromIterator<T> for PriorityQueue<T> {
532 fn from_iter<Iter: Iterator<T>>(iter: Iter) -> PriorityQueue<T> {
533 let mut q = PriorityQueue::new();
539 impl<T: Ord> Extendable<T> for PriorityQueue<T> {
540 fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
541 let (lower, _) = iter.size_hint();
543 let len = self.capacity();
544 self.reserve(len + lower);
556 use priority_queue::PriorityQueue;
562 let data = vec!(5i, 9, 3);
563 let iterout = [9i, 5, 3];
564 let pq = PriorityQueue::from_vec(data);
566 for el in pq.iter() {
567 assert_eq!(*el, iterout[i]);
573 fn test_top_and_pop() {
574 let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
575 let mut sorted = data.clone();
577 let mut heap = PriorityQueue::from_vec(data);
578 while !heap.is_empty() {
579 assert_eq!(heap.top().unwrap(), sorted.last().unwrap());
580 assert_eq!(heap.pop().unwrap(), sorted.pop().unwrap());
586 let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
587 assert_eq!(heap.len(), 3);
588 assert!(*heap.top().unwrap() == 9);
590 assert_eq!(heap.len(), 4);
591 assert!(*heap.top().unwrap() == 11);
593 assert_eq!(heap.len(), 5);
594 assert!(*heap.top().unwrap() == 11);
596 assert_eq!(heap.len(), 6);
597 assert!(*heap.top().unwrap() == 27);
599 assert_eq!(heap.len(), 7);
600 assert!(*heap.top().unwrap() == 27);
602 assert_eq!(heap.len(), 8);
603 assert!(*heap.top().unwrap() == 103);
607 fn test_push_unique() {
608 let mut heap = PriorityQueue::from_vec(vec!(box 2i, box 4, box 9));
609 assert_eq!(heap.len(), 3);
610 assert!(*heap.top().unwrap() == box 9);
612 assert_eq!(heap.len(), 4);
613 assert!(*heap.top().unwrap() == box 11);
615 assert_eq!(heap.len(), 5);
616 assert!(*heap.top().unwrap() == box 11);
618 assert_eq!(heap.len(), 6);
619 assert!(*heap.top().unwrap() == box 27);
621 assert_eq!(heap.len(), 7);
622 assert!(*heap.top().unwrap() == box 27);
624 assert_eq!(heap.len(), 8);
625 assert!(*heap.top().unwrap() == box 103);
630 let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
631 assert_eq!(heap.len(), 5);
632 assert_eq!(heap.push_pop(6), 6);
633 assert_eq!(heap.len(), 5);
634 assert_eq!(heap.push_pop(0), 5);
635 assert_eq!(heap.len(), 5);
636 assert_eq!(heap.push_pop(4), 5);
637 assert_eq!(heap.len(), 5);
638 assert_eq!(heap.push_pop(1), 4);
639 assert_eq!(heap.len(), 5);
644 let mut heap = PriorityQueue::from_vec(vec!(5i, 5, 2, 1, 3));
645 assert_eq!(heap.len(), 5);
646 assert_eq!(heap.replace(6).unwrap(), 5);
647 assert_eq!(heap.len(), 5);
648 assert_eq!(heap.replace(0).unwrap(), 6);
649 assert_eq!(heap.len(), 5);
650 assert_eq!(heap.replace(4).unwrap(), 5);
651 assert_eq!(heap.len(), 5);
652 assert_eq!(heap.replace(1).unwrap(), 4);
653 assert_eq!(heap.len(), 5);
656 fn check_to_vec(mut data: Vec<int>) {
657 let heap = PriorityQueue::from_vec(data.clone());
658 let mut v = heap.clone().into_vec();
662 assert_eq!(v.as_slice(), data.as_slice());
663 assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
668 check_to_vec(vec!());
669 check_to_vec(vec!(5i));
670 check_to_vec(vec!(3i, 2));
671 check_to_vec(vec!(2i, 3));
672 check_to_vec(vec!(5i, 1, 2));
673 check_to_vec(vec!(1i, 100, 2, 3));
674 check_to_vec(vec!(1i, 3, 5, 7, 9, 2, 4, 6, 8, 0));
675 check_to_vec(vec!(2i, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
676 check_to_vec(vec!(9i, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
677 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
678 check_to_vec(vec!(10i, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
679 check_to_vec(vec!(0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
680 check_to_vec(vec!(5i, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
684 fn test_empty_pop() {
685 let mut heap: PriorityQueue<int> = PriorityQueue::new();
686 assert!(heap.pop().is_none());
690 fn test_empty_top() {
691 let empty: PriorityQueue<int> = PriorityQueue::new();
692 assert!(empty.top().is_none());
696 fn test_empty_replace() {
697 let mut heap: PriorityQueue<int> = PriorityQueue::new();
698 heap.replace(5).is_none();
702 fn test_from_iter() {
703 let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
705 let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
707 for &x in xs.iter() {
708 assert_eq!(q.pop().unwrap(), x);