COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/bin_heap.h @ 2546:b5eba564bb60

Last change on this file since 2546:b5eba564bb60 was 2546:b5eba564bb60, checked in by Balazs Dezso, 12 years ago

Bug fix in erase

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