lemon/binomial_heap.h
changeset 993 ad40f7d32846
parent 855 65a0521e744e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/binomial_heap.h	Sun Aug 11 15:28:12 2013 +0200
     1.3 @@ -0,0 +1,445 @@
     1.4 +/* -*- mode: C++; indent-tabs-mode: nil; -*-
     1.5 + *
     1.6 + * This file is a part of LEMON, a generic C++ optimization library.
     1.7 + *
     1.8 + * Copyright (C) 2003-2010
     1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
    1.11 + *
    1.12 + * Permission to use, modify and distribute this software is granted
    1.13 + * provided that this copyright notice appears in all copies. For
    1.14 + * precise terms see the accompanying LICENSE file.
    1.15 + *
    1.16 + * This software is provided "AS IS" with no warranty of any kind,
    1.17 + * express or implied, and with no claim as to its suitability for any
    1.18 + * purpose.
    1.19 + *
    1.20 + */
    1.21 +
    1.22 +#ifndef LEMON_BINOMIAL_HEAP_H
    1.23 +#define LEMON_BINOMIAL_HEAP_H
    1.24 +
    1.25 +///\file
    1.26 +///\ingroup heaps
    1.27 +///\brief Binomial Heap implementation.
    1.28 +
    1.29 +#include <vector>
    1.30 +#include <utility>
    1.31 +#include <functional>
    1.32 +#include <lemon/math.h>
    1.33 +#include <lemon/counter.h>
    1.34 +
    1.35 +namespace lemon {
    1.36 +
    1.37 +  /// \ingroup heaps
    1.38 +  ///
    1.39 +  ///\brief Binomial heap data structure.
    1.40 +  ///
    1.41 +  /// This class implements the \e binomial \e heap data structure.
    1.42 +  /// It fully conforms to the \ref concepts::Heap "heap concept".
    1.43 +  ///
    1.44 +  /// The methods \ref increase() and \ref erase() are not efficient
    1.45 +  /// in a binomial heap. In case of many calls of these operations,
    1.46 +  /// it is better to use other heap structure, e.g. \ref BinHeap
    1.47 +  /// "binary heap".
    1.48 +  ///
    1.49 +  /// \tparam PR Type of the priorities of the items.
    1.50 +  /// \tparam IM A read-writable item map with \c int values, used
    1.51 +  /// internally to handle the cross references.
    1.52 +  /// \tparam CMP A functor class for comparing the priorities.
    1.53 +  /// The default is \c std::less<PR>.
    1.54 +#ifdef DOXYGEN
    1.55 +  template <typename PR, typename IM, typename CMP>
    1.56 +#else
    1.57 +  template <typename PR, typename IM, typename CMP = std::less<PR> >
    1.58 +#endif
    1.59 +  class BinomialHeap {
    1.60 +  public:
    1.61 +    /// Type of the item-int map.
    1.62 +    typedef IM ItemIntMap;
    1.63 +    /// Type of the priorities.
    1.64 +    typedef PR Prio;
    1.65 +    /// Type of the items stored in the heap.
    1.66 +    typedef typename ItemIntMap::Key Item;
    1.67 +    /// Functor type for comparing the priorities.
    1.68 +    typedef CMP Compare;
    1.69 +
    1.70 +    /// \brief Type to represent the states of the items.
    1.71 +    ///
    1.72 +    /// Each item has a state associated to it. It can be "in heap",
    1.73 +    /// "pre-heap" or "post-heap". The latter two are indifferent from the
    1.74 +    /// heap's point of view, but may be useful to the user.
    1.75 +    ///
    1.76 +    /// The item-int map must be initialized in such way that it assigns
    1.77 +    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
    1.78 +    enum State {
    1.79 +      IN_HEAP = 0,    ///< = 0.
    1.80 +      PRE_HEAP = -1,  ///< = -1.
    1.81 +      POST_HEAP = -2  ///< = -2.
    1.82 +    };
    1.83 +
    1.84 +  private:
    1.85 +    class Store;
    1.86 +
    1.87 +    std::vector<Store> _data;
    1.88 +    int _min, _head;
    1.89 +    ItemIntMap &_iim;
    1.90 +    Compare _comp;
    1.91 +    int _num_items;
    1.92 +
    1.93 +  public:
    1.94 +    /// \brief Constructor.
    1.95 +    ///
    1.96 +    /// Constructor.
    1.97 +    /// \param map A map that assigns \c int values to the items.
    1.98 +    /// It is used internally to handle the cross references.
    1.99 +    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
   1.100 +    explicit BinomialHeap(ItemIntMap &map)
   1.101 +      : _min(0), _head(-1), _iim(map), _num_items(0) {}
   1.102 +
   1.103 +    /// \brief Constructor.
   1.104 +    ///
   1.105 +    /// Constructor.
   1.106 +    /// \param map A map that assigns \c int values to the items.
   1.107 +    /// It is used internally to handle the cross references.
   1.108 +    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
   1.109 +    /// \param comp The function object used for comparing the priorities.
   1.110 +    BinomialHeap(ItemIntMap &map, const Compare &comp)
   1.111 +      : _min(0), _head(-1), _iim(map), _comp(comp), _num_items(0) {}
   1.112 +
   1.113 +    /// \brief The number of items stored in the heap.
   1.114 +    ///
   1.115 +    /// This function returns the number of items stored in the heap.
   1.116 +    int size() const { return _num_items; }
   1.117 +
   1.118 +    /// \brief Check if the heap is empty.
   1.119 +    ///
   1.120 +    /// This function returns \c true if the heap is empty.
   1.121 +    bool empty() const { return _num_items==0; }
   1.122 +
   1.123 +    /// \brief Make the heap empty.
   1.124 +    ///
   1.125 +    /// This functon makes the heap empty.
   1.126 +    /// It does not change the cross reference map. If you want to reuse
   1.127 +    /// a heap that is not surely empty, you should first clear it and
   1.128 +    /// then you should set the cross reference map to \c PRE_HEAP
   1.129 +    /// for each item.
   1.130 +    void clear() {
   1.131 +      _data.clear(); _min=0; _num_items=0; _head=-1;
   1.132 +    }
   1.133 +
   1.134 +    /// \brief Set the priority of an item or insert it, if it is
   1.135 +    /// not stored in the heap.
   1.136 +    ///
   1.137 +    /// This method sets the priority of the given item if it is
   1.138 +    /// already stored in the heap. Otherwise it inserts the given
   1.139 +    /// item into the heap with the given priority.
   1.140 +    /// \param item The item.
   1.141 +    /// \param value The priority.
   1.142 +    void set (const Item& item, const Prio& value) {
   1.143 +      int i=_iim[item];
   1.144 +      if ( i >= 0 && _data[i].in ) {
   1.145 +        if ( _comp(value, _data[i].prio) ) decrease(item, value);
   1.146 +        if ( _comp(_data[i].prio, value) ) increase(item, value);
   1.147 +      } else push(item, value);
   1.148 +    }
   1.149 +
   1.150 +    /// \brief Insert an item into the heap with the given priority.
   1.151 +    ///
   1.152 +    /// This function inserts the given item into the heap with the
   1.153 +    /// given priority.
   1.154 +    /// \param item The item to insert.
   1.155 +    /// \param value The priority of the item.
   1.156 +    /// \pre \e item must not be stored in the heap.
   1.157 +    void push (const Item& item, const Prio& value) {
   1.158 +      int i=_iim[item];
   1.159 +      if ( i<0 ) {
   1.160 +        int s=_data.size();
   1.161 +        _iim.set( item,s );
   1.162 +        Store st;
   1.163 +        st.name=item;
   1.164 +        st.prio=value;
   1.165 +        _data.push_back(st);
   1.166 +        i=s;
   1.167 +      }
   1.168 +      else {
   1.169 +        _data[i].parent=_data[i].right_neighbor=_data[i].child=-1;
   1.170 +        _data[i].degree=0;
   1.171 +        _data[i].in=true;
   1.172 +        _data[i].prio=value;
   1.173 +      }
   1.174 +
   1.175 +      if( 0==_num_items ) {
   1.176 +        _head=i;
   1.177 +        _min=i;
   1.178 +      } else {
   1.179 +        merge(i);
   1.180 +        if( _comp(_data[i].prio, _data[_min].prio) ) _min=i;
   1.181 +      }
   1.182 +      ++_num_items;
   1.183 +    }
   1.184 +
   1.185 +    /// \brief Return the item having minimum priority.
   1.186 +    ///
   1.187 +    /// This function returns the item having minimum priority.
   1.188 +    /// \pre The heap must be non-empty.
   1.189 +    Item top() const { return _data[_min].name; }
   1.190 +
   1.191 +    /// \brief The minimum priority.
   1.192 +    ///
   1.193 +    /// This function returns the minimum priority.
   1.194 +    /// \pre The heap must be non-empty.
   1.195 +    Prio prio() const { return _data[_min].prio; }
   1.196 +
   1.197 +    /// \brief The priority of the given item.
   1.198 +    ///
   1.199 +    /// This function returns the priority of the given item.
   1.200 +    /// \param item The item.
   1.201 +    /// \pre \e item must be in the heap.
   1.202 +    const Prio& operator[](const Item& item) const {
   1.203 +      return _data[_iim[item]].prio;
   1.204 +    }
   1.205 +
   1.206 +    /// \brief Remove the item having minimum priority.
   1.207 +    ///
   1.208 +    /// This function removes the item having minimum priority.
   1.209 +    /// \pre The heap must be non-empty.
   1.210 +    void pop() {
   1.211 +      _data[_min].in=false;
   1.212 +
   1.213 +      int head_child=-1;
   1.214 +      if ( _data[_min].child!=-1 ) {
   1.215 +        int child=_data[_min].child;
   1.216 +        int neighb;
   1.217 +        while( child!=-1 ) {
   1.218 +          neighb=_data[child].right_neighbor;
   1.219 +          _data[child].parent=-1;
   1.220 +          _data[child].right_neighbor=head_child;
   1.221 +          head_child=child;
   1.222 +          child=neighb;
   1.223 +        }
   1.224 +      }
   1.225 +
   1.226 +      if ( _data[_head].right_neighbor==-1 ) {
   1.227 +        // there was only one root
   1.228 +        _head=head_child;
   1.229 +      }
   1.230 +      else {
   1.231 +        // there were more roots
   1.232 +        if( _head!=_min )  { unlace(_min); }
   1.233 +        else { _head=_data[_head].right_neighbor; }
   1.234 +        merge(head_child);
   1.235 +      }
   1.236 +      _min=findMin();
   1.237 +      --_num_items;
   1.238 +    }
   1.239 +
   1.240 +    /// \brief Remove the given item from the heap.
   1.241 +    ///
   1.242 +    /// This function removes the given item from the heap if it is
   1.243 +    /// already stored.
   1.244 +    /// \param item The item to delete.
   1.245 +    /// \pre \e item must be in the heap.
   1.246 +    void erase (const Item& item) {
   1.247 +      int i=_iim[item];
   1.248 +      if ( i >= 0 && _data[i].in ) {
   1.249 +        decrease( item, _data[_min].prio-1 );
   1.250 +        pop();
   1.251 +      }
   1.252 +    }
   1.253 +
   1.254 +    /// \brief Decrease the priority of an item to the given value.
   1.255 +    ///
   1.256 +    /// This function decreases the priority of an item to the given value.
   1.257 +    /// \param item The item.
   1.258 +    /// \param value The priority.
   1.259 +    /// \pre \e item must be stored in the heap with priority at least \e value.
   1.260 +    void decrease (Item item, const Prio& value) {
   1.261 +      int i=_iim[item];
   1.262 +      int p=_data[i].parent;
   1.263 +      _data[i].prio=value;
   1.264 +
   1.265 +      while( p!=-1 && _comp(value, _data[p].prio) ) {
   1.266 +        _data[i].name=_data[p].name;
   1.267 +        _data[i].prio=_data[p].prio;
   1.268 +        _data[p].name=item;
   1.269 +        _data[p].prio=value;
   1.270 +        _iim[_data[i].name]=i;
   1.271 +        i=p;
   1.272 +        p=_data[p].parent;
   1.273 +      }
   1.274 +      _iim[item]=i;
   1.275 +      if ( _comp(value, _data[_min].prio) ) _min=i;
   1.276 +    }
   1.277 +
   1.278 +    /// \brief Increase the priority of an item to the given value.
   1.279 +    ///
   1.280 +    /// This function increases the priority of an item to the given value.
   1.281 +    /// \param item The item.
   1.282 +    /// \param value The priority.
   1.283 +    /// \pre \e item must be stored in the heap with priority at most \e value.
   1.284 +    void increase (Item item, const Prio& value) {
   1.285 +      erase(item);
   1.286 +      push(item, value);
   1.287 +    }
   1.288 +
   1.289 +    /// \brief Return the state of an item.
   1.290 +    ///
   1.291 +    /// This method returns \c PRE_HEAP if the given item has never
   1.292 +    /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
   1.293 +    /// and \c POST_HEAP otherwise.
   1.294 +    /// In the latter case it is possible that the item will get back
   1.295 +    /// to the heap again.
   1.296 +    /// \param item The item.
   1.297 +    State state(const Item &item) const {
   1.298 +      int i=_iim[item];
   1.299 +      if( i>=0 ) {
   1.300 +        if ( _data[i].in ) i=0;
   1.301 +        else i=-2;
   1.302 +      }
   1.303 +      return State(i);
   1.304 +    }
   1.305 +
   1.306 +    /// \brief Set the state of an item in the heap.
   1.307 +    ///
   1.308 +    /// This function sets the state of the given item in the heap.
   1.309 +    /// It can be used to manually clear the heap when it is important
   1.310 +    /// to achive better time complexity.
   1.311 +    /// \param i The item.
   1.312 +    /// \param st The state. It should not be \c IN_HEAP.
   1.313 +    void state(const Item& i, State st) {
   1.314 +      switch (st) {
   1.315 +      case POST_HEAP:
   1.316 +      case PRE_HEAP:
   1.317 +        if (state(i) == IN_HEAP) {
   1.318 +          erase(i);
   1.319 +        }
   1.320 +        _iim[i] = st;
   1.321 +        break;
   1.322 +      case IN_HEAP:
   1.323 +        break;
   1.324 +      }
   1.325 +    }
   1.326 +
   1.327 +  private:
   1.328 +
   1.329 +    // Find the minimum of the roots
   1.330 +    int findMin() {
   1.331 +      if( _head!=-1 ) {
   1.332 +        int min_loc=_head, min_val=_data[_head].prio;
   1.333 +        for( int x=_data[_head].right_neighbor; x!=-1;
   1.334 +             x=_data[x].right_neighbor ) {
   1.335 +          if( _comp( _data[x].prio,min_val ) ) {
   1.336 +            min_val=_data[x].prio;
   1.337 +            min_loc=x;
   1.338 +          }
   1.339 +        }
   1.340 +        return min_loc;
   1.341 +      }
   1.342 +      else return -1;
   1.343 +    }
   1.344 +
   1.345 +    // Merge the heap with another heap starting at the given position
   1.346 +    void merge(int a) {
   1.347 +      if( _head==-1 || a==-1 ) return;
   1.348 +      if( _data[a].right_neighbor==-1 &&
   1.349 +          _data[a].degree<=_data[_head].degree ) {
   1.350 +        _data[a].right_neighbor=_head;
   1.351 +        _head=a;
   1.352 +      } else {
   1.353 +        interleave(a);
   1.354 +      }
   1.355 +      if( _data[_head].right_neighbor==-1 ) return;
   1.356 +
   1.357 +      int x=_head;
   1.358 +      int x_prev=-1, x_next=_data[x].right_neighbor;
   1.359 +      while( x_next!=-1 ) {
   1.360 +        if( _data[x].degree!=_data[x_next].degree ||
   1.361 +            ( _data[x_next].right_neighbor!=-1 &&
   1.362 +              _data[_data[x_next].right_neighbor].degree==_data[x].degree ) ) {
   1.363 +          x_prev=x;
   1.364 +          x=x_next;
   1.365 +        }
   1.366 +        else {
   1.367 +          if( _comp(_data[x_next].prio,_data[x].prio) ) {
   1.368 +            if( x_prev==-1 ) {
   1.369 +              _head=x_next;
   1.370 +            } else {
   1.371 +              _data[x_prev].right_neighbor=x_next;
   1.372 +            }
   1.373 +            fuse(x,x_next);
   1.374 +            x=x_next;
   1.375 +          }
   1.376 +          else {
   1.377 +            _data[x].right_neighbor=_data[x_next].right_neighbor;
   1.378 +            fuse(x_next,x);
   1.379 +          }
   1.380 +        }
   1.381 +        x_next=_data[x].right_neighbor;
   1.382 +      }
   1.383 +    }
   1.384 +
   1.385 +    // Interleave the elements of the given list into the list of the roots
   1.386 +    void interleave(int a) {
   1.387 +      int p=_head, q=a;
   1.388 +      int curr=_data.size();
   1.389 +      _data.push_back(Store());
   1.390 +
   1.391 +      while( p!=-1 || q!=-1 ) {
   1.392 +        if( q==-1 || ( p!=-1 && _data[p].degree<_data[q].degree ) ) {
   1.393 +          _data[curr].right_neighbor=p;
   1.394 +          curr=p;
   1.395 +          p=_data[p].right_neighbor;
   1.396 +        }
   1.397 +        else {
   1.398 +          _data[curr].right_neighbor=q;
   1.399 +          curr=q;
   1.400 +          q=_data[q].right_neighbor;
   1.401 +        }
   1.402 +      }
   1.403 +
   1.404 +      _head=_data.back().right_neighbor;
   1.405 +      _data.pop_back();
   1.406 +    }
   1.407 +
   1.408 +    // Lace node a under node b
   1.409 +    void fuse(int a, int b) {
   1.410 +      _data[a].parent=b;
   1.411 +      _data[a].right_neighbor=_data[b].child;
   1.412 +      _data[b].child=a;
   1.413 +
   1.414 +      ++_data[b].degree;
   1.415 +    }
   1.416 +
   1.417 +    // Unlace node a (if it has siblings)
   1.418 +    void unlace(int a) {
   1.419 +      int neighb=_data[a].right_neighbor;
   1.420 +      int other=_head;
   1.421 +
   1.422 +      while( _data[other].right_neighbor!=a )
   1.423 +        other=_data[other].right_neighbor;
   1.424 +      _data[other].right_neighbor=neighb;
   1.425 +    }
   1.426 +
   1.427 +  private:
   1.428 +
   1.429 +    class Store {
   1.430 +      friend class BinomialHeap;
   1.431 +
   1.432 +      Item name;
   1.433 +      int parent;
   1.434 +      int right_neighbor;
   1.435 +      int child;
   1.436 +      int degree;
   1.437 +      bool in;
   1.438 +      Prio prio;
   1.439 +
   1.440 +      Store() : parent(-1), right_neighbor(-1), child(-1), degree(0),
   1.441 +        in(true) {}
   1.442 +    };
   1.443 +  };
   1.444 +
   1.445 +} //namespace lemon
   1.446 +
   1.447 +#endif //LEMON_BINOMIAL_HEAP_H
   1.448 +