1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_KARY_HEAP_H
20 #define LEMON_KARY_HEAP_H
24 ///\brief Fourary heap implementation.
34 ///\brief K-ary heap data structure.
36 /// This class implements the \e K-ary \e heap data structure.
37 /// It fully conforms to the \ref concepts::Heap "heap concept".
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.
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>.
58 template <typename PR, typename IM, int K, typename CMP>
60 template <typename PR, typename IM, int K = 16,
61 typename CMP = std::less<PR> >
65 /// Type of the item-int map.
66 typedef IM ItemIntMap;
67 /// Type of the priorities.
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.
76 /// \brief Type to represent the states of the items.
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.
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.
85 IN_HEAP = 0, ///< = 0.
86 PRE_HEAP = -1, ///< = -1.
87 POST_HEAP = -2 ///< = -2.
91 std::vector<Pair> _data;
96 /// \brief 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) {}
104 /// \brief 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) {}
114 /// \brief The number of items stored in the heap.
116 /// This function returns the number of items stored in the heap.
117 int size() const { return _data.size(); }
119 /// \brief Check if the heap is empty.
121 /// This function returns \c true if the heap is empty.
122 bool empty() const { return _data.empty(); }
124 /// \brief Make the heap empty.
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
131 void clear() { _data.clear(); }
134 int parent(int i) { return (i-1)/K; }
135 int firstChild(int i) { return K*i+1; }
137 bool less(const Pair &p1, const Pair &p2) const {
138 return _comp(p1.second, p2.second);
141 int findMin(const int child, const int length) {
143 while( i<K && child+i<length ) {
144 if( less(_data[child+i], _data[min]) )
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);
161 void bubbleDown(int hole, Pair p, int length) {
163 int child = firstChild(hole);
164 while( child<length ) {
165 child = findMin(child, length);
166 if( !less(_data[child], p) )
168 move(_data[child], hole);
170 child = firstChild(hole);
177 void move(const Pair &p, int i) {
179 _iim.set(p.first, i);
183 /// \brief Insert a pair of item and priority into the heap.
185 /// This function inserts \c p.first to the heap with priority
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();
195 /// \brief Insert an item into the heap with the given priority.
197 /// This function inserts the given item into the heap with the
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)); }
204 /// \brief Return the item having minimum priority.
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; }
210 /// \brief The minimum priority.
212 /// This function returns the minimum priority.
213 /// \pre The heap must be non-empty.
214 Prio prio() const { return _data[0].second; }
216 /// \brief Remove the item having minimum priority.
218 /// This function removes the item having minimum priority.
219 /// \pre The heap must be non-empty.
221 int n = _data.size()-1;
222 _iim.set(_data[0].first, POST_HEAP);
223 if (n>0) bubbleDown(0, _data[n], n);
227 /// \brief Remove the given item from the heap.
229 /// This function removes the given item from the heap if it is
231 /// \param i The item to delete.
232 /// \pre \e i must be in the heap.
233 void erase(const Item &i) {
235 int n = _data.size()-1;
236 _iim.set(_data[h].first, POST_HEAP);
238 if( less(_data[parent(h)], _data[n]) )
239 bubbleDown(h, _data[n], n);
241 bubbleUp(h, _data[n]);
246 /// \brief The priority of the given item.
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 {
253 return _data[idx].second;
256 /// \brief Set the priority of an item or insert it, if it is
257 /// not stored in the heap.
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) {
268 else if( _comp(p, _data[idx].second) )
269 bubbleUp(idx, Pair(i,p));
271 bubbleDown(idx, Pair(i,p), _data.size());
274 /// \brief Decrease the priority of an item to the given value.
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) {
282 bubbleUp(idx, Pair(i,p));
285 /// \brief Increase the priority of an item to the given value.
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) {
293 bubbleDown(idx, Pair(i,p), _data.size());
296 /// \brief Return the state of an item.
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 {
310 /// \brief Set the state of an item in the heap.
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) {
321 if (state(i) == IN_HEAP) erase(i);
329 /// \brief Replace an item in the heap.
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) {
338 _iim.set(i, _iim[j]);
347 #endif // LEMON_KARY_HEAP_H