lemon/bucket_heap.h
changeset 802 994c7df296c9
parent 682 bb8c4cd57900
child 709 0747f332c478
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/bucket_heap.h	Thu Dec 10 17:05:35 2009 +0100
     1.3 @@ -0,0 +1,567 @@
     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_BUCKET_HEAP_H
    1.23 +#define LEMON_BUCKET_HEAP_H
    1.24 +
    1.25 +///\ingroup auxdat
    1.26 +///\file
    1.27 +///\brief Bucket Heap implementation.
    1.28 +
    1.29 +#include <vector>
    1.30 +#include <utility>
    1.31 +#include <functional>
    1.32 +
    1.33 +namespace lemon {
    1.34 +
    1.35 +  namespace _bucket_heap_bits {
    1.36 +
    1.37 +    template <bool MIN>
    1.38 +    struct DirectionTraits {
    1.39 +      static bool less(int left, int right) {
    1.40 +        return left < right;
    1.41 +      }
    1.42 +      static void increase(int& value) {
    1.43 +        ++value;
    1.44 +      }
    1.45 +    };
    1.46 +
    1.47 +    template <>
    1.48 +    struct DirectionTraits<false> {
    1.49 +      static bool less(int left, int right) {
    1.50 +        return left > right;
    1.51 +      }
    1.52 +      static void increase(int& value) {
    1.53 +        --value;
    1.54 +      }
    1.55 +    };
    1.56 +
    1.57 +  }
    1.58 +
    1.59 +  /// \ingroup auxdat
    1.60 +  ///
    1.61 +  /// \brief A Bucket Heap implementation.
    1.62 +  ///
    1.63 +  /// This class implements the \e bucket \e heap data structure. A \e heap
    1.64 +  /// is a data structure for storing items with specified values called \e
    1.65 +  /// priorities in such a way that finding the item with minimum priority is
    1.66 +  /// efficient. The bucket heap is very simple implementation, it can store
    1.67 +  /// only integer priorities and it stores for each priority in the
    1.68 +  /// \f$ [0..C) \f$ range a list of items. So it should be used only when
    1.69 +  /// the priorities are small. It is not intended to use as dijkstra heap.
    1.70 +  ///
    1.71 +  /// \param IM A read and write Item int map, used internally
    1.72 +  /// to handle the cross references.
    1.73 +  /// \param MIN If the given parameter is false then instead of the
    1.74 +  /// minimum value the maximum can be retrivied with the top() and
    1.75 +  /// prio() member functions.
    1.76 +  template <typename IM, bool MIN = true>
    1.77 +  class BucketHeap {
    1.78 +
    1.79 +  public:
    1.80 +    /// \e
    1.81 +    typedef typename IM::Key Item;
    1.82 +    /// \e
    1.83 +    typedef int Prio;
    1.84 +    /// \e
    1.85 +    typedef std::pair<Item, Prio> Pair;
    1.86 +    /// \e
    1.87 +    typedef IM ItemIntMap;
    1.88 +
    1.89 +  private:
    1.90 +
    1.91 +    typedef _bucket_heap_bits::DirectionTraits<MIN> Direction;
    1.92 +
    1.93 +  public:
    1.94 +
    1.95 +    /// \brief Type to represent the items states.
    1.96 +    ///
    1.97 +    /// Each Item element have a state associated to it. It may be "in heap",
    1.98 +    /// "pre heap" or "post heap". The latter two are indifferent from the
    1.99 +    /// heap's point of view, but may be useful to the user.
   1.100 +    ///
   1.101 +    /// The item-int map must be initialized in such way that it assigns
   1.102 +    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
   1.103 +    enum State {
   1.104 +      IN_HEAP = 0,    ///< = 0.
   1.105 +      PRE_HEAP = -1,  ///< = -1.
   1.106 +      POST_HEAP = -2  ///< = -2.
   1.107 +    };
   1.108 +
   1.109 +  public:
   1.110 +    /// \brief The constructor.
   1.111 +    ///
   1.112 +    /// The constructor.
   1.113 +    /// \param map 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 +    explicit BucketHeap(ItemIntMap &map) : _iim(map), _minimum(0) {}
   1.117 +
   1.118 +    /// The number of items stored in the heap.
   1.119 +    ///
   1.120 +    /// \brief Returns the number of items stored in the heap.
   1.121 +    int size() const { return _data.size(); }
   1.122 +
   1.123 +    /// \brief Checks if the heap stores no items.
   1.124 +    ///
   1.125 +    /// Returns \c true if and only if the heap stores no items.
   1.126 +    bool empty() const { return _data.empty(); }
   1.127 +
   1.128 +    /// \brief Make empty this heap.
   1.129 +    ///
   1.130 +    /// Make empty this heap. It does not change the cross reference
   1.131 +    /// map.  If you want to reuse a heap what is not surely empty you
   1.132 +    /// should first clear the heap and after that you should set the
   1.133 +    /// cross reference map for each item to \c PRE_HEAP.
   1.134 +    void clear() {
   1.135 +      _data.clear(); _first.clear(); _minimum = 0;
   1.136 +    }
   1.137 +
   1.138 +  private:
   1.139 +
   1.140 +    void relocate_last(int idx) {
   1.141 +      if (idx + 1 < int(_data.size())) {
   1.142 +        _data[idx] = _data.back();
   1.143 +        if (_data[idx].prev != -1) {
   1.144 +          _data[_data[idx].prev].next = idx;
   1.145 +        } else {
   1.146 +          _first[_data[idx].value] = idx;
   1.147 +        }
   1.148 +        if (_data[idx].next != -1) {
   1.149 +          _data[_data[idx].next].prev = idx;
   1.150 +        }
   1.151 +        _iim[_data[idx].item] = idx;
   1.152 +      }
   1.153 +      _data.pop_back();
   1.154 +    }
   1.155 +
   1.156 +    void unlace(int idx) {
   1.157 +      if (_data[idx].prev != -1) {
   1.158 +        _data[_data[idx].prev].next = _data[idx].next;
   1.159 +      } else {
   1.160 +        _first[_data[idx].value] = _data[idx].next;
   1.161 +      }
   1.162 +      if (_data[idx].next != -1) {
   1.163 +        _data[_data[idx].next].prev = _data[idx].prev;
   1.164 +      }
   1.165 +    }
   1.166 +
   1.167 +    void lace(int idx) {
   1.168 +      if (int(_first.size()) <= _data[idx].value) {
   1.169 +        _first.resize(_data[idx].value + 1, -1);
   1.170 +      }
   1.171 +      _data[idx].next = _first[_data[idx].value];
   1.172 +      if (_data[idx].next != -1) {
   1.173 +        _data[_data[idx].next].prev = idx;
   1.174 +      }
   1.175 +      _first[_data[idx].value] = idx;
   1.176 +      _data[idx].prev = -1;
   1.177 +    }
   1.178 +
   1.179 +  public:
   1.180 +    /// \brief Insert a pair of item and priority into the heap.
   1.181 +    ///
   1.182 +    /// Adds \c p.first to the heap with priority \c p.second.
   1.183 +    /// \param p The pair to insert.
   1.184 +    void push(const Pair& p) {
   1.185 +      push(p.first, p.second);
   1.186 +    }
   1.187 +
   1.188 +    /// \brief Insert an item into the heap with the given priority.
   1.189 +    ///
   1.190 +    /// Adds \c i to the heap with priority \c p.
   1.191 +    /// \param i The item to insert.
   1.192 +    /// \param p The priority of the item.
   1.193 +    void push(const Item &i, const Prio &p) {
   1.194 +      int idx = _data.size();
   1.195 +      _iim[i] = idx;
   1.196 +      _data.push_back(BucketItem(i, p));
   1.197 +      lace(idx);
   1.198 +      if (Direction::less(p, _minimum)) {
   1.199 +        _minimum = p;
   1.200 +      }
   1.201 +    }
   1.202 +
   1.203 +    /// \brief Returns the item with minimum priority.
   1.204 +    ///
   1.205 +    /// This method returns the item with minimum priority.
   1.206 +    /// \pre The heap must be nonempty.
   1.207 +    Item top() const {
   1.208 +      while (_first[_minimum] == -1) {
   1.209 +        Direction::increase(_minimum);
   1.210 +      }
   1.211 +      return _data[_first[_minimum]].item;
   1.212 +    }
   1.213 +
   1.214 +    /// \brief Returns the minimum priority.
   1.215 +    ///
   1.216 +    /// It returns the minimum priority.
   1.217 +    /// \pre The heap must be nonempty.
   1.218 +    Prio prio() const {
   1.219 +      while (_first[_minimum] == -1) {
   1.220 +        Direction::increase(_minimum);
   1.221 +      }
   1.222 +      return _minimum;
   1.223 +    }
   1.224 +
   1.225 +    /// \brief Deletes the item with minimum priority.
   1.226 +    ///
   1.227 +    /// This method deletes the item with minimum priority from the heap.
   1.228 +    /// \pre The heap must be non-empty.
   1.229 +    void pop() {
   1.230 +      while (_first[_minimum] == -1) {
   1.231 +        Direction::increase(_minimum);
   1.232 +      }
   1.233 +      int idx = _first[_minimum];
   1.234 +      _iim[_data[idx].item] = -2;
   1.235 +      unlace(idx);
   1.236 +      relocate_last(idx);
   1.237 +    }
   1.238 +
   1.239 +    /// \brief Deletes \c i from the heap.
   1.240 +    ///
   1.241 +    /// This method deletes item \c i from the heap, if \c i was
   1.242 +    /// already stored in the heap.
   1.243 +    /// \param i The item to erase.
   1.244 +    void erase(const Item &i) {
   1.245 +      int idx = _iim[i];
   1.246 +      _iim[_data[idx].item] = -2;
   1.247 +      unlace(idx);
   1.248 +      relocate_last(idx);
   1.249 +    }
   1.250 +
   1.251 +
   1.252 +    /// \brief Returns the priority of \c i.
   1.253 +    ///
   1.254 +    /// This function returns the priority of item \c i.
   1.255 +    /// \pre \c i must be in the heap.
   1.256 +    /// \param i The item.
   1.257 +    Prio operator[](const Item &i) const {
   1.258 +      int idx = _iim[i];
   1.259 +      return _data[idx].value;
   1.260 +    }
   1.261 +
   1.262 +    /// \brief \c i gets to the heap with priority \c p independently
   1.263 +    /// if \c i was already there.
   1.264 +    ///
   1.265 +    /// This method calls \ref push(\c i, \c p) if \c i is not stored
   1.266 +    /// in the heap and sets the priority of \c i to \c p otherwise.
   1.267 +    /// \param i The item.
   1.268 +    /// \param p The priority.
   1.269 +    void set(const Item &i, const Prio &p) {
   1.270 +      int idx = _iim[i];
   1.271 +      if (idx < 0) {
   1.272 +        push(i, p);
   1.273 +      } else if (Direction::less(p, _data[idx].value)) {
   1.274 +        decrease(i, p);
   1.275 +      } else {
   1.276 +        increase(i, p);
   1.277 +      }
   1.278 +    }
   1.279 +
   1.280 +    /// \brief Decreases the priority of \c i to \c p.
   1.281 +    ///
   1.282 +    /// This method decreases the priority of item \c i to \c p.
   1.283 +    /// \pre \c i must be stored in the heap with priority at least \c
   1.284 +    /// p relative to \c Compare.
   1.285 +    /// \param i The item.
   1.286 +    /// \param p The priority.
   1.287 +    void decrease(const Item &i, const Prio &p) {
   1.288 +      int idx = _iim[i];
   1.289 +      unlace(idx);
   1.290 +      _data[idx].value = p;
   1.291 +      if (Direction::less(p, _minimum)) {
   1.292 +        _minimum = p;
   1.293 +      }
   1.294 +      lace(idx);
   1.295 +    }
   1.296 +
   1.297 +    /// \brief Increases the priority of \c i to \c p.
   1.298 +    ///
   1.299 +    /// This method sets the priority of item \c i to \c p.
   1.300 +    /// \pre \c i must be stored in the heap with priority at most \c
   1.301 +    /// p relative to \c Compare.
   1.302 +    /// \param i The item.
   1.303 +    /// \param p The priority.
   1.304 +    void increase(const Item &i, const Prio &p) {
   1.305 +      int idx = _iim[i];
   1.306 +      unlace(idx);
   1.307 +      _data[idx].value = p;
   1.308 +      lace(idx);
   1.309 +    }
   1.310 +
   1.311 +    /// \brief Returns if \c item is in, has already been in, or has
   1.312 +    /// never been in the heap.
   1.313 +    ///
   1.314 +    /// This method returns PRE_HEAP if \c item has never been in the
   1.315 +    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
   1.316 +    /// otherwise. In the latter case it is possible that \c item will
   1.317 +    /// get back to the heap again.
   1.318 +    /// \param i The item.
   1.319 +    State state(const Item &i) const {
   1.320 +      int idx = _iim[i];
   1.321 +      if (idx >= 0) idx = 0;
   1.322 +      return State(idx);
   1.323 +    }
   1.324 +
   1.325 +    /// \brief Sets the state of the \c item in the heap.
   1.326 +    ///
   1.327 +    /// Sets the state of the \c item in the heap. It can be used to
   1.328 +    /// manually clear the heap when it is important to achive the
   1.329 +    /// better time complexity.
   1.330 +    /// \param i The item.
   1.331 +    /// \param st The state. It should not be \c IN_HEAP.
   1.332 +    void state(const Item& i, State st) {
   1.333 +      switch (st) {
   1.334 +      case POST_HEAP:
   1.335 +      case PRE_HEAP:
   1.336 +        if (state(i) == IN_HEAP) {
   1.337 +          erase(i);
   1.338 +        }
   1.339 +        _iim[i] = st;
   1.340 +        break;
   1.341 +      case IN_HEAP:
   1.342 +        break;
   1.343 +      }
   1.344 +    }
   1.345 +
   1.346 +  private:
   1.347 +
   1.348 +    struct BucketItem {
   1.349 +      BucketItem(const Item& _item, int _value)
   1.350 +        : item(_item), value(_value) {}
   1.351 +
   1.352 +      Item item;
   1.353 +      int value;
   1.354 +
   1.355 +      int prev, next;
   1.356 +    };
   1.357 +
   1.358 +    ItemIntMap& _iim;
   1.359 +    std::vector<int> _first;
   1.360 +    std::vector<BucketItem> _data;
   1.361 +    mutable int _minimum;
   1.362 +
   1.363 +  }; // class BucketHeap
   1.364 +
   1.365 +  /// \ingroup auxdat
   1.366 +  ///
   1.367 +  /// \brief A Simplified Bucket Heap implementation.
   1.368 +  ///
   1.369 +  /// This class implements a simplified \e bucket \e heap data
   1.370 +  /// structure.  It does not provide some functionality but it faster
   1.371 +  /// and simplier data structure than the BucketHeap. The main
   1.372 +  /// difference is that the BucketHeap stores for every key a double
   1.373 +  /// linked list while this class stores just simple lists. In the
   1.374 +  /// other way it does not support erasing each elements just the
   1.375 +  /// minimal and it does not supports key increasing, decreasing.
   1.376 +  ///
   1.377 +  /// \param IM A read and write Item int map, used internally
   1.378 +  /// to handle the cross references.
   1.379 +  /// \param MIN If the given parameter is false then instead of the
   1.380 +  /// minimum value the maximum can be retrivied with the top() and
   1.381 +  /// prio() member functions.
   1.382 +  ///
   1.383 +  /// \sa BucketHeap
   1.384 +  template <typename IM, bool MIN = true >
   1.385 +  class SimpleBucketHeap {
   1.386 +
   1.387 +  public:
   1.388 +    typedef typename IM::Key Item;
   1.389 +    typedef int Prio;
   1.390 +    typedef std::pair<Item, Prio> Pair;
   1.391 +    typedef IM ItemIntMap;
   1.392 +
   1.393 +  private:
   1.394 +
   1.395 +    typedef _bucket_heap_bits::DirectionTraits<MIN> Direction;
   1.396 +
   1.397 +  public:
   1.398 +
   1.399 +    /// \brief Type to represent the items states.
   1.400 +    ///
   1.401 +    /// Each Item element have a state associated to it. It may be "in heap",
   1.402 +    /// "pre heap" or "post heap". The latter two are indifferent from the
   1.403 +    /// heap's point of view, but may be useful to the user.
   1.404 +    ///
   1.405 +    /// The item-int map must be initialized in such way that it assigns
   1.406 +    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
   1.407 +    enum State {
   1.408 +      IN_HEAP = 0,    ///< = 0.
   1.409 +      PRE_HEAP = -1,  ///< = -1.
   1.410 +      POST_HEAP = -2  ///< = -2.
   1.411 +    };
   1.412 +
   1.413 +  public:
   1.414 +
   1.415 +    /// \brief The constructor.
   1.416 +    ///
   1.417 +    /// The constructor.
   1.418 +    /// \param map should be given to the constructor, since it is used
   1.419 +    /// internally to handle the cross references. The value of the map
   1.420 +    /// should be PRE_HEAP (-1) for each element.
   1.421 +    explicit SimpleBucketHeap(ItemIntMap &map)
   1.422 +      : _iim(map), _free(-1), _num(0), _minimum(0) {}
   1.423 +
   1.424 +    /// \brief Returns the number of items stored in the heap.
   1.425 +    ///
   1.426 +    /// The number of items stored in the heap.
   1.427 +    int size() const { return _num; }
   1.428 +
   1.429 +    /// \brief Checks if the heap stores no items.
   1.430 +    ///
   1.431 +    /// Returns \c true if and only if the heap stores no items.
   1.432 +    bool empty() const { return _num == 0; }
   1.433 +
   1.434 +    /// \brief Make empty this heap.
   1.435 +    ///
   1.436 +    /// Make empty this heap. It does not change the cross reference
   1.437 +    /// map.  If you want to reuse a heap what is not surely empty you
   1.438 +    /// should first clear the heap and after that you should set the
   1.439 +    /// cross reference map for each item to \c PRE_HEAP.
   1.440 +    void clear() {
   1.441 +      _data.clear(); _first.clear(); _free = -1; _num = 0; _minimum = 0;
   1.442 +    }
   1.443 +
   1.444 +    /// \brief Insert a pair of item and priority into the heap.
   1.445 +    ///
   1.446 +    /// Adds \c p.first to the heap with priority \c p.second.
   1.447 +    /// \param p The pair to insert.
   1.448 +    void push(const Pair& p) {
   1.449 +      push(p.first, p.second);
   1.450 +    }
   1.451 +
   1.452 +    /// \brief Insert an item into the heap with the given priority.
   1.453 +    ///
   1.454 +    /// Adds \c i to the heap with priority \c p.
   1.455 +    /// \param i The item to insert.
   1.456 +    /// \param p The priority of the item.
   1.457 +    void push(const Item &i, const Prio &p) {
   1.458 +      int idx;
   1.459 +      if (_free == -1) {
   1.460 +        idx = _data.size();
   1.461 +        _data.push_back(BucketItem(i));
   1.462 +      } else {
   1.463 +        idx = _free;
   1.464 +        _free = _data[idx].next;
   1.465 +        _data[idx].item = i;
   1.466 +      }
   1.467 +      _iim[i] = idx;
   1.468 +      if (p >= int(_first.size())) _first.resize(p + 1, -1);
   1.469 +      _data[idx].next = _first[p];
   1.470 +      _first[p] = idx;
   1.471 +      if (Direction::less(p, _minimum)) {
   1.472 +        _minimum = p;
   1.473 +      }
   1.474 +      ++_num;
   1.475 +    }
   1.476 +
   1.477 +    /// \brief Returns the item with minimum priority.
   1.478 +    ///
   1.479 +    /// This method returns the item with minimum priority.
   1.480 +    /// \pre The heap must be nonempty.
   1.481 +    Item top() const {
   1.482 +      while (_first[_minimum] == -1) {
   1.483 +        Direction::increase(_minimum);
   1.484 +      }
   1.485 +      return _data[_first[_minimum]].item;
   1.486 +    }
   1.487 +
   1.488 +    /// \brief Returns the minimum priority.
   1.489 +    ///
   1.490 +    /// It returns the minimum priority.
   1.491 +    /// \pre The heap must be nonempty.
   1.492 +    Prio prio() const {
   1.493 +      while (_first[_minimum] == -1) {
   1.494 +        Direction::increase(_minimum);
   1.495 +      }
   1.496 +      return _minimum;
   1.497 +    }
   1.498 +
   1.499 +    /// \brief Deletes the item with minimum priority.
   1.500 +    ///
   1.501 +    /// This method deletes the item with minimum priority from the heap.
   1.502 +    /// \pre The heap must be non-empty.
   1.503 +    void pop() {
   1.504 +      while (_first[_minimum] == -1) {
   1.505 +        Direction::increase(_minimum);
   1.506 +      }
   1.507 +      int idx = _first[_minimum];
   1.508 +      _iim[_data[idx].item] = -2;
   1.509 +      _first[_minimum] = _data[idx].next;
   1.510 +      _data[idx].next = _free;
   1.511 +      _free = idx;
   1.512 +      --_num;
   1.513 +    }
   1.514 +
   1.515 +    /// \brief Returns the priority of \c i.
   1.516 +    ///
   1.517 +    /// This function returns the priority of item \c i.
   1.518 +    /// \warning This operator is not a constant time function
   1.519 +    /// because it scans the whole data structure to find the proper
   1.520 +    /// value.
   1.521 +    /// \pre \c i must be in the heap.
   1.522 +    /// \param i The item.
   1.523 +    Prio operator[](const Item &i) const {
   1.524 +      for (int k = 0; k < _first.size(); ++k) {
   1.525 +        int idx = _first[k];
   1.526 +        while (idx != -1) {
   1.527 +          if (_data[idx].item == i) {
   1.528 +            return k;
   1.529 +          }
   1.530 +          idx = _data[idx].next;
   1.531 +        }
   1.532 +      }
   1.533 +      return -1;
   1.534 +    }
   1.535 +
   1.536 +    /// \brief Returns if \c item is in, has already been in, or has
   1.537 +    /// never been in the heap.
   1.538 +    ///
   1.539 +    /// This method returns PRE_HEAP if \c item has never been in the
   1.540 +    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
   1.541 +    /// otherwise. In the latter case it is possible that \c item will
   1.542 +    /// get back to the heap again.
   1.543 +    /// \param i The item.
   1.544 +    State state(const Item &i) const {
   1.545 +      int idx = _iim[i];
   1.546 +      if (idx >= 0) idx = 0;
   1.547 +      return State(idx);
   1.548 +    }
   1.549 +
   1.550 +  private:
   1.551 +
   1.552 +    struct BucketItem {
   1.553 +      BucketItem(const Item& _item)
   1.554 +        : item(_item) {}
   1.555 +
   1.556 +      Item item;
   1.557 +      int next;
   1.558 +    };
   1.559 +
   1.560 +    ItemIntMap& _iim;
   1.561 +    std::vector<int> _first;
   1.562 +    std::vector<BucketItem> _data;
   1.563 +    int _free, _num;
   1.564 +    mutable int _minimum;
   1.565 +
   1.566 +  }; // class SimpleBucketHeap
   1.567 +
   1.568 +}
   1.569 +
   1.570 +#endif