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