COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/bin_heap.h @ 1875:98698b69a902

Last change on this file since 1875:98698b69a902 was 1875:98698b69a902, checked in by Alpar Juttner, 18 years ago

Happy new year to LEMON

File size: 9.1 KB
RevLine 
[906]1/* -*- C++ -*-
[1435]2 * lemon/bin_heap.h - Part of LEMON, a generic C++ optimization library
[39]3 *
[1875]4 * Copyright (C) 2006 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
[1359]5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
[39]6 *
[906]7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
[39]10 *
[906]11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
13 * purpose.
[39]14 *
15 */
16
[921]17#ifndef LEMON_BIN_HEAP_H
18#define LEMON_BIN_HEAP_H
[37]19
[491]20///\ingroup auxdat
[274]21///\file
22///\brief Binary Heap implementation.
23
[37]24#include <vector>
25#include <utility>
26#include <functional>
27
[921]28namespace lemon {
[37]29
[1834]30  /// \ingroup auxdat
[430]31
[1270]32  /// A Binary Heap implementation.
[967]33 
[1270]34  ///This class implements the \e binary \e heap data structure. A \e heap
35  ///is a data structure for storing items with specified values called \e
36  ///priorities in such a way that finding the item with minimum priority is
37  ///efficient. \c Compare specifies the ordering of the priorities. In a heap
38  ///one can change the priority of an item, add or erase an item, etc.
39  ///
40  ///\param Item Type of the items to be stored. 
41  ///\param Prio Type of the priority of the items.
42  ///\param ItemIntMap A read and writable Item int map, used internally
43  ///to handle the cross references.
44  ///\param Compare A class for the ordering of the priorities. The
45  ///default is \c std::less<Prio>.
[967]46  ///
47  ///\sa FibHeap
48  ///\sa Dijkstra
[172]49  template <typename Item, typename Prio, typename ItemIntMap,
50            typename Compare = std::less<Prio> >
[37]51  class BinHeap {
52
53  public:
[172]54    typedef Item                             ItemType;
[37]55    // FIXME: stl-ben nem ezt hivjak value_type -nak, hanem a kovetkezot...
[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    ///
113    /// Make empty this heap.
114    void clear() {
115      for (int i = 0; i < (int)data.size(); ++i) {
116        iim.set(data[i].first, POST_HEAP);
117      }
118      data.clear();
119    }
120
[37]121  private:
122    static int parent(int i) { return (i-1)/2; }
123    static int second_child(int i) { return 2*i+2; }
[214]124    bool less(const PairType &p1, const PairType &p2) const {
[37]125      return comp(p1.second, p2.second);
126    }
127
128    int bubble_up(int hole, PairType p);
129    int bubble_down(int hole, PairType p, int length);
130
131    void move(const PairType &p, int i) {
132      data[i] = p;
[172]133      iim.set(p.first, i);
[37]134    }
135
[41]136    void rmidx(int h) {
137      int n = data.size()-1;
138      if( h>=0 && h<=n ) {
[172]139        iim.set(data[h].first, POST_HEAP);
[41]140        if ( h<n ) {
141          bubble_down(h, data[n], n);
142        }
143        data.pop_back();
144      }
145    }
146
[37]147  public:
[1331]148    /// \brief Insert a pair of item and priority into the heap.
149    ///
150    /// Adds \c p.first to the heap with priority \c p.second.
151    /// \param p The pair to insert.
[37]152    void push(const PairType &p) {
153      int n = data.size();
154      data.resize(n+1);
155      bubble_up(n, p);
156    }
[1270]157
[1331]158    /// \brief Insert an item into the heap with the given heap.
159    ///   
160    /// Adds \c i to the heap with priority \c p.
161    /// \param i The item to insert.
162    /// \param p The priority of the item.
[172]163    void push(const Item &i, const Prio &p) { push(PairType(i,p)); }
[37]164
[1331]165    /// \brief Returns the item with minimum priority relative to \c Compare.
166    ///
167    /// This method returns the item with minimum priority relative to \c
168    /// Compare. 
169    /// \pre The heap must be nonempty. 
[172]170    Item top() const {
[37]171      return data[0].first;
172    }
[1270]173
[1331]174    /// \brief Returns the minimum priority relative to \c Compare.
175    ///
176    /// It returns the minimum priority relative to \c Compare.
177    /// \pre The heap must be nonempty.
[274]178    Prio prio() const {
[37]179      return data[0].second;
180    }
181
[1331]182    /// \brief Deletes the item with minimum priority relative to \c Compare.
183    ///
184    /// This method deletes the item with minimum priority relative to \c
185    /// Compare from the heap. 
186    /// \pre The heap must be non-empty. 
[37]187    void pop() {
[41]188      rmidx(0);
189    }
190
[1331]191    /// \brief Deletes \c i from the heap.
192    ///
193    /// This method deletes item \c i from the heap, if \c i was
194    /// already stored in the heap.
195    /// \param i The item to erase.
[172]196    void erase(const Item &i) {
[221]197      rmidx(iim[i]);
[37]198    }
199
[1270]200   
[1331]201    /// \brief Returns the priority of \c i.
202    ///
203    /// This function returns the priority of item \c i. 
204    /// \pre \c i must be in the heap.
205    /// \param i The item.
[274]206    Prio operator[](const Item &i) const {
[221]207      int idx = iim[i];
[37]208      return data[idx].second;
209    }
[274]210
[1331]211    /// \brief \c i gets to the heap with priority \c p independently
212    /// if \c i was already there.
213    ///
214    /// This method calls \ref push(\c i, \c p) if \c i is not stored
215    /// in the heap and sets the priority of \c i to \c p otherwise.
216    /// \param i The item.
217    /// \param p The priority.
[172]218    void set(const Item &i, const Prio &p) {
[221]219      int idx = iim[i];
[37]220      if( idx < 0 ) {
[172]221        push(i,p);
[37]222      }
[172]223      else if( comp(p, data[idx].second) ) {
224        bubble_up(idx, PairType(i,p));
[37]225      }
226      else {
[172]227        bubble_down(idx, PairType(i,p), data.size());
[37]228      }
229    }
230
[1331]231    /// \brief Decreases the priority of \c i to \c p.
[1270]232
[1331]233    /// This method decreases the priority of item \c i to \c p.
234    /// \pre \c i must be stored in the heap with priority at least \c
235    /// p relative to \c Compare.
236    /// \param i The item.
237    /// \param p The priority.
[172]238    void decrease(const Item &i, const Prio &p) {
[221]239      int idx = iim[i];
[172]240      bubble_up(idx, PairType(i,p));
[37]241    }
[1270]242   
[1331]243    /// \brief Increases the priority of \c i to \c p.
244    ///
245    /// This method sets the priority of item \c i to \c p.
246    /// \pre \c i must be stored in the heap with priority at most \c
247    /// p relative to \c Compare.
248    /// \param i The item.
249    /// \param p The priority.
[172]250    void increase(const Item &i, const Prio &p) {
[221]251      int idx = iim[i];
[172]252      bubble_down(idx, PairType(i,p), data.size());
[37]253    }
254
[1331]255    /// \brief Returns if \c item is in, has already been in, or has
256    /// never been in the heap.
257    ///
258    /// This method returns PRE_HEAP if \c item has never been in the
259    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
260    /// otherwise. In the latter case it is possible that \c item will
261    /// get back to the heap again.
262    /// \param i The item.
[172]263    state_enum state(const Item &i) const {
[221]264      int s = iim[i];
[39]265      if( s>=0 )
266        s=0;
267      return state_enum(s);
268    }
269
[37]270  }; // class BinHeap
271
272 
273  template <typename K, typename V, typename M, typename C>
274  int BinHeap<K,V,M,C>::bubble_up(int hole, PairType p) {
275    int par = parent(hole);
276    while( hole>0 && less(p,data[par]) ) {
277      move(data[par],hole);
278      hole = par;
279      par = parent(hole);
280    }
281    move(p, hole);
282    return hole;
283  }
284
285  template <typename K, typename V, typename M, typename C>
286  int BinHeap<K,V,M,C>::bubble_down(int hole, PairType p, int length) {
287    int child = second_child(hole);
288    while(child < length) {
289      if( less(data[child-1], data[child]) ) {
290        --child;
291      }
292      if( !less(data[child], p) )
293        goto ok;
294      move(data[child], hole);
295      hole = child;
296      child = second_child(hole);
297    }
298    child--;
299    if( child<length && less(data[child], p) ) {
300      move(data[child], hole);
301      hole=child;
302    }
303  ok:
304    move(p, hole);
305    return hole;
306  }
307
[430]308
[921]309} // namespace lemon
[37]310
[921]311#endif // LEMON_BIN_HEAP_H
Note: See TracBrowser for help on using the repository browser.