lemon/radix_heap.h
changeset 681 532697c9fa53
child 683 9f529abcaebf
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/radix_heap.h	Thu Jun 11 22:11:29 2009 +0200
     1.3 @@ -0,0 +1,433 @@
     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 auxdat
    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 auxdata
    1.36 +  ///
    1.37 +  /// \brief A Radix Heap implementation.
    1.38 +  ///
    1.39 +  /// This class implements the \e radix \e heap data structure. A \e heap
    1.40 +  /// is a data structure for storing items with specified values called \e
    1.41 +  /// priorities in such a way that finding the item with minimum priority is
    1.42 +  /// efficient. This heap type can store only items with \e int priority.
    1.43 +  /// In a heap one can change the priority of an item, add or erase an
    1.44 +  /// item, but the priority cannot be decreased under the last removed
    1.45 +  /// item's priority.
    1.46 +  ///
    1.47 +  /// \param _ItemIntMap A read and writable Item int map, used internally
    1.48 +  /// to handle the cross references.
    1.49 +  ///
    1.50 +  /// \see BinHeap
    1.51 +  /// \see Dijkstra
    1.52 +  template <typename _ItemIntMap>
    1.53 +  class RadixHeap {
    1.54 +
    1.55 +  public:
    1.56 +    typedef typename _ItemIntMap::Key Item;
    1.57 +    typedef int Prio;
    1.58 +    typedef _ItemIntMap ItemIntMap;
    1.59 +
    1.60 +    /// \brief Exception thrown by RadixHeap.
    1.61 +    ///
    1.62 +    /// This Exception is thrown when a smaller priority
    1.63 +    /// is inserted into the \e RadixHeap then the last time erased.
    1.64 +    /// \see RadixHeap
    1.65 +
    1.66 +    class UnderFlowPriorityError : public Exception {
    1.67 +    public:
    1.68 +      virtual const char* what() const throw() {
    1.69 +        return "lemon::RadixHeap::UnderFlowPriorityError";
    1.70 +      }
    1.71 +    };
    1.72 +
    1.73 +    /// \brief Type to represent the items states.
    1.74 +    ///
    1.75 +    /// Each Item element have a state associated to it. It may be "in heap",
    1.76 +    /// "pre heap" or "post heap". The latter two are indifferent from the
    1.77 +    /// heap's point of view, but may be useful to the user.
    1.78 +    ///
    1.79 +    /// The ItemIntMap \e should be initialized in such way that it maps
    1.80 +    /// PRE_HEAP (-1) to any element to be put in the heap...
    1.81 +    enum State {
    1.82 +      IN_HEAP = 0,
    1.83 +      PRE_HEAP = -1,
    1.84 +      POST_HEAP = -2
    1.85 +    };
    1.86 +
    1.87 +  private:
    1.88 +
    1.89 +    struct RadixItem {
    1.90 +      int prev, next, box;
    1.91 +      Item item;
    1.92 +      int prio;
    1.93 +      RadixItem(Item _item, int _prio) : item(_item), prio(_prio) {}
    1.94 +    };
    1.95 +
    1.96 +    struct RadixBox {
    1.97 +      int first;
    1.98 +      int min, size;
    1.99 +      RadixBox(int _min, int _size) : first(-1), min(_min), size(_size) {}
   1.100 +    };
   1.101 +
   1.102 +    std::vector<RadixItem> data;
   1.103 +    std::vector<RadixBox> boxes;
   1.104 +
   1.105 +    ItemIntMap &iim;
   1.106 +
   1.107 +
   1.108 +  public:
   1.109 +    /// \brief The constructor.
   1.110 +    ///
   1.111 +    /// The constructor.
   1.112 +    ///
   1.113 +    /// \param _iim It should be given to the constructor, since it is used
   1.114 +    /// internally to handle the cross references. The value of the map
   1.115 +    /// should be PRE_HEAP (-1) for each element.
   1.116 +    ///
   1.117 +    /// \param minimal The initial minimal value of the heap.
   1.118 +    /// \param capacity It determines the initial capacity of the heap.
   1.119 +    RadixHeap(ItemIntMap &_iim, int minimal = 0, int capacity = 0)
   1.120 +      : iim(_iim) {
   1.121 +      boxes.push_back(RadixBox(minimal, 1));
   1.122 +      boxes.push_back(RadixBox(minimal + 1, 1));
   1.123 +      while (lower(boxes.size() - 1, capacity + minimal - 1)) {
   1.124 +        extend();
   1.125 +      }
   1.126 +    }
   1.127 +
   1.128 +    /// The number of items stored in the heap.
   1.129 +    ///
   1.130 +    /// \brief Returns the number of items stored in the heap.
   1.131 +    int size() const { return data.size(); }
   1.132 +    /// \brief Checks if the heap stores no items.
   1.133 +    ///
   1.134 +    /// Returns \c true if and only if the heap stores no items.
   1.135 +    bool empty() const { return data.empty(); }
   1.136 +
   1.137 +    /// \brief Make empty this heap.
   1.138 +    ///
   1.139 +    /// Make empty this heap. It does not change the cross reference
   1.140 +    /// map.  If you want to reuse a heap what is not surely empty you
   1.141 +    /// should first clear the heap and after that you should set the
   1.142 +    /// cross reference map for each item to \c PRE_HEAP.
   1.143 +    void clear(int minimal = 0, int capacity = 0) {
   1.144 +      data.clear(); boxes.clear();
   1.145 +      boxes.push_back(RadixBox(minimal, 1));
   1.146 +      boxes.push_back(RadixBox(minimal + 1, 1));
   1.147 +      while (lower(boxes.size() - 1, capacity + minimal - 1)) {
   1.148 +        extend();
   1.149 +      }
   1.150 +    }
   1.151 +
   1.152 +  private:
   1.153 +
   1.154 +    bool upper(int box, Prio pr) {
   1.155 +      return pr < boxes[box].min;
   1.156 +    }
   1.157 +
   1.158 +    bool lower(int box, Prio pr) {
   1.159 +      return pr >= boxes[box].min + boxes[box].size;
   1.160 +    }
   1.161 +
   1.162 +    /// \brief Remove item from the box list.
   1.163 +    void remove(int index) {
   1.164 +      if (data[index].prev >= 0) {
   1.165 +        data[data[index].prev].next = data[index].next;
   1.166 +      } else {
   1.167 +        boxes[data[index].box].first = data[index].next;
   1.168 +      }
   1.169 +      if (data[index].next >= 0) {
   1.170 +        data[data[index].next].prev = data[index].prev;
   1.171 +      }
   1.172 +    }
   1.173 +
   1.174 +    /// \brief Insert item into the box list.
   1.175 +    void insert(int box, int index) {
   1.176 +      if (boxes[box].first == -1) {
   1.177 +        boxes[box].first = index;
   1.178 +        data[index].next = data[index].prev = -1;
   1.179 +      } else {
   1.180 +        data[index].next = boxes[box].first;
   1.181 +        data[boxes[box].first].prev = index;
   1.182 +        data[index].prev = -1;
   1.183 +        boxes[box].first = index;
   1.184 +      }
   1.185 +      data[index].box = box;
   1.186 +    }
   1.187 +
   1.188 +    /// \brief Add a new box to the box list.
   1.189 +    void extend() {
   1.190 +      int min = boxes.back().min + boxes.back().size;
   1.191 +      int bs = 2 * boxes.back().size;
   1.192 +      boxes.push_back(RadixBox(min, bs));
   1.193 +    }
   1.194 +
   1.195 +    /// \brief Move an item up into the proper box.
   1.196 +    void bubble_up(int index) {
   1.197 +      if (!lower(data[index].box, data[index].prio)) return;
   1.198 +      remove(index);
   1.199 +      int box = findUp(data[index].box, data[index].prio);
   1.200 +      insert(box, index);
   1.201 +    }
   1.202 +
   1.203 +    /// \brief Find up the proper box for the item with the given prio.
   1.204 +    int findUp(int start, int pr) {
   1.205 +      while (lower(start, pr)) {
   1.206 +        if (++start == int(boxes.size())) {
   1.207 +          extend();
   1.208 +        }
   1.209 +      }
   1.210 +      return start;
   1.211 +    }
   1.212 +
   1.213 +    /// \brief Move an item down into the proper box.
   1.214 +    void bubble_down(int index) {
   1.215 +      if (!upper(data[index].box, data[index].prio)) return;
   1.216 +      remove(index);
   1.217 +      int box = findDown(data[index].box, data[index].prio);
   1.218 +      insert(box, index);
   1.219 +    }
   1.220 +
   1.221 +    /// \brief Find up the proper box for the item with the given prio.
   1.222 +    int findDown(int start, int pr) {
   1.223 +      while (upper(start, pr)) {
   1.224 +        if (--start < 0) throw UnderFlowPriorityError();
   1.225 +      }
   1.226 +      return start;
   1.227 +    }
   1.228 +
   1.229 +    /// \brief Find the first not empty box.
   1.230 +    int findFirst() {
   1.231 +      int first = 0;
   1.232 +      while (boxes[first].first == -1) ++first;
   1.233 +      return first;
   1.234 +    }
   1.235 +
   1.236 +    /// \brief Gives back the minimal prio of the box.
   1.237 +    int minValue(int box) {
   1.238 +      int min = data[boxes[box].first].prio;
   1.239 +      for (int k = boxes[box].first; k != -1; k = data[k].next) {
   1.240 +        if (data[k].prio < min) min = data[k].prio;
   1.241 +      }
   1.242 +      return min;
   1.243 +    }
   1.244 +
   1.245 +    /// \brief Rearrange the items of the heap and makes the
   1.246 +    /// first box not 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 +        bubble_down(curr);
   1.259 +        curr = next;
   1.260 +      }
   1.261 +    }
   1.262 +
   1.263 +    void relocate_last(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 +    /// Adds \c i to the heap with priority \c p.
   1.284 +    /// \param i The item to insert.
   1.285 +    /// \param p The priority of the item.
   1.286 +    void push(const Item &i, const Prio &p) {
   1.287 +      int n = data.size();
   1.288 +      iim.set(i, n);
   1.289 +      data.push_back(RadixItem(i, p));
   1.290 +      while (lower(boxes.size() - 1, p)) {
   1.291 +        extend();
   1.292 +      }
   1.293 +      int box = findDown(boxes.size() - 1, p);
   1.294 +      insert(box, n);
   1.295 +    }
   1.296 +
   1.297 +    /// \brief Returns the item with minimum priority.
   1.298 +    ///
   1.299 +    /// This method returns the item with minimum priority.
   1.300 +    /// \pre The heap must be nonempty.
   1.301 +    Item top() const {
   1.302 +      const_cast<RadixHeap<ItemIntMap>&>(*this).moveDown();
   1.303 +      return data[boxes[0].first].item;
   1.304 +    }
   1.305 +
   1.306 +    /// \brief Returns the minimum priority.
   1.307 +    ///
   1.308 +    /// It returns the minimum priority.
   1.309 +    /// \pre The heap must be nonempty.
   1.310 +    Prio prio() const {
   1.311 +      const_cast<RadixHeap<ItemIntMap>&>(*this).moveDown();
   1.312 +      return data[boxes[0].first].prio;
   1.313 +     }
   1.314 +
   1.315 +    /// \brief Deletes the item with minimum priority.
   1.316 +    ///
   1.317 +    /// This method deletes the item with minimum priority.
   1.318 +    /// \pre The heap must be non-empty.
   1.319 +    void pop() {
   1.320 +      moveDown();
   1.321 +      int index = boxes[0].first;
   1.322 +      iim[data[index].item] = POST_HEAP;
   1.323 +      remove(index);
   1.324 +      relocate_last(index);
   1.325 +    }
   1.326 +
   1.327 +    /// \brief Deletes \c i from the heap.
   1.328 +    ///
   1.329 +    /// This method deletes item \c i from the heap, if \c i was
   1.330 +    /// already stored in the heap.
   1.331 +    /// \param i The item to erase.
   1.332 +    void erase(const Item &i) {
   1.333 +      int index = iim[i];
   1.334 +      iim[i] = POST_HEAP;
   1.335 +      remove(index);
   1.336 +      relocate_last(index);
   1.337 +   }
   1.338 +
   1.339 +    /// \brief Returns the priority of \c i.
   1.340 +    ///
   1.341 +    /// This function returns the priority of item \c i.
   1.342 +    /// \pre \c i must be in the heap.
   1.343 +    /// \param i The item.
   1.344 +    Prio operator[](const Item &i) const {
   1.345 +      int idx = iim[i];
   1.346 +      return data[idx].prio;
   1.347 +    }
   1.348 +
   1.349 +    /// \brief \c i gets to the heap with priority \c p independently
   1.350 +    /// if \c i was already there.
   1.351 +    ///
   1.352 +    /// This method calls \ref push(\c i, \c p) if \c i is not stored
   1.353 +    /// in the heap and sets the priority of \c i to \c p otherwise.
   1.354 +    /// It may throw an \e UnderFlowPriorityException.
   1.355 +    /// \param i The item.
   1.356 +    /// \param p The priority.
   1.357 +    void set(const Item &i, const Prio &p) {
   1.358 +      int idx = iim[i];
   1.359 +      if( idx < 0 ) {
   1.360 +        push(i, p);
   1.361 +      }
   1.362 +      else if( p >= data[idx].prio ) {
   1.363 +        data[idx].prio = p;
   1.364 +        bubble_up(idx);
   1.365 +      } else {
   1.366 +        data[idx].prio = p;
   1.367 +        bubble_down(idx);
   1.368 +      }
   1.369 +    }
   1.370 +
   1.371 +
   1.372 +    /// \brief Decreases the priority of \c i to \c p.
   1.373 +    ///
   1.374 +    /// This method decreases the priority of item \c i to \c p.
   1.375 +    /// \pre \c i must be stored in the heap with priority at least \c p, and
   1.376 +    /// \c should be greater or equal to the last removed item's priority.
   1.377 +    /// \param i The item.
   1.378 +    /// \param p The priority.
   1.379 +    void decrease(const Item &i, const Prio &p) {
   1.380 +      int idx = iim[i];
   1.381 +      data[idx].prio = p;
   1.382 +      bubble_down(idx);
   1.383 +    }
   1.384 +
   1.385 +    /// \brief Increases the priority of \c i to \c p.
   1.386 +    ///
   1.387 +    /// This method sets the priority of item \c i to \c p.
   1.388 +    /// \pre \c i must be stored in the heap with priority at most \c p
   1.389 +    /// \param i The item.
   1.390 +    /// \param p The priority.
   1.391 +    void increase(const Item &i, const Prio &p) {
   1.392 +      int idx = iim[i];
   1.393 +      data[idx].prio = p;
   1.394 +      bubble_up(idx);
   1.395 +    }
   1.396 +
   1.397 +    /// \brief Returns if \c item is in, has already been in, or has
   1.398 +    /// never been in the heap.
   1.399 +    ///
   1.400 +    /// This method returns PRE_HEAP if \c item has never been in the
   1.401 +    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
   1.402 +    /// otherwise. In the latter case it is possible that \c item will
   1.403 +    /// get back to the heap again.
   1.404 +    /// \param i The item.
   1.405 +    State state(const Item &i) const {
   1.406 +      int s = iim[i];
   1.407 +      if( s >= 0 ) s = 0;
   1.408 +      return State(s);
   1.409 +    }
   1.410 +
   1.411 +    /// \brief Sets the state of the \c item in the heap.
   1.412 +    ///
   1.413 +    /// Sets the state of the \c item in the heap. It can be used to
   1.414 +    /// manually clear the heap when it is important to achive the
   1.415 +    /// better time complexity.
   1.416 +    /// \param i The item.
   1.417 +    /// \param st The state. It should not be \c IN_HEAP.
   1.418 +    void state(const Item& i, State st) {
   1.419 +      switch (st) {
   1.420 +      case POST_HEAP:
   1.421 +      case PRE_HEAP:
   1.422 +        if (state(i) == IN_HEAP) {
   1.423 +          erase(i);
   1.424 +        }
   1.425 +        iim[i] = st;
   1.426 +        break;
   1.427 +      case IN_HEAP:
   1.428 +        break;
   1.429 +      }
   1.430 +    }
   1.431 +
   1.432 +  }; // class RadixHeap
   1.433 +
   1.434 +} // namespace lemon
   1.435 +
   1.436 +#endif // LEMON_RADIX_HEAP_H