1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/lemon/radix_heap.h Fri Sep 25 09:13:03 2009 +0200
1.3 @@ -0,0 +1,438 @@
1.4 +/* -*- mode: C++; indent-tabs-mode: nil; -*-
1.5 + *
1.6 + * This file is a part of LEMON, a generic C++ optimization library.
1.7 + *
1.8 + * Copyright (C) 2003-2009
1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
1.11 + *
1.12 + * Permission to use, modify and distribute this software is granted
1.13 + * provided that this copyright notice appears in all copies. For
1.14 + * precise terms see the accompanying LICENSE file.
1.15 + *
1.16 + * This software is provided "AS IS" with no warranty of any kind,
1.17 + * express or implied, and with no claim as to its suitability for any
1.18 + * purpose.
1.19 + *
1.20 + */
1.21 +
1.22 +#ifndef LEMON_RADIX_HEAP_H
1.23 +#define LEMON_RADIX_HEAP_H
1.24 +
1.25 +///\ingroup heaps
1.26 +///\file
1.27 +///\brief Radix heap implementation.
1.28 +
1.29 +#include <vector>
1.30 +#include <lemon/error.h>
1.31 +
1.32 +namespace lemon {
1.33 +
1.34 +
1.35 + /// \ingroup heaps
1.36 + ///
1.37 + /// \brief Radix heap data structure.
1.38 + ///
1.39 + /// This class implements the \e radix \e heap data structure.
1.40 + /// It practically conforms to the \ref concepts::Heap "heap concept",
1.41 + /// but it has some limitations due its special implementation.
1.42 + /// The type of the priorities must be \c int and the priority of an
1.43 + /// item cannot be decreased under the priority of the last removed item.
1.44 + ///
1.45 + /// \tparam IM A read-writable item map with \c int values, used
1.46 + /// internally to handle the cross references.
1.47 + template <typename IM>
1.48 + class RadixHeap {
1.49 +
1.50 + public:
1.51 +
1.52 + /// Type of the item-int map.
1.53 + typedef IM ItemIntMap;
1.54 + /// Type of the priorities.
1.55 + typedef int Prio;
1.56 + /// Type of the items stored in the heap.
1.57 + typedef typename ItemIntMap::Key Item;
1.58 +
1.59 + /// \brief Exception thrown by RadixHeap.
1.60 + ///
1.61 + /// This exception is thrown when an item is inserted into a
1.62 + /// RadixHeap with a priority smaller than the last erased one.
1.63 + /// \see RadixHeap
1.64 + class PriorityUnderflowError : public Exception {
1.65 + public:
1.66 + virtual const char* what() const throw() {
1.67 + return "lemon::RadixHeap::PriorityUnderflowError";
1.68 + }
1.69 + };
1.70 +
1.71 + /// \brief Type to represent the states of the items.
1.72 + ///
1.73 + /// Each item has a state associated to it. It can be "in heap",
1.74 + /// "pre-heap" or "post-heap". The latter two are indifferent from the
1.75 + /// heap's point of view, but may be useful to the user.
1.76 + ///
1.77 + /// The item-int map must be initialized in such way that it assigns
1.78 + /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
1.79 + enum State {
1.80 + IN_HEAP = 0, ///< = 0.
1.81 + PRE_HEAP = -1, ///< = -1.
1.82 + POST_HEAP = -2 ///< = -2.
1.83 + };
1.84 +
1.85 + private:
1.86 +
1.87 + struct RadixItem {
1.88 + int prev, next, box;
1.89 + Item item;
1.90 + int prio;
1.91 + RadixItem(Item _item, int _prio) : item(_item), prio(_prio) {}
1.92 + };
1.93 +
1.94 + struct RadixBox {
1.95 + int first;
1.96 + int min, size;
1.97 + RadixBox(int _min, int _size) : first(-1), min(_min), size(_size) {}
1.98 + };
1.99 +
1.100 + std::vector<RadixItem> _data;
1.101 + std::vector<RadixBox> _boxes;
1.102 +
1.103 + ItemIntMap &_iim;
1.104 +
1.105 + public:
1.106 +
1.107 + /// \brief Constructor.
1.108 + ///
1.109 + /// Constructor.
1.110 + /// \param map A map that assigns \c int values to the items.
1.111 + /// It is used internally to handle the cross references.
1.112 + /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
1.113 + /// \param minimum The initial minimum value of the heap.
1.114 + /// \param capacity The initial capacity of the heap.
1.115 + RadixHeap(ItemIntMap &map, int minimum = 0, int capacity = 0)
1.116 + : _iim(map)
1.117 + {
1.118 + _boxes.push_back(RadixBox(minimum, 1));
1.119 + _boxes.push_back(RadixBox(minimum + 1, 1));
1.120 + while (lower(_boxes.size() - 1, capacity + minimum - 1)) {
1.121 + extend();
1.122 + }
1.123 + }
1.124 +
1.125 + /// \brief The number of items stored in the heap.
1.126 + ///
1.127 + /// This function returns the number of items stored in the heap.
1.128 + int size() const { return _data.size(); }
1.129 +
1.130 + /// \brief Check if the heap is empty.
1.131 + ///
1.132 + /// This function returns \c true if the heap is empty.
1.133 + bool empty() const { return _data.empty(); }
1.134 +
1.135 + /// \brief Make the heap empty.
1.136 + ///
1.137 + /// This functon makes the heap empty.
1.138 + /// It does not change the cross reference map. If you want to reuse
1.139 + /// a heap that is not surely empty, you should first clear it and
1.140 + /// then you should set the cross reference map to \c PRE_HEAP
1.141 + /// for each item.
1.142 + /// \param minimum The minimum value of the heap.
1.143 + /// \param capacity The capacity of the heap.
1.144 + void clear(int minimum = 0, int capacity = 0) {
1.145 + _data.clear(); _boxes.clear();
1.146 + _boxes.push_back(RadixBox(minimum, 1));
1.147 + _boxes.push_back(RadixBox(minimum + 1, 1));
1.148 + while (lower(_boxes.size() - 1, capacity + minimum - 1)) {
1.149 + extend();
1.150 + }
1.151 + }
1.152 +
1.153 + private:
1.154 +
1.155 + bool upper(int box, Prio pr) {
1.156 + return pr < _boxes[box].min;
1.157 + }
1.158 +
1.159 + bool lower(int box, Prio pr) {
1.160 + return pr >= _boxes[box].min + _boxes[box].size;
1.161 + }
1.162 +
1.163 + // Remove item from the box list
1.164 + void remove(int index) {
1.165 + if (_data[index].prev >= 0) {
1.166 + _data[_data[index].prev].next = _data[index].next;
1.167 + } else {
1.168 + _boxes[_data[index].box].first = _data[index].next;
1.169 + }
1.170 + if (_data[index].next >= 0) {
1.171 + _data[_data[index].next].prev = _data[index].prev;
1.172 + }
1.173 + }
1.174 +
1.175 + // Insert item into the box list
1.176 + void insert(int box, int index) {
1.177 + if (_boxes[box].first == -1) {
1.178 + _boxes[box].first = index;
1.179 + _data[index].next = _data[index].prev = -1;
1.180 + } else {
1.181 + _data[index].next = _boxes[box].first;
1.182 + _data[_boxes[box].first].prev = index;
1.183 + _data[index].prev = -1;
1.184 + _boxes[box].first = index;
1.185 + }
1.186 + _data[index].box = box;
1.187 + }
1.188 +
1.189 + // Add a new box to the box list
1.190 + void extend() {
1.191 + int min = _boxes.back().min + _boxes.back().size;
1.192 + int bs = 2 * _boxes.back().size;
1.193 + _boxes.push_back(RadixBox(min, bs));
1.194 + }
1.195 +
1.196 + // Move an item up into the proper box.
1.197 + void bubbleUp(int index) {
1.198 + if (!lower(_data[index].box, _data[index].prio)) return;
1.199 + remove(index);
1.200 + int box = findUp(_data[index].box, _data[index].prio);
1.201 + insert(box, index);
1.202 + }
1.203 +
1.204 + // Find up the proper box for the item with the given priority
1.205 + int findUp(int start, int pr) {
1.206 + while (lower(start, pr)) {
1.207 + if (++start == int(_boxes.size())) {
1.208 + extend();
1.209 + }
1.210 + }
1.211 + return start;
1.212 + }
1.213 +
1.214 + // Move an item down into the proper box
1.215 + void bubbleDown(int index) {
1.216 + if (!upper(_data[index].box, _data[index].prio)) return;
1.217 + remove(index);
1.218 + int box = findDown(_data[index].box, _data[index].prio);
1.219 + insert(box, index);
1.220 + }
1.221 +
1.222 + // Find down the proper box for the item with the given priority
1.223 + int findDown(int start, int pr) {
1.224 + while (upper(start, pr)) {
1.225 + if (--start < 0) throw PriorityUnderflowError();
1.226 + }
1.227 + return start;
1.228 + }
1.229 +
1.230 + // Find the first non-empty box
1.231 + int findFirst() {
1.232 + int first = 0;
1.233 + while (_boxes[first].first == -1) ++first;
1.234 + return first;
1.235 + }
1.236 +
1.237 + // Gives back the minimum priority of the given box
1.238 + int minValue(int box) {
1.239 + int min = _data[_boxes[box].first].prio;
1.240 + for (int k = _boxes[box].first; k != -1; k = _data[k].next) {
1.241 + if (_data[k].prio < min) min = _data[k].prio;
1.242 + }
1.243 + return min;
1.244 + }
1.245 +
1.246 + // Rearrange the items of the heap and make the first box non-empty
1.247 + void moveDown() {
1.248 + int box = findFirst();
1.249 + if (box == 0) return;
1.250 + int min = minValue(box);
1.251 + for (int i = 0; i <= box; ++i) {
1.252 + _boxes[i].min = min;
1.253 + min += _boxes[i].size;
1.254 + }
1.255 + int curr = _boxes[box].first, next;
1.256 + while (curr != -1) {
1.257 + next = _data[curr].next;
1.258 + bubbleDown(curr);
1.259 + curr = next;
1.260 + }
1.261 + }
1.262 +
1.263 + void relocateLast(int index) {
1.264 + if (index != int(_data.size()) - 1) {
1.265 + _data[index] = _data.back();
1.266 + if (_data[index].prev != -1) {
1.267 + _data[_data[index].prev].next = index;
1.268 + } else {
1.269 + _boxes[_data[index].box].first = index;
1.270 + }
1.271 + if (_data[index].next != -1) {
1.272 + _data[_data[index].next].prev = index;
1.273 + }
1.274 + _iim[_data[index].item] = index;
1.275 + }
1.276 + _data.pop_back();
1.277 + }
1.278 +
1.279 + public:
1.280 +
1.281 + /// \brief Insert an item into the heap with the given priority.
1.282 + ///
1.283 + /// This function inserts the given item into the heap with the
1.284 + /// given priority.
1.285 + /// \param i The item to insert.
1.286 + /// \param p The priority of the item.
1.287 + /// \pre \e i must not be stored in the heap.
1.288 + /// \warning This method may throw an \c UnderFlowPriorityException.
1.289 + void push(const Item &i, const Prio &p) {
1.290 + int n = _data.size();
1.291 + _iim.set(i, n);
1.292 + _data.push_back(RadixItem(i, p));
1.293 + while (lower(_boxes.size() - 1, p)) {
1.294 + extend();
1.295 + }
1.296 + int box = findDown(_boxes.size() - 1, p);
1.297 + insert(box, n);
1.298 + }
1.299 +
1.300 + /// \brief Return the item having minimum priority.
1.301 + ///
1.302 + /// This function returns the item having minimum priority.
1.303 + /// \pre The heap must be non-empty.
1.304 + Item top() const {
1.305 + const_cast<RadixHeap<ItemIntMap>&>(*this).moveDown();
1.306 + return _data[_boxes[0].first].item;
1.307 + }
1.308 +
1.309 + /// \brief The minimum priority.
1.310 + ///
1.311 + /// This function returns the minimum priority.
1.312 + /// \pre The heap must be non-empty.
1.313 + Prio prio() const {
1.314 + const_cast<RadixHeap<ItemIntMap>&>(*this).moveDown();
1.315 + return _data[_boxes[0].first].prio;
1.316 + }
1.317 +
1.318 + /// \brief Remove the item having minimum priority.
1.319 + ///
1.320 + /// This function removes the item having minimum priority.
1.321 + /// \pre The heap must be non-empty.
1.322 + void pop() {
1.323 + moveDown();
1.324 + int index = _boxes[0].first;
1.325 + _iim[_data[index].item] = POST_HEAP;
1.326 + remove(index);
1.327 + relocateLast(index);
1.328 + }
1.329 +
1.330 + /// \brief Remove the given item from the heap.
1.331 + ///
1.332 + /// This function removes the given item from the heap if it is
1.333 + /// already stored.
1.334 + /// \param i The item to delete.
1.335 + /// \pre \e i must be in the heap.
1.336 + void erase(const Item &i) {
1.337 + int index = _iim[i];
1.338 + _iim[i] = POST_HEAP;
1.339 + remove(index);
1.340 + relocateLast(index);
1.341 + }
1.342 +
1.343 + /// \brief The priority of the given item.
1.344 + ///
1.345 + /// This function returns the priority of the given item.
1.346 + /// \param i The item.
1.347 + /// \pre \e i must be in the heap.
1.348 + Prio operator[](const Item &i) const {
1.349 + int idx = _iim[i];
1.350 + return _data[idx].prio;
1.351 + }
1.352 +
1.353 + /// \brief Set the priority of an item or insert it, if it is
1.354 + /// not stored in the heap.
1.355 + ///
1.356 + /// This method sets the priority of the given item if it is
1.357 + /// already stored in the heap. Otherwise it inserts the given
1.358 + /// item into the heap with the given priority.
1.359 + /// \param i The item.
1.360 + /// \param p The priority.
1.361 + /// \pre \e i must be in the heap.
1.362 + /// \warning This method may throw an \c UnderFlowPriorityException.
1.363 + void set(const Item &i, const Prio &p) {
1.364 + int idx = _iim[i];
1.365 + if( idx < 0 ) {
1.366 + push(i, p);
1.367 + }
1.368 + else if( p >= _data[idx].prio ) {
1.369 + _data[idx].prio = p;
1.370 + bubbleUp(idx);
1.371 + } else {
1.372 + _data[idx].prio = p;
1.373 + bubbleDown(idx);
1.374 + }
1.375 + }
1.376 +
1.377 + /// \brief Decrease the priority of an item to the given value.
1.378 + ///
1.379 + /// This function decreases the priority of an item to the given value.
1.380 + /// \param i The item.
1.381 + /// \param p The priority.
1.382 + /// \pre \e i must be stored in the heap with priority at least \e p.
1.383 + /// \warning This method may throw an \c UnderFlowPriorityException.
1.384 + void decrease(const Item &i, const Prio &p) {
1.385 + int idx = _iim[i];
1.386 + _data[idx].prio = p;
1.387 + bubbleDown(idx);
1.388 + }
1.389 +
1.390 + /// \brief Increase the priority of an item to the given value.
1.391 + ///
1.392 + /// This function increases the priority of an item to the given value.
1.393 + /// \param i The item.
1.394 + /// \param p The priority.
1.395 + /// \pre \e i must be stored in the heap with priority at most \e p.
1.396 + void increase(const Item &i, const Prio &p) {
1.397 + int idx = _iim[i];
1.398 + _data[idx].prio = p;
1.399 + bubbleUp(idx);
1.400 + }
1.401 +
1.402 + /// \brief Return the state of an item.
1.403 + ///
1.404 + /// This method returns \c PRE_HEAP if the given item has never
1.405 + /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
1.406 + /// and \c POST_HEAP otherwise.
1.407 + /// In the latter case it is possible that the item will get back
1.408 + /// to the heap again.
1.409 + /// \param i The item.
1.410 + State state(const Item &i) const {
1.411 + int s = _iim[i];
1.412 + if( s >= 0 ) s = 0;
1.413 + return State(s);
1.414 + }
1.415 +
1.416 + /// \brief Set the state of an item in the heap.
1.417 + ///
1.418 + /// This function sets the state of the given item in the heap.
1.419 + /// It can be used to manually clear the heap when it is important
1.420 + /// to achive better time complexity.
1.421 + /// \param i The item.
1.422 + /// \param st The state. It should not be \c IN_HEAP.
1.423 + void state(const Item& i, State st) {
1.424 + switch (st) {
1.425 + case POST_HEAP:
1.426 + case PRE_HEAP:
1.427 + if (state(i) == IN_HEAP) {
1.428 + erase(i);
1.429 + }
1.430 + _iim[i] = st;
1.431 + break;
1.432 + case IN_HEAP:
1.433 + break;
1.434 + }
1.435 + }
1.436 +
1.437 + }; // class RadixHeap
1.438 +
1.439 +} // namespace lemon
1.440 +
1.441 +#endif // LEMON_RADIX_HEAP_H