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