lemon/bin_heap.h
author deba
Thu, 20 Dec 2007 15:21:22 +0000
changeset 2546 b5eba564bb60
parent 2529 93de38566e6c
child 2547 f393a8162688
permissions -rw-r--r--
Bug fix in erase
alpar@906
     1
/* -*- C++ -*-
klao@39
     2
 *
alpar@1956
     3
 * This file is a part of LEMON, a generic C++ optimization library
alpar@1956
     4
 *
alpar@2391
     5
 * Copyright (C) 2003-2007
alpar@1956
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@1359
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
klao@39
     8
 *
alpar@906
     9
 * Permission to use, modify and distribute this software is granted
alpar@906
    10
 * provided that this copyright notice appears in all copies. For
alpar@906
    11
 * precise terms see the accompanying LICENSE file.
klao@39
    12
 *
alpar@906
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@906
    14
 * express or implied, and with no claim as to its suitability for any
alpar@906
    15
 * purpose.
klao@39
    16
 *
klao@39
    17
 */
klao@39
    18
alpar@921
    19
#ifndef LEMON_BIN_HEAP_H
alpar@921
    20
#define LEMON_BIN_HEAP_H
klao@37
    21
klao@491
    22
///\ingroup auxdat
klao@274
    23
///\file
klao@274
    24
///\brief Binary Heap implementation.
klao@274
    25
klao@37
    26
#include <vector>
klao@37
    27
#include <utility>
klao@37
    28
#include <functional>
klao@37
    29
alpar@921
    30
namespace lemon {
klao@37
    31
deba@2529
    32
  ///\ingroup auxdat
deba@2529
    33
  ///
deba@2529
    34
  ///\brief A Binary Heap implementation.
deba@2529
    35
  ///
jacint@1270
    36
  ///This class implements the \e binary \e heap data structure. A \e heap
jacint@1270
    37
  ///is a data structure for storing items with specified values called \e
jacint@1270
    38
  ///priorities in such a way that finding the item with minimum priority is
jacint@1270
    39
  ///efficient. \c Compare specifies the ordering of the priorities. In a heap
jacint@1270
    40
  ///one can change the priority of an item, add or erase an item, etc.
jacint@1270
    41
  ///
jacint@1270
    42
  ///\param Prio Type of the priority of the items.
jacint@1270
    43
  ///\param ItemIntMap A read and writable Item int map, used internally
jacint@1270
    44
  ///to handle the cross references.
jacint@1270
    45
  ///\param Compare A class for the ordering of the priorities. The
jacint@1270
    46
  ///default is \c std::less<Prio>.
alpar@967
    47
  ///
alpar@967
    48
  ///\sa FibHeap
alpar@967
    49
  ///\sa Dijkstra
mqrelly@2263
    50
  template <typename Prio, typename ItemIntMap,
klao@172
    51
	    typename Compare = std::less<Prio> >
klao@37
    52
  class BinHeap {
klao@37
    53
klao@37
    54
  public:
mqrelly@2263
    55
    typedef typename ItemIntMap::Key         ItemType;
klao@172
    56
    typedef Prio                             PrioType;
klao@172
    57
    typedef std::pair<ItemType,PrioType>     PairType;
klao@172
    58
    typedef ItemIntMap                       ItemIntMapType;
klao@172
    59
    typedef Compare                          PrioCompare;
klao@37
    60
deba@1331
    61
    /// \brief Type to represent the items states.
klao@274
    62
    ///
deba@1331
    63
    /// Each Item element have a state associated to it. It may be "in heap",
alpar@1336
    64
    /// "pre heap" or "post heap". The latter two are indifferent from the
deba@1331
    65
    /// heap's point of view, but may be useful to the user.
deba@1331
    66
    ///
alpar@1336
    67
    /// The ItemIntMap \e should be initialized in such way that it maps
deba@1331
    68
    /// PRE_HEAP (-1) to any element to be put in the heap...
klao@39
    69
    enum state_enum {
klao@37
    70
      IN_HEAP = 0,
klao@37
    71
      PRE_HEAP = -1,
klao@37
    72
      POST_HEAP = -2
klao@37
    73
    };
klao@37
    74
klao@37
    75
  private:
klao@37
    76
    std::vector<PairType> data;
klao@37
    77
    Compare comp;
klao@172
    78
    ItemIntMap &iim;
klao@37
    79
klao@37
    80
  public:
deba@1331
    81
    /// \brief The constructor.
deba@1331
    82
    ///
deba@1331
    83
    /// The constructor.
deba@1331
    84
    /// \param _iim should be given to the constructor, since it is used
deba@1331
    85
    /// internally to handle the cross references. The value of the map
deba@1331
    86
    /// should be PRE_HEAP (-1) for each element.
deba@1185
    87
    explicit BinHeap(ItemIntMap &_iim) : iim(_iim) {}
jacint@1270
    88
    
deba@1331
    89
    /// \brief The constructor.
deba@1331
    90
    ///
deba@1331
    91
    /// The constructor.
deba@1331
    92
    /// \param _iim should be given to the constructor, since it is used
deba@1331
    93
    /// internally to handle the cross references. The value of the map
deba@1331
    94
    /// should be PRE_HEAP (-1) for each element.
deba@1331
    95
    ///
deba@1331
    96
    /// \param _comp The comparator function object.
deba@1191
    97
    BinHeap(ItemIntMap &_iim, const Compare &_comp) 
deba@1185
    98
      : iim(_iim), comp(_comp) {}
klao@37
    99
klao@37
   100
deba@1331
   101
    /// The number of items stored in the heap.
deba@1331
   102
    ///
deba@1331
   103
    /// \brief Returns the number of items stored in the heap.
klao@37
   104
    int size() const { return data.size(); }
jacint@1270
   105
    
deba@1331
   106
    /// \brief Checks if the heap stores no items.
deba@1331
   107
    ///
deba@1331
   108
    /// Returns \c true if and only if the heap stores no items.
klao@41
   109
    bool empty() const { return data.empty(); }
klao@37
   110
deba@1717
   111
    /// \brief Make empty this heap.
deba@1717
   112
    /// 
deba@2050
   113
    /// Make empty this heap. It does not change the cross reference map.
deba@2050
   114
    /// If you want to reuse what is not surely empty you should first clear
deba@2050
   115
    /// the heap and after that you should set the cross reference map for
deba@2050
   116
    /// each item to \c PRE_HEAP.
deba@1717
   117
    void clear() { 
deba@1717
   118
      data.clear(); 
deba@1717
   119
    }
deba@1717
   120
klao@37
   121
  private:
klao@37
   122
    static int parent(int i) { return (i-1)/2; }
deba@2546
   123
klao@37
   124
    static int second_child(int i) { return 2*i+2; }
klao@214
   125
    bool less(const PairType &p1, const PairType &p2) const {
klao@37
   126
      return comp(p1.second, p2.second);
klao@37
   127
    }
klao@37
   128
deba@2546
   129
    int bubble_up(int hole, PairType p) {
deba@2546
   130
      int par = parent(hole);
deba@2546
   131
      while( hole>0 && less(p,data[par]) ) {
deba@2546
   132
	move(data[par],hole);
deba@2546
   133
	hole = par;
deba@2546
   134
	par = parent(hole);
deba@2546
   135
      }
deba@2546
   136
      move(p, hole);
deba@2546
   137
      return hole;
deba@2546
   138
    }
deba@2546
   139
deba@2546
   140
    int bubble_down(int hole, PairType p, int length) {
deba@2546
   141
      int child = second_child(hole);
deba@2546
   142
      while(child < length) {
deba@2546
   143
	if( less(data[child-1], data[child]) ) {
deba@2546
   144
	  --child;
deba@2546
   145
	}
deba@2546
   146
	if( !less(data[child], p) )
deba@2546
   147
	  goto ok;
deba@2546
   148
	move(data[child], hole);
deba@2546
   149
	hole = child;
deba@2546
   150
	child = second_child(hole);
deba@2546
   151
      }
deba@2546
   152
      child--;
deba@2546
   153
      if( child<length && less(data[child], p) ) {
deba@2546
   154
	move(data[child], hole);
deba@2546
   155
	hole=child;
deba@2546
   156
      }
deba@2546
   157
    ok:
deba@2546
   158
      move(p, hole);
deba@2546
   159
      return hole;
deba@2546
   160
    }
klao@37
   161
klao@37
   162
    void move(const PairType &p, int i) {
klao@37
   163
      data[i] = p;
klao@172
   164
      iim.set(p.first, i);
klao@37
   165
    }
klao@37
   166
klao@37
   167
  public:
deba@1331
   168
    /// \brief Insert a pair of item and priority into the heap.
deba@1331
   169
    ///
deba@1331
   170
    /// Adds \c p.first to the heap with priority \c p.second.
deba@1331
   171
    /// \param p The pair to insert.
klao@37
   172
    void push(const PairType &p) {
klao@37
   173
      int n = data.size();
klao@37
   174
      data.resize(n+1);
klao@37
   175
      bubble_up(n, p);
klao@37
   176
    }
jacint@1270
   177
deba@1331
   178
    /// \brief Insert an item into the heap with the given heap.
deba@1331
   179
    ///    
deba@1331
   180
    /// Adds \c i to the heap with priority \c p. 
deba@1331
   181
    /// \param i The item to insert.
deba@1331
   182
    /// \param p The priority of the item.
mqrelly@2263
   183
    void push(const ItemType &i, const Prio &p) { push(PairType(i,p)); }
klao@37
   184
deba@1331
   185
    /// \brief Returns the item with minimum priority relative to \c Compare.
deba@1331
   186
    ///
deba@1331
   187
    /// This method returns the item with minimum priority relative to \c
deba@1331
   188
    /// Compare.  
deba@1331
   189
    /// \pre The heap must be nonempty.  
mqrelly@2263
   190
    ItemType top() const {
klao@37
   191
      return data[0].first;
klao@37
   192
    }
jacint@1270
   193
deba@1331
   194
    /// \brief Returns the minimum priority relative to \c Compare.
deba@1331
   195
    ///
deba@1331
   196
    /// It returns the minimum priority relative to \c Compare.
deba@1331
   197
    /// \pre The heap must be nonempty.
klao@274
   198
    Prio prio() const {
klao@37
   199
      return data[0].second;
klao@37
   200
    }
klao@37
   201
deba@1331
   202
    /// \brief Deletes the item with minimum priority relative to \c Compare.
deba@1331
   203
    ///
deba@1331
   204
    /// This method deletes the item with minimum priority relative to \c
deba@1331
   205
    /// Compare from the heap.  
deba@1331
   206
    /// \pre The heap must be non-empty.  
klao@37
   207
    void pop() {
deba@2546
   208
      int n = data.size()-1;
deba@2546
   209
      iim.set(data[0].first, POST_HEAP);
deba@2546
   210
      if (n > 0) {
deba@2546
   211
	bubble_down(0, data[n], n);
deba@2546
   212
      }
deba@2546
   213
      data.pop_back();
klao@41
   214
    }
klao@41
   215
deba@1331
   216
    /// \brief Deletes \c i from the heap.
deba@1331
   217
    ///
deba@2546
   218
    /// This method deletes item \c i from the heap.
deba@2546
   219
    /// \param i The item to erase.
deba@2546
   220
    /// \pre The item should be in the heap.
mqrelly@2263
   221
    void erase(const ItemType &i) {
deba@2546
   222
      int h = iim[i];
deba@2546
   223
      int n = data.size()-1;
deba@2546
   224
      iim.set(data[h].first, POST_HEAP);
deba@2546
   225
      if( h < n ) {
deba@2546
   226
	if ( bubble_up(h, data[n]) == h) {
deba@2546
   227
	  bubble_down(h, data[n], n);
deba@2546
   228
	}
deba@2546
   229
      }
deba@2546
   230
      data.pop_back();
klao@37
   231
    }
klao@37
   232
jacint@1270
   233
    
deba@1331
   234
    /// \brief Returns the priority of \c i.
deba@1331
   235
    ///
deba@1331
   236
    /// This function returns the priority of item \c i.  
deba@1331
   237
    /// \pre \c i must be in the heap.
deba@1331
   238
    /// \param i The item.
mqrelly@2263
   239
    Prio operator[](const ItemType &i) const {
jacint@221
   240
      int idx = iim[i];
klao@37
   241
      return data[idx].second;
klao@37
   242
    }
klao@274
   243
deba@1331
   244
    /// \brief \c i gets to the heap with priority \c p independently 
deba@1331
   245
    /// if \c i was already there.
deba@1331
   246
    ///
deba@1331
   247
    /// This method calls \ref push(\c i, \c p) if \c i is not stored
deba@1331
   248
    /// in the heap and sets the priority of \c i to \c p otherwise.
deba@1331
   249
    /// \param i The item.
deba@1331
   250
    /// \param p The priority.
mqrelly@2263
   251
    void set(const ItemType &i, const Prio &p) {
jacint@221
   252
      int idx = iim[i];
klao@37
   253
      if( idx < 0 ) {
klao@172
   254
	push(i,p);
klao@37
   255
      }
klao@172
   256
      else if( comp(p, data[idx].second) ) {
klao@172
   257
	bubble_up(idx, PairType(i,p));
klao@37
   258
      }
klao@37
   259
      else {
klao@172
   260
	bubble_down(idx, PairType(i,p), data.size());
klao@37
   261
      }
klao@37
   262
    }
klao@37
   263
deba@1331
   264
    /// \brief Decreases the priority of \c i to \c p.
deba@2529
   265
    ///
deba@1331
   266
    /// This method decreases the priority of item \c i to \c p.
deba@1331
   267
    /// \pre \c i must be stored in the heap with priority at least \c
deba@1331
   268
    /// p relative to \c Compare.
deba@1331
   269
    /// \param i The item.
deba@1331
   270
    /// \param p The priority.
mqrelly@2263
   271
    void decrease(const ItemType &i, const Prio &p) {
jacint@221
   272
      int idx = iim[i];
klao@172
   273
      bubble_up(idx, PairType(i,p));
klao@37
   274
    }
jacint@1270
   275
    
deba@1331
   276
    /// \brief Increases the priority of \c i to \c p.
deba@1331
   277
    ///
deba@1331
   278
    /// This method sets the priority of item \c i to \c p. 
deba@1331
   279
    /// \pre \c i must be stored in the heap with priority at most \c
deba@1331
   280
    /// p relative to \c Compare.
deba@1331
   281
    /// \param i The item.
deba@1331
   282
    /// \param p The priority.
mqrelly@2263
   283
    void increase(const ItemType &i, const Prio &p) {
jacint@221
   284
      int idx = iim[i];
klao@172
   285
      bubble_down(idx, PairType(i,p), data.size());
klao@37
   286
    }
klao@37
   287
deba@1331
   288
    /// \brief Returns if \c item is in, has already been in, or has 
deba@1331
   289
    /// never been in the heap.
deba@1331
   290
    ///
deba@1331
   291
    /// This method returns PRE_HEAP if \c item has never been in the
deba@1331
   292
    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
deba@1331
   293
    /// otherwise. In the latter case it is possible that \c item will
deba@1331
   294
    /// get back to the heap again.
deba@1331
   295
    /// \param i The item.
mqrelly@2263
   296
    state_enum state(const ItemType &i) const {
jacint@221
   297
      int s = iim[i];
klao@39
   298
      if( s>=0 )
klao@39
   299
	s=0;
klao@39
   300
      return state_enum(s);
klao@39
   301
    }
klao@39
   302
deba@1902
   303
    /// \brief Sets the state of the \c item in the heap.
deba@1902
   304
    ///
deba@1902
   305
    /// Sets the state of the \c item in the heap. It can be used to
deba@1902
   306
    /// manually clear the heap when it is important to achive the
deba@1902
   307
    /// better time complexity.
deba@1902
   308
    /// \param i The item.
deba@1902
   309
    /// \param st The state. It should not be \c IN_HEAP. 
mqrelly@2263
   310
    void state(const ItemType& i, state_enum st) {
deba@1902
   311
      switch (st) {
deba@1902
   312
      case POST_HEAP:
deba@1902
   313
      case PRE_HEAP:
deba@1902
   314
        if (state(i) == IN_HEAP) {
deba@1902
   315
          erase(i);
deba@1902
   316
        }
deba@1903
   317
        iim[i] = st;
deba@1902
   318
        break;
deba@1906
   319
      case IN_HEAP:
deba@1906
   320
        break;
deba@1902
   321
      }
deba@1902
   322
    }
deba@1902
   323
klao@37
   324
  }; // class BinHeap
klao@37
   325
  
alpar@921
   326
} // namespace lemon
klao@37
   327
alpar@921
   328
#endif // LEMON_BIN_HEAP_H