lemon/dheap.h
author Alpar Juttner <alpar@cs.elte.hu>
Tue, 28 Apr 2015 18:07:07 +0200
changeset 1340 f70f688d9ef9
parent 753 9314d9339475
permissions -rw-r--r--
Replace #define WIN32 (#595)
kpeter@750
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@748
     2
 *
kpeter@750
     3
 * This file is a part of LEMON, a generic C++ optimization library.
kpeter@748
     4
 *
kpeter@750
     5
 * Copyright (C) 2003-2009
kpeter@748
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@748
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@748
     8
 *
kpeter@748
     9
 * Permission to use, modify and distribute this software is granted
kpeter@748
    10
 * provided that this copyright notice appears in all copies. For
kpeter@748
    11
 * precise terms see the accompanying LICENSE file.
kpeter@748
    12
 *
kpeter@748
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@748
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@748
    15
 * purpose.
kpeter@748
    16
 *
kpeter@748
    17
 */
kpeter@748
    18
kpeter@929
    19
#ifndef LEMON_DHEAP_H
kpeter@929
    20
#define LEMON_DHEAP_H
kpeter@748
    21
kpeter@750
    22
///\ingroup heaps
kpeter@748
    23
///\file
kpeter@929
    24
///\brief D-ary heap implementation.
kpeter@748
    25
kpeter@748
    26
#include <vector>
kpeter@748
    27
#include <utility>
kpeter@748
    28
#include <functional>
kpeter@748
    29
kpeter@748
    30
namespace lemon {
kpeter@748
    31
kpeter@750
    32
  /// \ingroup heaps
kpeter@748
    33
  ///
kpeter@929
    34
  ///\brief D-ary heap data structure.
kpeter@748
    35
  ///
kpeter@929
    36
  /// This class implements the \e D-ary \e heap data structure.
kpeter@750
    37
  /// It fully conforms to the \ref concepts::Heap "heap concept".
kpeter@748
    38
  ///
kpeter@929
    39
  /// The \ref DHeap "D-ary heap" is a generalization of the
kpeter@750
    40
  /// \ref BinHeap "binary heap" structure, its nodes have at most
kpeter@929
    41
  /// \c D children, instead of two.
kpeter@929
    42
  /// \ref BinHeap and \ref QuadHeap are specialized implementations
kpeter@929
    43
  /// of this structure for <tt>D=2</tt> and <tt>D=4</tt>, respectively.
kpeter@748
    44
  ///
kpeter@750
    45
  /// \tparam PR Type of the priorities of the items.
kpeter@750
    46
  /// \tparam IM A read-writable item map with \c int values, used
kpeter@750
    47
  /// internally to handle the cross references.
kpeter@929
    48
  /// \tparam D The degree of the heap, each node have at most \e D
kpeter@751
    49
  /// children. The default is 16. Powers of two are suggested to use
kpeter@751
    50
  /// so that the multiplications and divisions needed to traverse the
kpeter@751
    51
  /// nodes of the heap could be performed faster.
kpeter@750
    52
  /// \tparam CMP A functor class for comparing the priorities.
kpeter@750
    53
  /// The default is \c std::less<PR>.
kpeter@750
    54
  ///
kpeter@750
    55
  ///\sa BinHeap
kpeter@750
    56
  ///\sa FouraryHeap
kpeter@750
    57
#ifdef DOXYGEN
kpeter@929
    58
  template <typename PR, typename IM, int D, typename CMP>
kpeter@750
    59
#else
kpeter@929
    60
  template <typename PR, typename IM, int D = 16,
kpeter@751
    61
            typename CMP = std::less<PR> >
kpeter@750
    62
#endif
kpeter@929
    63
  class DHeap {
kpeter@750
    64
  public:
kpeter@750
    65
    /// Type of the item-int map.
kpeter@750
    66
    typedef IM ItemIntMap;
kpeter@750
    67
    /// Type of the priorities.
kpeter@750
    68
    typedef PR Prio;
kpeter@750
    69
    /// Type of the items stored in the heap.
kpeter@750
    70
    typedef typename ItemIntMap::Key Item;
kpeter@750
    71
    /// Type of the item-priority pairs.
kpeter@750
    72
    typedef std::pair<Item,Prio> Pair;
kpeter@750
    73
    /// Functor type for comparing the priorities.
kpeter@750
    74
    typedef CMP Compare;
kpeter@748
    75
kpeter@750
    76
    /// \brief Type to represent the states of the items.
kpeter@748
    77
    ///
kpeter@750
    78
    /// Each item has a state associated to it. It can be "in heap",
kpeter@750
    79
    /// "pre-heap" or "post-heap". The latter two are indifferent from the
kpeter@748
    80
    /// heap's point of view, but may be useful to the user.
kpeter@748
    81
    ///
kpeter@750
    82
    /// The item-int map must be initialized in such way that it assigns
kpeter@750
    83
    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
kpeter@748
    84
    enum State {
kpeter@750
    85
      IN_HEAP = 0,    ///< = 0.
kpeter@750
    86
      PRE_HEAP = -1,  ///< = -1.
kpeter@750
    87
      POST_HEAP = -2  ///< = -2.
kpeter@748
    88
    };
kpeter@748
    89
kpeter@748
    90
  private:
kpeter@750
    91
    std::vector<Pair> _data;
kpeter@750
    92
    Compare _comp;
kpeter@750
    93
    ItemIntMap &_iim;
kpeter@748
    94
kpeter@748
    95
  public:
kpeter@750
    96
    /// \brief Constructor.
kpeter@748
    97
    ///
kpeter@750
    98
    /// Constructor.
kpeter@750
    99
    /// \param map A map that assigns \c int values to the items.
kpeter@750
   100
    /// It is used internally to handle the cross references.
kpeter@750
   101
    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
kpeter@929
   102
    explicit DHeap(ItemIntMap &map) : _iim(map) {}
kpeter@748
   103
kpeter@750
   104
    /// \brief Constructor.
kpeter@748
   105
    ///
kpeter@750
   106
    /// Constructor.
kpeter@750
   107
    /// \param map A map that assigns \c int values to the items.
kpeter@750
   108
    /// It is used internally to handle the cross references.
kpeter@750
   109
    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
kpeter@750
   110
    /// \param comp The function object used for comparing the priorities.
kpeter@929
   111
    DHeap(ItemIntMap &map, const Compare &comp)
kpeter@751
   112
      : _iim(map), _comp(comp) {}
kpeter@750
   113
kpeter@750
   114
    /// \brief The number of items stored in the heap.
kpeter@748
   115
    ///
kpeter@750
   116
    /// This function returns the number of items stored in the heap.
kpeter@750
   117
    int size() const { return _data.size(); }
kpeter@748
   118
kpeter@750
   119
    /// \brief Check if the heap is empty.
kpeter@750
   120
    ///
kpeter@750
   121
    /// This function returns \c true if the heap is empty.
kpeter@750
   122
    bool empty() const { return _data.empty(); }
kpeter@748
   123
kpeter@750
   124
    /// \brief Make the heap empty.
kpeter@748
   125
    ///
kpeter@750
   126
    /// This functon makes the heap empty.
kpeter@750
   127
    /// It does not change the cross reference map. If you want to reuse
kpeter@750
   128
    /// a heap that is not surely empty, you should first clear it and
kpeter@750
   129
    /// then you should set the cross reference map to \c PRE_HEAP
kpeter@750
   130
    /// for each item.
kpeter@750
   131
    void clear() { _data.clear(); }
kpeter@748
   132
kpeter@748
   133
  private:
kpeter@929
   134
    int parent(int i) { return (i-1)/D; }
kpeter@929
   135
    int firstChild(int i) { return D*i+1; }
kpeter@748
   136
kpeter@748
   137
    bool less(const Pair &p1, const Pair &p2) const {
kpeter@750
   138
      return _comp(p1.second, p2.second);
kpeter@748
   139
    }
kpeter@748
   140
kpeter@750
   141
    void bubbleUp(int hole, Pair p) {
kpeter@748
   142
      int par = parent(hole);
kpeter@750
   143
      while( hole>0 && less(p,_data[par]) ) {
kpeter@750
   144
        move(_data[par],hole);
kpeter@748
   145
        hole = par;
kpeter@748
   146
        par = parent(hole);
kpeter@748
   147
      }
kpeter@748
   148
      move(p, hole);
kpeter@748
   149
    }
kpeter@748
   150
kpeter@750
   151
    void bubbleDown(int hole, Pair p, int length) {
kpeter@748
   152
      if( length>1 ) {
kpeter@750
   153
        int child = firstChild(hole);
kpeter@929
   154
        while( child+D<=length ) {
kpeter@753
   155
          int min=child;
kpeter@929
   156
          for (int i=1; i<D; ++i) {
kpeter@753
   157
            if( less(_data[child+i], _data[min]) )
kpeter@753
   158
              min=child+i;
kpeter@753
   159
          }
kpeter@753
   160
          if( !less(_data[min], p) )
kpeter@748
   161
            goto ok;
kpeter@753
   162
          move(_data[min], hole);
kpeter@753
   163
          hole = min;
kpeter@750
   164
          child = firstChild(hole);
kpeter@748
   165
        }
kpeter@753
   166
        if ( child<length ) {
kpeter@753
   167
          int min = child;
kpeter@753
   168
          while (++child < length) {
kpeter@753
   169
            if( less(_data[child], _data[min]) )
kpeter@753
   170
              min=child;
kpeter@753
   171
          }
kpeter@753
   172
          if( less(_data[min], p) ) {
kpeter@753
   173
            move(_data[min], hole);
kpeter@753
   174
            hole = min;
kpeter@753
   175
          }
kpeter@753
   176
        }
kpeter@748
   177
      }
kpeter@748
   178
    ok:
kpeter@748
   179
      move(p, hole);
kpeter@748
   180
    }
kpeter@748
   181
kpeter@748
   182
    void move(const Pair &p, int i) {
kpeter@750
   183
      _data[i] = p;
kpeter@750
   184
      _iim.set(p.first, i);
kpeter@748
   185
    }
kpeter@748
   186
kpeter@748
   187
  public:
kpeter@748
   188
    /// \brief Insert a pair of item and priority into the heap.
kpeter@748
   189
    ///
kpeter@750
   190
    /// This function inserts \c p.first to the heap with priority
kpeter@750
   191
    /// \c p.second.
kpeter@748
   192
    /// \param p The pair to insert.
kpeter@750
   193
    /// \pre \c p.first must not be stored in the heap.
kpeter@748
   194
    void push(const Pair &p) {
kpeter@750
   195
      int n = _data.size();
kpeter@750
   196
      _data.resize(n+1);
kpeter@750
   197
      bubbleUp(n, p);
kpeter@748
   198
    }
kpeter@748
   199
kpeter@750
   200
    /// \brief Insert an item into the heap with the given priority.
kpeter@748
   201
    ///
kpeter@750
   202
    /// This function inserts the given item into the heap with the
kpeter@750
   203
    /// given priority.
kpeter@748
   204
    /// \param i The item to insert.
kpeter@748
   205
    /// \param p The priority of the item.
kpeter@750
   206
    /// \pre \e i must not be stored in the heap.
kpeter@748
   207
    void push(const Item &i, const Prio &p) { push(Pair(i,p)); }
kpeter@748
   208
kpeter@750
   209
    /// \brief Return the item having minimum priority.
kpeter@748
   210
    ///
kpeter@750
   211
    /// This function returns the item having minimum priority.
kpeter@750
   212
    /// \pre The heap must be non-empty.
kpeter@750
   213
    Item top() const { return _data[0].first; }
kpeter@748
   214
kpeter@750
   215
    /// \brief The minimum priority.
kpeter@748
   216
    ///
kpeter@750
   217
    /// This function returns the minimum priority.
kpeter@750
   218
    /// \pre The heap must be non-empty.
kpeter@750
   219
    Prio prio() const { return _data[0].second; }
kpeter@748
   220
kpeter@750
   221
    /// \brief Remove the item having minimum priority.
kpeter@748
   222
    ///
kpeter@750
   223
    /// This function removes the item having minimum priority.
kpeter@748
   224
    /// \pre The heap must be non-empty.
kpeter@748
   225
    void pop() {
kpeter@750
   226
      int n = _data.size()-1;
kpeter@750
   227
      _iim.set(_data[0].first, POST_HEAP);
kpeter@750
   228
      if (n>0) bubbleDown(0, _data[n], n);
kpeter@750
   229
      _data.pop_back();
kpeter@748
   230
    }
kpeter@748
   231
kpeter@750
   232
    /// \brief Remove the given item from the heap.
kpeter@748
   233
    ///
kpeter@750
   234
    /// This function removes the given item from the heap if it is
kpeter@750
   235
    /// already stored.
kpeter@750
   236
    /// \param i The item to delete.
kpeter@750
   237
    /// \pre \e i must be in the heap.
kpeter@748
   238
    void erase(const Item &i) {
kpeter@750
   239
      int h = _iim[i];
kpeter@750
   240
      int n = _data.size()-1;
kpeter@750
   241
      _iim.set(_data[h].first, POST_HEAP);
kpeter@748
   242
      if( h<n ) {
kpeter@750
   243
        if( less(_data[parent(h)], _data[n]) )
kpeter@750
   244
          bubbleDown(h, _data[n], n);
kpeter@748
   245
        else
kpeter@750
   246
          bubbleUp(h, _data[n]);
kpeter@748
   247
      }
kpeter@750
   248
      _data.pop_back();
kpeter@748
   249
    }
kpeter@748
   250
kpeter@750
   251
    /// \brief The priority of the given item.
kpeter@748
   252
    ///
kpeter@750
   253
    /// This function returns the priority of the given item.
kpeter@748
   254
    /// \param i The item.
kpeter@750
   255
    /// \pre \e i must be in the heap.
kpeter@748
   256
    Prio operator[](const Item &i) const {
kpeter@750
   257
      int idx = _iim[i];
kpeter@750
   258
      return _data[idx].second;
kpeter@748
   259
    }
kpeter@748
   260
kpeter@750
   261
    /// \brief Set the priority of an item or insert it, if it is
kpeter@750
   262
    /// not stored in the heap.
kpeter@748
   263
    ///
kpeter@750
   264
    /// This method sets the priority of the given item if it is
kpeter@750
   265
    /// already stored in the heap. Otherwise it inserts the given
kpeter@750
   266
    /// item into the heap with the given priority.
kpeter@748
   267
    /// \param i The item.
kpeter@748
   268
    /// \param p The priority.
kpeter@748
   269
    void set(const Item &i, const Prio &p) {
kpeter@750
   270
      int idx = _iim[i];
kpeter@748
   271
      if( idx<0 )
kpeter@748
   272
        push(i,p);
kpeter@750
   273
      else if( _comp(p, _data[idx].second) )
kpeter@750
   274
        bubbleUp(idx, Pair(i,p));
kpeter@748
   275
      else
kpeter@750
   276
        bubbleDown(idx, Pair(i,p), _data.size());
kpeter@748
   277
    }
kpeter@748
   278
kpeter@750
   279
    /// \brief Decrease the priority of an item to the given value.
kpeter@748
   280
    ///
kpeter@750
   281
    /// This function decreases the priority of an item to the given value.
kpeter@748
   282
    /// \param i The item.
kpeter@748
   283
    /// \param p The priority.
kpeter@750
   284
    /// \pre \e i must be stored in the heap with priority at least \e p.
kpeter@748
   285
    void decrease(const Item &i, const Prio &p) {
kpeter@750
   286
      int idx = _iim[i];
kpeter@750
   287
      bubbleUp(idx, Pair(i,p));
kpeter@748
   288
    }
kpeter@748
   289
kpeter@750
   290
    /// \brief Increase the priority of an item to the given value.
kpeter@748
   291
    ///
kpeter@750
   292
    /// This function increases the priority of an item to the given value.
kpeter@748
   293
    /// \param i The item.
kpeter@748
   294
    /// \param p The priority.
kpeter@750
   295
    /// \pre \e i must be stored in the heap with priority at most \e p.
kpeter@748
   296
    void increase(const Item &i, const Prio &p) {
kpeter@750
   297
      int idx = _iim[i];
kpeter@750
   298
      bubbleDown(idx, Pair(i,p), _data.size());
kpeter@748
   299
    }
kpeter@748
   300
kpeter@750
   301
    /// \brief Return the state of an item.
kpeter@748
   302
    ///
kpeter@750
   303
    /// This method returns \c PRE_HEAP if the given item has never
kpeter@750
   304
    /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
kpeter@750
   305
    /// and \c POST_HEAP otherwise.
kpeter@750
   306
    /// In the latter case it is possible that the item will get back
kpeter@750
   307
    /// to the heap again.
kpeter@748
   308
    /// \param i The item.
kpeter@748
   309
    State state(const Item &i) const {
kpeter@750
   310
      int s = _iim[i];
kpeter@748
   311
      if (s>=0) s=0;
kpeter@748
   312
      return State(s);
kpeter@748
   313
    }
kpeter@748
   314
kpeter@750
   315
    /// \brief Set the state of an item in the heap.
kpeter@748
   316
    ///
kpeter@750
   317
    /// This function sets the state of the given item in the heap.
kpeter@750
   318
    /// It can be used to manually clear the heap when it is important
kpeter@750
   319
    /// to achive better time complexity.
kpeter@748
   320
    /// \param i The item.
kpeter@748
   321
    /// \param st The state. It should not be \c IN_HEAP.
kpeter@748
   322
    void state(const Item& i, State st) {
kpeter@748
   323
      switch (st) {
kpeter@750
   324
        case POST_HEAP:
kpeter@750
   325
        case PRE_HEAP:
kpeter@750
   326
          if (state(i) == IN_HEAP) erase(i);
kpeter@750
   327
          _iim[i] = st;
kpeter@750
   328
          break;
kpeter@750
   329
        case IN_HEAP:
kpeter@750
   330
          break;
kpeter@748
   331
      }
kpeter@748
   332
    }
kpeter@748
   333
kpeter@750
   334
    /// \brief Replace an item in the heap.
kpeter@748
   335
    ///
kpeter@750
   336
    /// This function replaces item \c i with item \c j.
kpeter@750
   337
    /// Item \c i must be in the heap, while \c j must be out of the heap.
kpeter@750
   338
    /// After calling this method, item \c i will be out of the
kpeter@750
   339
    /// heap and \c j will be in the heap with the same prioriority
kpeter@750
   340
    /// as item \c i had before.
kpeter@748
   341
    void replace(const Item& i, const Item& j) {
kpeter@750
   342
      int idx=_iim[i];
kpeter@750
   343
      _iim.set(i, _iim[j]);
kpeter@750
   344
      _iim.set(j, idx);
kpeter@750
   345
      _data[idx].first=j;
kpeter@748
   346
    }
kpeter@748
   347
kpeter@929
   348
  }; // class DHeap
kpeter@748
   349
kpeter@748
   350
} // namespace lemon
kpeter@748
   351
kpeter@929
   352
#endif // LEMON_DHEAP_H