kpeter@703: /* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@701:  *
kpeter@703:  * This file is a part of LEMON, a generic C++ optimization library.
kpeter@701:  *
kpeter@703:  * Copyright (C) 2003-2009
kpeter@701:  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@701:  * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@701:  *
kpeter@701:  * Permission to use, modify and distribute this software is granted
kpeter@701:  * provided that this copyright notice appears in all copies. For
kpeter@701:  * precise terms see the accompanying LICENSE file.
kpeter@701:  *
kpeter@701:  * This software is provided "AS IS" with no warranty of any kind,
kpeter@701:  * express or implied, and with no claim as to its suitability for any
kpeter@701:  * purpose.
kpeter@701:  *
kpeter@701:  */
kpeter@701: 
kpeter@855: #ifndef LEMON_DHEAP_H
kpeter@855: #define LEMON_DHEAP_H
kpeter@701: 
kpeter@703: ///\ingroup heaps
kpeter@701: ///\file
kpeter@855: ///\brief D-ary heap implementation.
kpeter@701: 
kpeter@701: #include <vector>
kpeter@701: #include <utility>
kpeter@701: #include <functional>
kpeter@701: 
kpeter@701: namespace lemon {
kpeter@701: 
kpeter@703:   /// \ingroup heaps
kpeter@701:   ///
kpeter@855:   ///\brief D-ary heap data structure.
kpeter@701:   ///
kpeter@855:   /// This class implements the \e D-ary \e heap data structure.
kpeter@703:   /// It fully conforms to the \ref concepts::Heap "heap concept".
kpeter@701:   ///
kpeter@855:   /// The \ref DHeap "D-ary heap" is a generalization of the
kpeter@703:   /// \ref BinHeap "binary heap" structure, its nodes have at most
kpeter@855:   /// \c D children, instead of two.
kpeter@855:   /// \ref BinHeap and \ref QuadHeap are specialized implementations
kpeter@855:   /// of this structure for <tt>D=2</tt> and <tt>D=4</tt>, respectively.
kpeter@701:   ///
kpeter@703:   /// \tparam PR Type of the priorities of the items.
kpeter@703:   /// \tparam IM A read-writable item map with \c int values, used
kpeter@703:   /// internally to handle the cross references.
kpeter@855:   /// \tparam D The degree of the heap, each node have at most \e D
kpeter@704:   /// children. The default is 16. Powers of two are suggested to use
kpeter@704:   /// so that the multiplications and divisions needed to traverse the
kpeter@704:   /// nodes of the heap could be performed faster.
kpeter@703:   /// \tparam CMP A functor class for comparing the priorities.
kpeter@703:   /// The default is \c std::less<PR>.
kpeter@703:   ///
kpeter@703:   ///\sa BinHeap
kpeter@703:   ///\sa FouraryHeap
kpeter@703: #ifdef DOXYGEN
kpeter@855:   template <typename PR, typename IM, int D, typename CMP>
kpeter@703: #else
kpeter@855:   template <typename PR, typename IM, int D = 16,
kpeter@704:             typename CMP = std::less<PR> >
kpeter@703: #endif
kpeter@855:   class DHeap {
kpeter@703:   public:
kpeter@703:     /// Type of the item-int map.
kpeter@703:     typedef IM ItemIntMap;
kpeter@703:     /// Type of the priorities.
kpeter@703:     typedef PR Prio;
kpeter@703:     /// Type of the items stored in the heap.
kpeter@703:     typedef typename ItemIntMap::Key Item;
kpeter@703:     /// Type of the item-priority pairs.
kpeter@703:     typedef std::pair<Item,Prio> Pair;
kpeter@703:     /// Functor type for comparing the priorities.
kpeter@703:     typedef CMP Compare;
kpeter@701: 
kpeter@703:     /// \brief Type to represent the states of the items.
kpeter@701:     ///
kpeter@703:     /// Each item has a state associated to it. It can be "in heap",
kpeter@703:     /// "pre-heap" or "post-heap". The latter two are indifferent from the
kpeter@701:     /// heap's point of view, but may be useful to the user.
kpeter@701:     ///
kpeter@703:     /// The item-int map must be initialized in such way that it assigns
kpeter@703:     /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
kpeter@701:     enum State {
kpeter@703:       IN_HEAP = 0,    ///< = 0.
kpeter@703:       PRE_HEAP = -1,  ///< = -1.
kpeter@703:       POST_HEAP = -2  ///< = -2.
kpeter@701:     };
kpeter@701: 
kpeter@701:   private:
kpeter@703:     std::vector<Pair> _data;
kpeter@703:     Compare _comp;
kpeter@703:     ItemIntMap &_iim;
kpeter@701: 
kpeter@701:   public:
kpeter@703:     /// \brief Constructor.
kpeter@701:     ///
kpeter@703:     /// Constructor.
kpeter@703:     /// \param map A map that assigns \c int values to the items.
kpeter@703:     /// It is used internally to handle the cross references.
kpeter@703:     /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
kpeter@855:     explicit DHeap(ItemIntMap &map) : _iim(map) {}
kpeter@701: 
kpeter@703:     /// \brief Constructor.
kpeter@701:     ///
kpeter@703:     /// Constructor.
kpeter@703:     /// \param map A map that assigns \c int values to the items.
kpeter@703:     /// It is used internally to handle the cross references.
kpeter@703:     /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
kpeter@703:     /// \param comp The function object used for comparing the priorities.
kpeter@855:     DHeap(ItemIntMap &map, const Compare &comp)
kpeter@704:       : _iim(map), _comp(comp) {}
kpeter@703: 
kpeter@703:     /// \brief The number of items stored in the heap.
kpeter@701:     ///
kpeter@703:     /// This function returns the number of items stored in the heap.
kpeter@703:     int size() const { return _data.size(); }
kpeter@701: 
kpeter@703:     /// \brief Check if the heap is empty.
kpeter@703:     ///
kpeter@703:     /// This function returns \c true if the heap is empty.
kpeter@703:     bool empty() const { return _data.empty(); }
kpeter@701: 
kpeter@703:     /// \brief Make the heap empty.
kpeter@701:     ///
kpeter@703:     /// This functon makes the heap empty.
kpeter@703:     /// It does not change the cross reference map. If you want to reuse
kpeter@703:     /// a heap that is not surely empty, you should first clear it and
kpeter@703:     /// then you should set the cross reference map to \c PRE_HEAP
kpeter@703:     /// for each item.
kpeter@703:     void clear() { _data.clear(); }
kpeter@701: 
kpeter@701:   private:
kpeter@855:     int parent(int i) { return (i-1)/D; }
kpeter@855:     int firstChild(int i) { return D*i+1; }
kpeter@701: 
kpeter@701:     bool less(const Pair &p1, const Pair &p2) const {
kpeter@703:       return _comp(p1.second, p2.second);
kpeter@701:     }
kpeter@701: 
kpeter@703:     void bubbleUp(int hole, Pair p) {
kpeter@701:       int par = parent(hole);
kpeter@703:       while( hole>0 && less(p,_data[par]) ) {
kpeter@703:         move(_data[par],hole);
kpeter@701:         hole = par;
kpeter@701:         par = parent(hole);
kpeter@701:       }
kpeter@701:       move(p, hole);
kpeter@701:     }
kpeter@701: 
kpeter@703:     void bubbleDown(int hole, Pair p, int length) {
kpeter@701:       if( length>1 ) {
kpeter@703:         int child = firstChild(hole);
kpeter@855:         while( child+D<=length ) {
kpeter@706:           int min=child;
kpeter@855:           for (int i=1; i<D; ++i) {
kpeter@706:             if( less(_data[child+i], _data[min]) )
kpeter@706:               min=child+i;
kpeter@706:           }
kpeter@706:           if( !less(_data[min], p) )
kpeter@701:             goto ok;
kpeter@706:           move(_data[min], hole);
kpeter@706:           hole = min;
kpeter@703:           child = firstChild(hole);
kpeter@701:         }
kpeter@706:         if ( child<length ) {
kpeter@706:           int min = child;
kpeter@706:           while (++child < length) {
kpeter@706:             if( less(_data[child], _data[min]) )
kpeter@706:               min=child;
kpeter@706:           }
kpeter@706:           if( less(_data[min], p) ) {
kpeter@706:             move(_data[min], hole);
kpeter@706:             hole = min;
kpeter@706:           }
kpeter@706:         }
kpeter@701:       }
kpeter@701:     ok:
kpeter@701:       move(p, hole);
kpeter@701:     }
kpeter@701: 
kpeter@701:     void move(const Pair &p, int i) {
kpeter@703:       _data[i] = p;
kpeter@703:       _iim.set(p.first, i);
kpeter@701:     }
kpeter@701: 
kpeter@701:   public:
kpeter@701:     /// \brief Insert a pair of item and priority into the heap.
kpeter@701:     ///
kpeter@703:     /// This function inserts \c p.first to the heap with priority
kpeter@703:     /// \c p.second.
kpeter@701:     /// \param p The pair to insert.
kpeter@703:     /// \pre \c p.first must not be stored in the heap.
kpeter@701:     void push(const Pair &p) {
kpeter@703:       int n = _data.size();
kpeter@703:       _data.resize(n+1);
kpeter@703:       bubbleUp(n, p);
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Insert an item into the heap with the given priority.
kpeter@701:     ///
kpeter@703:     /// This function inserts the given item into the heap with the
kpeter@703:     /// given priority.
kpeter@701:     /// \param i The item to insert.
kpeter@701:     /// \param p The priority of the item.
kpeter@703:     /// \pre \e i must not be stored in the heap.
kpeter@701:     void push(const Item &i, const Prio &p) { push(Pair(i,p)); }
kpeter@701: 
kpeter@703:     /// \brief Return the item having minimum priority.
kpeter@701:     ///
kpeter@703:     /// This function returns the item having minimum priority.
kpeter@703:     /// \pre The heap must be non-empty.
kpeter@703:     Item top() const { return _data[0].first; }
kpeter@701: 
kpeter@703:     /// \brief The minimum priority.
kpeter@701:     ///
kpeter@703:     /// This function returns the minimum priority.
kpeter@703:     /// \pre The heap must be non-empty.
kpeter@703:     Prio prio() const { return _data[0].second; }
kpeter@701: 
kpeter@703:     /// \brief Remove the item having minimum priority.
kpeter@701:     ///
kpeter@703:     /// This function removes the item having minimum priority.
kpeter@701:     /// \pre The heap must be non-empty.
kpeter@701:     void pop() {
kpeter@703:       int n = _data.size()-1;
kpeter@703:       _iim.set(_data[0].first, POST_HEAP);
kpeter@703:       if (n>0) bubbleDown(0, _data[n], n);
kpeter@703:       _data.pop_back();
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Remove the given item from the heap.
kpeter@701:     ///
kpeter@703:     /// This function removes the given item from the heap if it is
kpeter@703:     /// already stored.
kpeter@703:     /// \param i The item to delete.
kpeter@703:     /// \pre \e i must be in the heap.
kpeter@701:     void erase(const Item &i) {
kpeter@703:       int h = _iim[i];
kpeter@703:       int n = _data.size()-1;
kpeter@703:       _iim.set(_data[h].first, POST_HEAP);
kpeter@701:       if( h<n ) {
kpeter@703:         if( less(_data[parent(h)], _data[n]) )
kpeter@703:           bubbleDown(h, _data[n], n);
kpeter@701:         else
kpeter@703:           bubbleUp(h, _data[n]);
kpeter@701:       }
kpeter@703:       _data.pop_back();
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief The priority of the given item.
kpeter@701:     ///
kpeter@703:     /// This function returns the priority of the given item.
kpeter@701:     /// \param i The item.
kpeter@703:     /// \pre \e i must be in the heap.
kpeter@701:     Prio operator[](const Item &i) const {
kpeter@703:       int idx = _iim[i];
kpeter@703:       return _data[idx].second;
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Set the priority of an item or insert it, if it is
kpeter@703:     /// not stored in the heap.
kpeter@701:     ///
kpeter@703:     /// This method sets the priority of the given item if it is
kpeter@703:     /// already stored in the heap. Otherwise it inserts the given
kpeter@703:     /// item into the heap with the given priority.
kpeter@701:     /// \param i The item.
kpeter@701:     /// \param p The priority.
kpeter@701:     void set(const Item &i, const Prio &p) {
kpeter@703:       int idx = _iim[i];
kpeter@701:       if( idx<0 )
kpeter@701:         push(i,p);
kpeter@703:       else if( _comp(p, _data[idx].second) )
kpeter@703:         bubbleUp(idx, Pair(i,p));
kpeter@701:       else
kpeter@703:         bubbleDown(idx, Pair(i,p), _data.size());
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Decrease the priority of an item to the given value.
kpeter@701:     ///
kpeter@703:     /// This function decreases the priority of an item to the given value.
kpeter@701:     /// \param i The item.
kpeter@701:     /// \param p The priority.
kpeter@703:     /// \pre \e i must be stored in the heap with priority at least \e p.
kpeter@701:     void decrease(const Item &i, const Prio &p) {
kpeter@703:       int idx = _iim[i];
kpeter@703:       bubbleUp(idx, Pair(i,p));
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Increase the priority of an item to the given value.
kpeter@701:     ///
kpeter@703:     /// This function increases the priority of an item to the given value.
kpeter@701:     /// \param i The item.
kpeter@701:     /// \param p The priority.
kpeter@703:     /// \pre \e i must be stored in the heap with priority at most \e p.
kpeter@701:     void increase(const Item &i, const Prio &p) {
kpeter@703:       int idx = _iim[i];
kpeter@703:       bubbleDown(idx, Pair(i,p), _data.size());
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Return the state of an item.
kpeter@701:     ///
kpeter@703:     /// This method returns \c PRE_HEAP if the given item has never
kpeter@703:     /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
kpeter@703:     /// and \c POST_HEAP otherwise.
kpeter@703:     /// In the latter case it is possible that the item will get back
kpeter@703:     /// to the heap again.
kpeter@701:     /// \param i The item.
kpeter@701:     State state(const Item &i) const {
kpeter@703:       int s = _iim[i];
kpeter@701:       if (s>=0) s=0;
kpeter@701:       return State(s);
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Set the state of an item in the heap.
kpeter@701:     ///
kpeter@703:     /// This function sets the state of the given item in the heap.
kpeter@703:     /// It can be used to manually clear the heap when it is important
kpeter@703:     /// to achive better time complexity.
kpeter@701:     /// \param i The item.
kpeter@701:     /// \param st The state. It should not be \c IN_HEAP.
kpeter@701:     void state(const Item& i, State st) {
kpeter@701:       switch (st) {
kpeter@703:         case POST_HEAP:
kpeter@703:         case PRE_HEAP:
kpeter@703:           if (state(i) == IN_HEAP) erase(i);
kpeter@703:           _iim[i] = st;
kpeter@703:           break;
kpeter@703:         case IN_HEAP:
kpeter@703:           break;
kpeter@701:       }
kpeter@701:     }
kpeter@701: 
kpeter@703:     /// \brief Replace an item in the heap.
kpeter@701:     ///
kpeter@703:     /// This function replaces item \c i with item \c j.
kpeter@703:     /// Item \c i must be in the heap, while \c j must be out of the heap.
kpeter@703:     /// After calling this method, item \c i will be out of the
kpeter@703:     /// heap and \c j will be in the heap with the same prioriority
kpeter@703:     /// as item \c i had before.
kpeter@701:     void replace(const Item& i, const Item& j) {
kpeter@703:       int idx=_iim[i];
kpeter@703:       _iim.set(i, _iim[j]);
kpeter@703:       _iim.set(j, idx);
kpeter@703:       _data[idx].first=j;
kpeter@701:     }
kpeter@701: 
kpeter@855:   }; // class DHeap
kpeter@701: 
kpeter@701: } // namespace lemon
kpeter@701: 
kpeter@855: #endif // LEMON_DHEAP_H