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