COIN-OR::LEMON - Graph Library

source: lemon/lemon/kary_heap.h @ 750:bb3392fe91f2

Last change on this file since 750:bb3392fe91f2 was 750:bb3392fe91f2, checked in by Peter Kovacs <kpeter@…>, 10 years ago

Improve and unify the doc + names in the new heaps (#301)

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