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