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, 16 years ago

Bug fix in erase

File size: 9.6 KB
RevLine 
[906]1/* -*- C++ -*-
[39]2 *
[1956]3 * This file is a part of LEMON, a generic C++ optimization library
4 *
[2391]5 * Copyright (C) 2003-2007
[1956]6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
[1359]7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
[39]8 *
[906]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.
[39]12 *
[906]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.
[39]16 *
17 */
18
[921]19#ifndef LEMON_BIN_HEAP_H
20#define LEMON_BIN_HEAP_H
[37]21
[491]22///\ingroup auxdat
[274]23///\file
24///\brief Binary Heap implementation.
25
[37]26#include <vector>
27#include <utility>
28#include <functional>
29
[921]30namespace lemon {
[37]31
[2529]32  ///\ingroup auxdat
33  ///
34  ///\brief A Binary Heap implementation.
35  ///
[1270]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>.
[967]47  ///
48  ///\sa FibHeap
49  ///\sa Dijkstra
[2263]50  template <typename Prio, typename ItemIntMap,
[172]51            typename Compare = std::less<Prio> >
[37]52  class BinHeap {
53
54  public:
[2263]55    typedef typename ItemIntMap::Key         ItemType;
[172]56    typedef Prio                             PrioType;
57    typedef std::pair<ItemType,PrioType>     PairType;
58    typedef ItemIntMap                       ItemIntMapType;
59    typedef Compare                          PrioCompare;
[37]60
[1331]61    /// \brief Type to represent the items states.
[274]62    ///
[1331]63    /// Each Item element have a state associated to it. It may be "in heap",
[1336]64    /// "pre heap" or "post heap". The latter two are indifferent from the
[1331]65    /// heap's point of view, but may be useful to the user.
66    ///
[1336]67    /// The ItemIntMap \e should be initialized in such way that it maps
[1331]68    /// PRE_HEAP (-1) to any element to be put in the heap...
[39]69    enum state_enum {
[37]70      IN_HEAP = 0,
71      PRE_HEAP = -1,
72      POST_HEAP = -2
73    };
74
75  private:
76    std::vector<PairType> data;
77    Compare comp;
[172]78    ItemIntMap &iim;
[37]79
80  public:
[1331]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.
[1185]87    explicit BinHeap(ItemIntMap &_iim) : iim(_iim) {}
[1270]88   
[1331]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.
[1191]97    BinHeap(ItemIntMap &_iim, const Compare &_comp)
[1185]98      : iim(_iim), comp(_comp) {}
[37]99
100
[1331]101    /// The number of items stored in the heap.
102    ///
103    /// \brief Returns the number of items stored in the heap.
[37]104    int size() const { return data.size(); }
[1270]105   
[1331]106    /// \brief Checks if the heap stores no items.
107    ///
108    /// Returns \c true if and only if the heap stores no items.
[41]109    bool empty() const { return data.empty(); }
[37]110
[1717]111    /// \brief Make empty this heap.
112    ///
[2050]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.
[1717]117    void clear() {
118      data.clear();
119    }
120
[37]121  private:
122    static int parent(int i) { return (i-1)/2; }
[2546]123
[37]124    static int second_child(int i) { return 2*i+2; }
[214]125    bool less(const PairType &p1, const PairType &p2) const {
[37]126      return comp(p1.second, p2.second);
127    }
128
[2546]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    }
[37]161
162    void move(const PairType &p, int i) {
163      data[i] = p;
[172]164      iim.set(p.first, i);
[37]165    }
166
167  public:
[1331]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.
[37]172    void push(const PairType &p) {
173      int n = data.size();
174      data.resize(n+1);
175      bubble_up(n, p);
176    }
[1270]177
[1331]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.
[2263]183    void push(const ItemType &i, const Prio &p) { push(PairType(i,p)); }
[37]184
[1331]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. 
[2263]190    ItemType top() const {
[37]191      return data[0].first;
192    }
[1270]193
[1331]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.
[274]198    Prio prio() const {
[37]199      return data[0].second;
200    }
201
[1331]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. 
[37]207    void pop() {
[2546]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();
[41]214    }
215
[1331]216    /// \brief Deletes \c i from the heap.
217    ///
[2546]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.
[2263]221    void erase(const ItemType &i) {
[2546]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();
[37]231    }
232
[1270]233   
[1331]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.
[2263]239    Prio operator[](const ItemType &i) const {
[221]240      int idx = iim[i];
[37]241      return data[idx].second;
242    }
[274]243
[1331]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.
[2263]251    void set(const ItemType &i, const Prio &p) {
[221]252      int idx = iim[i];
[37]253      if( idx < 0 ) {
[172]254        push(i,p);
[37]255      }
[172]256      else if( comp(p, data[idx].second) ) {
257        bubble_up(idx, PairType(i,p));
[37]258      }
259      else {
[172]260        bubble_down(idx, PairType(i,p), data.size());
[37]261      }
262    }
263
[1331]264    /// \brief Decreases the priority of \c i to \c p.
[2529]265    ///
[1331]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.
[2263]271    void decrease(const ItemType &i, const Prio &p) {
[221]272      int idx = iim[i];
[172]273      bubble_up(idx, PairType(i,p));
[37]274    }
[1270]275   
[1331]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.
[2263]283    void increase(const ItemType &i, const Prio &p) {
[221]284      int idx = iim[i];
[172]285      bubble_down(idx, PairType(i,p), data.size());
[37]286    }
287
[1331]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.
[2263]296    state_enum state(const ItemType &i) const {
[221]297      int s = iim[i];
[39]298      if( s>=0 )
299        s=0;
300      return state_enum(s);
301    }
302
[1902]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.
[2263]310    void state(const ItemType& i, state_enum st) {
[1902]311      switch (st) {
312      case POST_HEAP:
313      case PRE_HEAP:
314        if (state(i) == IN_HEAP) {
315          erase(i);
316        }
[1903]317        iim[i] = st;
[1902]318        break;
[1906]319      case IN_HEAP:
320        break;
[1902]321      }
322    }
323
[37]324  }; // class BinHeap
325 
[921]326} // namespace lemon
[37]327
[921]328#endif // LEMON_BIN_HEAP_H
Note: See TracBrowser for help on using the repository browser.