lemon/fib_heap.h
changeset 784 1a7fe3bef514
parent 710 f1fe0ddad6f7
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/fib_heap.h	Thu Nov 05 15:50:01 2009 +0100
     1.3 @@ -0,0 +1,475 @@
     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-2009
     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_FIB_HEAP_H
    1.23 +#define LEMON_FIB_HEAP_H
    1.24 +
    1.25 +///\file
    1.26 +///\ingroup heaps
    1.27 +///\brief Fibonacci heap implementation.
    1.28 +
    1.29 +#include <vector>
    1.30 +#include <utility>
    1.31 +#include <functional>
    1.32 +#include <lemon/math.h>
    1.33 +
    1.34 +namespace lemon {
    1.35 +
    1.36 +  /// \ingroup heaps
    1.37 +  ///
    1.38 +  /// \brief Fibonacci heap data structure.
    1.39 +  ///
    1.40 +  /// This class implements the \e Fibonacci \e heap data structure.
    1.41 +  /// It fully conforms to the \ref concepts::Heap "heap concept".
    1.42 +  ///
    1.43 +  /// The methods \ref increase() and \ref erase() are not efficient in a
    1.44 +  /// Fibonacci heap. In case of many calls of these operations, it is
    1.45 +  /// better to use other heap structure, e.g. \ref BinHeap "binary heap".
    1.46 +  ///
    1.47 +  /// \tparam PR Type of the priorities of the items.
    1.48 +  /// \tparam IM A read-writable item map with \c int values, used
    1.49 +  /// internally to handle the cross references.
    1.50 +  /// \tparam CMP A functor class for comparing the priorities.
    1.51 +  /// The default is \c std::less<PR>.
    1.52 +#ifdef DOXYGEN
    1.53 +  template <typename PR, typename IM, typename CMP>
    1.54 +#else
    1.55 +  template <typename PR, typename IM, typename CMP = std::less<PR> >
    1.56 +#endif
    1.57 +  class FibHeap {
    1.58 +  public:
    1.59 +
    1.60 +    /// Type of the item-int map.
    1.61 +    typedef IM ItemIntMap;
    1.62 +    /// Type of the priorities.
    1.63 +    typedef PR Prio;
    1.64 +    /// Type of the items stored in the heap.
    1.65 +    typedef typename ItemIntMap::Key Item;
    1.66 +    /// Type of the item-priority pairs.
    1.67 +    typedef std::pair<Item,Prio> Pair;
    1.68 +    /// Functor type for comparing the priorities.
    1.69 +    typedef CMP Compare;
    1.70 +
    1.71 +  private:
    1.72 +    class Store;
    1.73 +
    1.74 +    std::vector<Store> _data;
    1.75 +    int _minimum;
    1.76 +    ItemIntMap &_iim;
    1.77 +    Compare _comp;
    1.78 +    int _num;
    1.79 +
    1.80 +  public:
    1.81 +
    1.82 +    /// \brief Type to represent the states of the items.
    1.83 +    ///
    1.84 +    /// Each item has a state associated to it. It can be "in heap",
    1.85 +    /// "pre-heap" or "post-heap". The latter two are indifferent from the
    1.86 +    /// heap's point of view, but may be useful to the user.
    1.87 +    ///
    1.88 +    /// The item-int map must be initialized in such way that it assigns
    1.89 +    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
    1.90 +    enum State {
    1.91 +      IN_HEAP = 0,    ///< = 0.
    1.92 +      PRE_HEAP = -1,  ///< = -1.
    1.93 +      POST_HEAP = -2  ///< = -2.
    1.94 +    };
    1.95 +
    1.96 +    /// \brief Constructor.
    1.97 +    ///
    1.98 +    /// Constructor.
    1.99 +    /// \param map A map that assigns \c int values to the items.
   1.100 +    /// It is used internally to handle the cross references.
   1.101 +    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
   1.102 +    explicit FibHeap(ItemIntMap &map)
   1.103 +      : _minimum(0), _iim(map), _num() {}
   1.104 +
   1.105 +    /// \brief Constructor.
   1.106 +    ///
   1.107 +    /// Constructor.
   1.108 +    /// \param map A map that assigns \c int values to the items.
   1.109 +    /// It is used internally to handle the cross references.
   1.110 +    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
   1.111 +    /// \param comp The function object used for comparing the priorities.
   1.112 +    FibHeap(ItemIntMap &map, const Compare &comp)
   1.113 +      : _minimum(0), _iim(map), _comp(comp), _num() {}
   1.114 +
   1.115 +    /// \brief The number of items stored in the heap.
   1.116 +    ///
   1.117 +    /// This function returns the number of items stored in the heap.
   1.118 +    int size() const { return _num; }
   1.119 +
   1.120 +    /// \brief Check if the heap is empty.
   1.121 +    ///
   1.122 +    /// This function returns \c true if the heap is empty.
   1.123 +    bool empty() const { return _num==0; }
   1.124 +
   1.125 +    /// \brief Make the heap empty.
   1.126 +    ///
   1.127 +    /// This functon makes the heap empty.
   1.128 +    /// It does not change the cross reference map. If you want to reuse
   1.129 +    /// a heap that is not surely empty, you should first clear it and
   1.130 +    /// then you should set the cross reference map to \c PRE_HEAP
   1.131 +    /// for each item.
   1.132 +    void clear() {
   1.133 +      _data.clear(); _minimum = 0; _num = 0;
   1.134 +    }
   1.135 +
   1.136 +    /// \brief Insert an item into the heap with the given priority.
   1.137 +    ///
   1.138 +    /// This function inserts the given item into the heap with the
   1.139 +    /// given priority.
   1.140 +    /// \param item The item to insert.
   1.141 +    /// \param prio The priority of the item.
   1.142 +    /// \pre \e item must not be stored in the heap.
   1.143 +    void push (const Item& item, const Prio& prio) {
   1.144 +      int i=_iim[item];
   1.145 +      if ( i < 0 ) {
   1.146 +        int s=_data.size();
   1.147 +        _iim.set( item, s );
   1.148 +        Store st;
   1.149 +        st.name=item;
   1.150 +        _data.push_back(st);
   1.151 +        i=s;
   1.152 +      } else {
   1.153 +        _data[i].parent=_data[i].child=-1;
   1.154 +        _data[i].degree=0;
   1.155 +        _data[i].in=true;
   1.156 +        _data[i].marked=false;
   1.157 +      }
   1.158 +
   1.159 +      if ( _num ) {
   1.160 +        _data[_data[_minimum].right_neighbor].left_neighbor=i;
   1.161 +        _data[i].right_neighbor=_data[_minimum].right_neighbor;
   1.162 +        _data[_minimum].right_neighbor=i;
   1.163 +        _data[i].left_neighbor=_minimum;
   1.164 +        if ( _comp( prio, _data[_minimum].prio) ) _minimum=i;
   1.165 +      } else {
   1.166 +        _data[i].right_neighbor=_data[i].left_neighbor=i;
   1.167 +        _minimum=i;
   1.168 +      }
   1.169 +      _data[i].prio=prio;
   1.170 +      ++_num;
   1.171 +    }
   1.172 +
   1.173 +    /// \brief Return the item having minimum priority.
   1.174 +    ///
   1.175 +    /// This function returns the item having minimum priority.
   1.176 +    /// \pre The heap must be non-empty.
   1.177 +    Item top() const { return _data[_minimum].name; }
   1.178 +
   1.179 +    /// \brief The minimum priority.
   1.180 +    ///
   1.181 +    /// This function returns the minimum priority.
   1.182 +    /// \pre The heap must be non-empty.
   1.183 +    Prio prio() const { return _data[_minimum].prio; }
   1.184 +
   1.185 +    /// \brief Remove the item having minimum priority.
   1.186 +    ///
   1.187 +    /// This function removes the item having minimum priority.
   1.188 +    /// \pre The heap must be non-empty.
   1.189 +    void pop() {
   1.190 +      /*The first case is that there are only one root.*/
   1.191 +      if ( _data[_minimum].left_neighbor==_minimum ) {
   1.192 +        _data[_minimum].in=false;
   1.193 +        if ( _data[_minimum].degree!=0 ) {
   1.194 +          makeRoot(_data[_minimum].child);
   1.195 +          _minimum=_data[_minimum].child;
   1.196 +          balance();
   1.197 +        }
   1.198 +      } else {
   1.199 +        int right=_data[_minimum].right_neighbor;
   1.200 +        unlace(_minimum);
   1.201 +        _data[_minimum].in=false;
   1.202 +        if ( _data[_minimum].degree > 0 ) {
   1.203 +          int left=_data[_minimum].left_neighbor;
   1.204 +          int child=_data[_minimum].child;
   1.205 +          int last_child=_data[child].left_neighbor;
   1.206 +
   1.207 +          makeRoot(child);
   1.208 +
   1.209 +          _data[left].right_neighbor=child;
   1.210 +          _data[child].left_neighbor=left;
   1.211 +          _data[right].left_neighbor=last_child;
   1.212 +          _data[last_child].right_neighbor=right;
   1.213 +        }
   1.214 +        _minimum=right;
   1.215 +        balance();
   1.216 +      } // the case where there are more roots
   1.217 +      --_num;
   1.218 +    }
   1.219 +
   1.220 +    /// \brief Remove the given item from the heap.
   1.221 +    ///
   1.222 +    /// This function removes the given item from the heap if it is
   1.223 +    /// already stored.
   1.224 +    /// \param item The item to delete.
   1.225 +    /// \pre \e item must be in the heap.
   1.226 +    void erase (const Item& item) {
   1.227 +      int i=_iim[item];
   1.228 +
   1.229 +      if ( i >= 0 && _data[i].in ) {
   1.230 +        if ( _data[i].parent!=-1 ) {
   1.231 +          int p=_data[i].parent;
   1.232 +          cut(i,p);
   1.233 +          cascade(p);
   1.234 +        }
   1.235 +        _minimum=i;     //As if its prio would be -infinity
   1.236 +        pop();
   1.237 +      }
   1.238 +    }
   1.239 +
   1.240 +    /// \brief The priority of the given item.
   1.241 +    ///
   1.242 +    /// This function returns the priority of the given item.
   1.243 +    /// \param item The item.
   1.244 +    /// \pre \e item must be in the heap.
   1.245 +    Prio operator[](const Item& item) const {
   1.246 +      return _data[_iim[item]].prio;
   1.247 +    }
   1.248 +
   1.249 +    /// \brief Set the priority of an item or insert it, if it is
   1.250 +    /// not stored in the heap.
   1.251 +    ///
   1.252 +    /// This method sets the priority of the given item if it is
   1.253 +    /// already stored in the heap. Otherwise it inserts the given
   1.254 +    /// item into the heap with the given priority.
   1.255 +    /// \param item The item.
   1.256 +    /// \param prio The priority.
   1.257 +    void set (const Item& item, const Prio& prio) {
   1.258 +      int i=_iim[item];
   1.259 +      if ( i >= 0 && _data[i].in ) {
   1.260 +        if ( _comp(prio, _data[i].prio) ) decrease(item, prio);
   1.261 +        if ( _comp(_data[i].prio, prio) ) increase(item, prio);
   1.262 +      } else push(item, prio);
   1.263 +    }
   1.264 +
   1.265 +    /// \brief Decrease the priority of an item to the given value.
   1.266 +    ///
   1.267 +    /// This function decreases the priority of an item to the given value.
   1.268 +    /// \param item The item.
   1.269 +    /// \param prio The priority.
   1.270 +    /// \pre \e item must be stored in the heap with priority at least \e prio.
   1.271 +    void decrease (const Item& item, const Prio& prio) {
   1.272 +      int i=_iim[item];
   1.273 +      _data[i].prio=prio;
   1.274 +      int p=_data[i].parent;
   1.275 +
   1.276 +      if ( p!=-1 && _comp(prio, _data[p].prio) ) {
   1.277 +        cut(i,p);
   1.278 +        cascade(p);
   1.279 +      }
   1.280 +      if ( _comp(prio, _data[_minimum].prio) ) _minimum=i;
   1.281 +    }
   1.282 +
   1.283 +    /// \brief Increase the priority of an item to the given value.
   1.284 +    ///
   1.285 +    /// This function increases the priority of an item to the given value.
   1.286 +    /// \param item The item.
   1.287 +    /// \param prio The priority.
   1.288 +    /// \pre \e item must be stored in the heap with priority at most \e prio.
   1.289 +    void increase (const Item& item, const Prio& prio) {
   1.290 +      erase(item);
   1.291 +      push(item, prio);
   1.292 +    }
   1.293 +
   1.294 +    /// \brief Return the state of an item.
   1.295 +    ///
   1.296 +    /// This method returns \c PRE_HEAP if the given item has never
   1.297 +    /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
   1.298 +    /// and \c POST_HEAP otherwise.
   1.299 +    /// In the latter case it is possible that the item will get back
   1.300 +    /// to the heap again.
   1.301 +    /// \param item The item.
   1.302 +    State state(const Item &item) const {
   1.303 +      int i=_iim[item];
   1.304 +      if( i>=0 ) {
   1.305 +        if ( _data[i].in ) i=0;
   1.306 +        else i=-2;
   1.307 +      }
   1.308 +      return State(i);
   1.309 +    }
   1.310 +
   1.311 +    /// \brief Set the state of an item in the heap.
   1.312 +    ///
   1.313 +    /// This function sets the state of the given item in the heap.
   1.314 +    /// It can be used to manually clear the heap when it is important
   1.315 +    /// to achive better time complexity.
   1.316 +    /// \param i The item.
   1.317 +    /// \param st The state. It should not be \c IN_HEAP.
   1.318 +    void state(const Item& i, State st) {
   1.319 +      switch (st) {
   1.320 +      case POST_HEAP:
   1.321 +      case PRE_HEAP:
   1.322 +        if (state(i) == IN_HEAP) {
   1.323 +          erase(i);
   1.324 +        }
   1.325 +        _iim[i] = st;
   1.326 +        break;
   1.327 +      case IN_HEAP:
   1.328 +        break;
   1.329 +      }
   1.330 +    }
   1.331 +
   1.332 +  private:
   1.333 +
   1.334 +    void balance() {
   1.335 +
   1.336 +      int maxdeg=int( std::floor( 2.08*log(double(_data.size()))))+1;
   1.337 +
   1.338 +      std::vector<int> A(maxdeg,-1);
   1.339 +
   1.340 +      /*
   1.341 +       *Recall that now minimum does not point to the minimum prio element.
   1.342 +       *We set minimum to this during balance().
   1.343 +       */
   1.344 +      int anchor=_data[_minimum].left_neighbor;
   1.345 +      int next=_minimum;
   1.346 +      bool end=false;
   1.347 +
   1.348 +      do {
   1.349 +        int active=next;
   1.350 +        if ( anchor==active ) end=true;
   1.351 +        int d=_data[active].degree;
   1.352 +        next=_data[active].right_neighbor;
   1.353 +
   1.354 +        while (A[d]!=-1) {
   1.355 +          if( _comp(_data[active].prio, _data[A[d]].prio) ) {
   1.356 +            fuse(active,A[d]);
   1.357 +          } else {
   1.358 +            fuse(A[d],active);
   1.359 +            active=A[d];
   1.360 +          }
   1.361 +          A[d]=-1;
   1.362 +          ++d;
   1.363 +        }
   1.364 +        A[d]=active;
   1.365 +      } while ( !end );
   1.366 +
   1.367 +
   1.368 +      while ( _data[_minimum].parent >=0 )
   1.369 +        _minimum=_data[_minimum].parent;
   1.370 +      int s=_minimum;
   1.371 +      int m=_minimum;
   1.372 +      do {
   1.373 +        if ( _comp(_data[s].prio, _data[_minimum].prio) ) _minimum=s;
   1.374 +        s=_data[s].right_neighbor;
   1.375 +      } while ( s != m );
   1.376 +    }
   1.377 +
   1.378 +    void makeRoot(int c) {
   1.379 +      int s=c;
   1.380 +      do {
   1.381 +        _data[s].parent=-1;
   1.382 +        s=_data[s].right_neighbor;
   1.383 +      } while ( s != c );
   1.384 +    }
   1.385 +
   1.386 +    void cut(int a, int b) {
   1.387 +      /*
   1.388 +       *Replacing a from the children of b.
   1.389 +       */
   1.390 +      --_data[b].degree;
   1.391 +
   1.392 +      if ( _data[b].degree !=0 ) {
   1.393 +        int child=_data[b].child;
   1.394 +        if ( child==a )
   1.395 +          _data[b].child=_data[child].right_neighbor;
   1.396 +        unlace(a);
   1.397 +      }
   1.398 +
   1.399 +
   1.400 +      /*Lacing a to the roots.*/
   1.401 +      int right=_data[_minimum].right_neighbor;
   1.402 +      _data[_minimum].right_neighbor=a;
   1.403 +      _data[a].left_neighbor=_minimum;
   1.404 +      _data[a].right_neighbor=right;
   1.405 +      _data[right].left_neighbor=a;
   1.406 +
   1.407 +      _data[a].parent=-1;
   1.408 +      _data[a].marked=false;
   1.409 +    }
   1.410 +
   1.411 +    void cascade(int a) {
   1.412 +      if ( _data[a].parent!=-1 ) {
   1.413 +        int p=_data[a].parent;
   1.414 +
   1.415 +        if ( _data[a].marked==false ) _data[a].marked=true;
   1.416 +        else {
   1.417 +          cut(a,p);
   1.418 +          cascade(p);
   1.419 +        }
   1.420 +      }
   1.421 +    }
   1.422 +
   1.423 +    void fuse(int a, int b) {
   1.424 +      unlace(b);
   1.425 +
   1.426 +      /*Lacing b under a.*/
   1.427 +      _data[b].parent=a;
   1.428 +
   1.429 +      if (_data[a].degree==0) {
   1.430 +        _data[b].left_neighbor=b;
   1.431 +        _data[b].right_neighbor=b;
   1.432 +        _data[a].child=b;
   1.433 +      } else {
   1.434 +        int child=_data[a].child;
   1.435 +        int last_child=_data[child].left_neighbor;
   1.436 +        _data[child].left_neighbor=b;
   1.437 +        _data[b].right_neighbor=child;
   1.438 +        _data[last_child].right_neighbor=b;
   1.439 +        _data[b].left_neighbor=last_child;
   1.440 +      }
   1.441 +
   1.442 +      ++_data[a].degree;
   1.443 +
   1.444 +      _data[b].marked=false;
   1.445 +    }
   1.446 +
   1.447 +    /*
   1.448 +     *It is invoked only if a has siblings.
   1.449 +     */
   1.450 +    void unlace(int a) {
   1.451 +      int leftn=_data[a].left_neighbor;
   1.452 +      int rightn=_data[a].right_neighbor;
   1.453 +      _data[leftn].right_neighbor=rightn;
   1.454 +      _data[rightn].left_neighbor=leftn;
   1.455 +    }
   1.456 +
   1.457 +
   1.458 +    class Store {
   1.459 +      friend class FibHeap;
   1.460 +
   1.461 +      Item name;
   1.462 +      int parent;
   1.463 +      int left_neighbor;
   1.464 +      int right_neighbor;
   1.465 +      int child;
   1.466 +      int degree;
   1.467 +      bool marked;
   1.468 +      bool in;
   1.469 +      Prio prio;
   1.470 +
   1.471 +      Store() : parent(-1), child(-1), degree(), marked(false), in(true) {}
   1.472 +    };
   1.473 +  };
   1.474 +
   1.475 +} //namespace lemon
   1.476 +
   1.477 +#endif //LEMON_FIB_HEAP_H
   1.478 +