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 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![
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 {Collection, Mutable};
161 /// A priority queue implemented with a binary heap
163 pub struct PriorityQueue<T> {
167 impl<T: Ord> Collection for PriorityQueue<T> {
168 /// Returns the length of the queue
169 fn len(&self) -> uint { self.data.len() }
172 impl<T: Ord> Mutable for PriorityQueue<T> {
173 /// Drop all items from the queue
174 fn clear(&mut self) { self.data.truncate(0) }
177 impl<T: Ord> Default for PriorityQueue<T> {
179 fn default() -> PriorityQueue<T> { PriorityQueue::new() }
182 impl<T: Ord> PriorityQueue<T> {
183 /// An iterator visiting all values in underlying vector, in
185 pub fn iter<'a>(&'a self) -> Items<'a, T> {
186 Items { iter: self.data.iter() }
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)) }
194 #[deprecated="renamed to `top`"]
195 pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
197 /// Returns the number of elements the queue can hold without reallocating
198 pub fn capacity(&self) -> uint { self.data.capacity() }
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) }
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) {
210 /// Remove the greatest item from a queue and return it, or `None` if it is
212 pub fn pop(&mut self) -> Option<T> {
213 match self.data.pop() {
216 if !self.is_empty() {
217 swap(&mut item, self.data.get_mut(0));
225 #[deprecated="renamed to `pop`"]
226 pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
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);
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));
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));
258 #[deprecated="renamed to `into_vec`"]
259 fn to_vec(self) -> Vec<T> { self.into_vec() }
262 #[deprecated="renamed to `into_sorted_vec`"]
263 fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
265 /// Consume the PriorityQueue and return the underlying vector
266 pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
268 /// Consume the PriorityQueue and return a vector in sorted
269 /// (ascending) order
270 pub fn into_sorted_vec(self) -> Vec<T> {
272 let mut end = q.len();
275 q.data.as_mut_slice().swap(0, end);
276 q.siftdown_range(0, end)
281 /// Create an empty PriorityQueue
282 pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
284 /// Create an empty PriorityQueue with capacity `capacity`
285 pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
286 PriorityQueue { data: Vec::with_capacity(capacity) }
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;
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) {
307 let new = replace(self.data.get_mut(pos), zeroed());
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);
319 ptr::write(self.data.get_mut(pos), new);
323 fn siftdown_range(&mut self, mut pos: uint, end: uint) {
326 let new = replace(self.data.get_mut(pos), zeroed());
328 let mut child = 2 * pos + 1;
330 let right = child + 1;
331 if right < end && !(*self.data.get(child) > *self.data.get(right)) {
334 let x = replace(self.data.get_mut(child), zeroed());
335 ptr::write(self.data.get_mut(pos), x);
340 ptr::write(self.data.get_mut(pos), new);
341 self.siftup(start, pos);
345 fn siftdown(&mut self, pos: uint) {
346 let len = self.len();
347 self.siftdown_range(pos, len);
351 /// PriorityQueue iterator
352 pub struct Items <'a, T> {
353 iter: slice::Items<'a, T>,
356 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
358 fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }
361 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
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();
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();
376 let len = self.capacity();
377 self.reserve(len + lower);
389 use priority_queue::PriorityQueue;
394 let data = vec!(5i, 9, 3);
395 let iterout = [9i, 5, 3];
396 let pq = PriorityQueue::from_vec(data);
398 for el in pq.iter() {
399 assert_eq!(*el, iterout[i]);
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();
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());
418 let mut heap = PriorityQueue::from_vec(vec!(2i, 4, 9));
419 assert_eq!(heap.len(), 3);
420 assert!(*heap.top().unwrap() == 9);
422 assert_eq!(heap.len(), 4);
423 assert!(*heap.top().unwrap() == 11);
425 assert_eq!(heap.len(), 5);
426 assert!(*heap.top().unwrap() == 11);
428 assert_eq!(heap.len(), 6);
429 assert!(*heap.top().unwrap() == 27);
431 assert_eq!(heap.len(), 7);
432 assert!(*heap.top().unwrap() == 27);
434 assert_eq!(heap.len(), 8);
435 assert!(*heap.top().unwrap() == 103);
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);
444 assert_eq!(heap.len(), 4);
445 assert!(*heap.top().unwrap() == box 11);
447 assert_eq!(heap.len(), 5);
448 assert!(*heap.top().unwrap() == box 11);
450 assert_eq!(heap.len(), 6);
451 assert!(*heap.top().unwrap() == box 27);
453 assert_eq!(heap.len(), 7);
454 assert!(*heap.top().unwrap() == box 27);
456 assert_eq!(heap.len(), 8);
457 assert!(*heap.top().unwrap() == box 103);
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);
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);
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();
494 assert_eq!(v.as_slice(), data.as_slice());
495 assert_eq!(heap.into_sorted_vec().as_slice(), data.as_slice());
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));
516 fn test_empty_pop() {
517 let mut heap: PriorityQueue<int> = PriorityQueue::new();
518 assert!(heap.pop().is_none());
522 fn test_empty_top() {
523 let empty: PriorityQueue<int> = PriorityQueue::new();
524 assert!(empty.top().is_none());
528 fn test_empty_replace() {
529 let mut heap: PriorityQueue<int> = PriorityQueue::new();
530 heap.replace(5).is_none();
534 fn test_from_iter() {
535 let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);
537 let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();
539 for &x in xs.iter() {
540 assert_eq!(q.pop().unwrap(), x);