COIN-OR::LEMON - Graph Library

source: lemon/lemon/kary_heap.h @ 751:7124b2581f72

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

Make K a template parameter in KaryHeap? (#301)

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