lemon/fib_heap.h
changeset 728 532697c9fa53
child 730 9f529abcaebf
equal deleted inserted replaced
-1:000000000000 0:ecddf211311d
       
     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_FIB_HEAP_H
       
    20 #define LEMON_FIB_HEAP_H
       
    21 
       
    22 ///\file
       
    23 ///\ingroup auxdat
       
    24 ///\brief Fibonacci Heap implementation.
       
    25 
       
    26 #include <vector>
       
    27 #include <functional>
       
    28 #include <lemon/math.h>
       
    29 
       
    30 namespace lemon {
       
    31 
       
    32   /// \ingroup auxdat
       
    33   ///
       
    34   ///\brief Fibonacci Heap.
       
    35   ///
       
    36   ///This class implements the \e Fibonacci \e heap data structure. A \e heap
       
    37   ///is a data structure for storing items with specified values called \e
       
    38   ///priorities in such a way that finding the item with minimum priority is
       
    39   ///efficient. \c Compare specifies the ordering of the priorities. In a heap
       
    40   ///one can change the priority of an item, add or erase an item, etc.
       
    41   ///
       
    42   ///The methods \ref increase and \ref erase are not efficient in a Fibonacci
       
    43   ///heap. In case of many calls to these operations, it is better to use a
       
    44   ///\ref BinHeap "binary heap".
       
    45   ///
       
    46   ///\param _Prio Type of the priority of the items.
       
    47   ///\param _ItemIntMap A read and writable Item int map, used internally
       
    48   ///to handle the cross references.
       
    49   ///\param _Compare A class for the ordering of the priorities. The
       
    50   ///default is \c std::less<_Prio>.
       
    51   ///
       
    52   ///\sa BinHeap
       
    53   ///\sa Dijkstra
       
    54 #ifdef DOXYGEN
       
    55   template <typename _Prio,
       
    56             typename _ItemIntMap,
       
    57             typename _Compare>
       
    58 #else
       
    59   template <typename _Prio,
       
    60             typename _ItemIntMap,
       
    61             typename _Compare = std::less<_Prio> >
       
    62 #endif
       
    63   class FibHeap {
       
    64   public:
       
    65     ///\e
       
    66     typedef _ItemIntMap ItemIntMap;
       
    67     ///\e
       
    68     typedef _Prio Prio;
       
    69     ///\e
       
    70     typedef typename ItemIntMap::Key Item;
       
    71     ///\e
       
    72     typedef std::pair<Item,Prio> Pair;
       
    73     ///\e
       
    74     typedef _Compare Compare;
       
    75 
       
    76   private:
       
    77     class store;
       
    78 
       
    79     std::vector<store> container;
       
    80     int minimum;
       
    81     ItemIntMap &iimap;
       
    82     Compare comp;
       
    83     int num_items;
       
    84 
       
    85   public:
       
    86     ///Status of the nodes
       
    87     enum State {
       
    88       ///The node is in the heap
       
    89       IN_HEAP = 0,
       
    90       ///The node has never been in the heap
       
    91       PRE_HEAP = -1,
       
    92       ///The node was in the heap but it got out of it
       
    93       POST_HEAP = -2
       
    94     };
       
    95 
       
    96     /// \brief The constructor
       
    97     ///
       
    98     /// \c _iimap should be given to the constructor, since it is
       
    99     ///   used internally to handle the cross references.
       
   100     explicit FibHeap(ItemIntMap &_iimap)
       
   101       : minimum(0), iimap(_iimap), num_items() {}
       
   102 
       
   103     /// \brief The constructor
       
   104     ///
       
   105     /// \c _iimap should be given to the constructor, since it is used
       
   106     /// internally to handle the cross references. \c _comp is an
       
   107     /// object for ordering of the priorities.
       
   108     FibHeap(ItemIntMap &_iimap, const Compare &_comp)
       
   109       : minimum(0), iimap(_iimap), comp(_comp), num_items() {}
       
   110 
       
   111     /// \brief The number of items stored in the heap.
       
   112     ///
       
   113     /// Returns the number of items stored in the heap.
       
   114     int size() const { return num_items; }
       
   115 
       
   116     /// \brief Checks if the heap stores no items.
       
   117     ///
       
   118     ///   Returns \c true if and only if the heap stores no items.
       
   119     bool empty() const { return num_items==0; }
       
   120 
       
   121     /// \brief Make empty this heap.
       
   122     ///
       
   123     /// Make empty this heap. It does not change the cross reference
       
   124     /// map.  If you want to reuse a heap what is not surely empty you
       
   125     /// should first clear the heap and after that you should set the
       
   126     /// cross reference map for each item to \c PRE_HEAP.
       
   127     void clear() {
       
   128       container.clear(); minimum = 0; num_items = 0;
       
   129     }
       
   130 
       
   131     /// \brief \c item gets to the heap with priority \c value independently
       
   132     /// if \c item was already there.
       
   133     ///
       
   134     /// This method calls \ref push(\c item, \c value) if \c item is not
       
   135     /// stored in the heap and it calls \ref decrease(\c item, \c value) or
       
   136     /// \ref increase(\c item, \c value) otherwise.
       
   137     void set (const Item& item, const Prio& value) {
       
   138       int i=iimap[item];
       
   139       if ( i >= 0 && container[i].in ) {
       
   140         if ( comp(value, container[i].prio) ) decrease(item, value);
       
   141         if ( comp(container[i].prio, value) ) increase(item, value);
       
   142       } else push(item, value);
       
   143     }
       
   144 
       
   145     /// \brief Adds \c item to the heap with priority \c value.
       
   146     ///
       
   147     /// Adds \c item to the heap with priority \c value.
       
   148     /// \pre \c item must not be stored in the heap.
       
   149     void push (const Item& item, const Prio& value) {
       
   150       int i=iimap[item];
       
   151       if ( i < 0 ) {
       
   152         int s=container.size();
       
   153         iimap.set( item, s );
       
   154         store st;
       
   155         st.name=item;
       
   156         container.push_back(st);
       
   157         i=s;
       
   158       } else {
       
   159         container[i].parent=container[i].child=-1;
       
   160         container[i].degree=0;
       
   161         container[i].in=true;
       
   162         container[i].marked=false;
       
   163       }
       
   164 
       
   165       if ( num_items ) {
       
   166         container[container[minimum].right_neighbor].left_neighbor=i;
       
   167         container[i].right_neighbor=container[minimum].right_neighbor;
       
   168         container[minimum].right_neighbor=i;
       
   169         container[i].left_neighbor=minimum;
       
   170         if ( comp( value, container[minimum].prio) ) minimum=i;
       
   171       } else {
       
   172         container[i].right_neighbor=container[i].left_neighbor=i;
       
   173         minimum=i;
       
   174       }
       
   175       container[i].prio=value;
       
   176       ++num_items;
       
   177     }
       
   178 
       
   179     /// \brief Returns the item with minimum priority relative to \c Compare.
       
   180     ///
       
   181     /// This method returns the item with minimum priority relative to \c
       
   182     /// Compare.
       
   183     /// \pre The heap must be nonempty.
       
   184     Item top() const { return container[minimum].name; }
       
   185 
       
   186     /// \brief Returns the minimum priority relative to \c Compare.
       
   187     ///
       
   188     /// It returns the minimum priority relative to \c Compare.
       
   189     /// \pre The heap must be nonempty.
       
   190     const Prio& prio() const { return container[minimum].prio; }
       
   191 
       
   192     /// \brief Returns the priority of \c item.
       
   193     ///
       
   194     /// It returns the priority of \c item.
       
   195     /// \pre \c item must be in the heap.
       
   196     const Prio& operator[](const Item& item) const {
       
   197       return container[iimap[item]].prio;
       
   198     }
       
   199 
       
   200     /// \brief Deletes the item with minimum priority relative to \c Compare.
       
   201     ///
       
   202     /// This method deletes the item with minimum priority relative to \c
       
   203     /// Compare from the heap.
       
   204     /// \pre The heap must be non-empty.
       
   205     void pop() {
       
   206       /*The first case is that there are only one root.*/
       
   207       if ( container[minimum].left_neighbor==minimum ) {
       
   208         container[minimum].in=false;
       
   209         if ( container[minimum].degree!=0 ) {
       
   210           makeroot(container[minimum].child);
       
   211           minimum=container[minimum].child;
       
   212           balance();
       
   213         }
       
   214       } else {
       
   215         int right=container[minimum].right_neighbor;
       
   216         unlace(minimum);
       
   217         container[minimum].in=false;
       
   218         if ( container[minimum].degree > 0 ) {
       
   219           int left=container[minimum].left_neighbor;
       
   220           int child=container[minimum].child;
       
   221           int last_child=container[child].left_neighbor;
       
   222 
       
   223           makeroot(child);
       
   224 
       
   225           container[left].right_neighbor=child;
       
   226           container[child].left_neighbor=left;
       
   227           container[right].left_neighbor=last_child;
       
   228           container[last_child].right_neighbor=right;
       
   229         }
       
   230         minimum=right;
       
   231         balance();
       
   232       } // the case where there are more roots
       
   233       --num_items;
       
   234     }
       
   235 
       
   236     /// \brief Deletes \c item from the heap.
       
   237     ///
       
   238     /// This method deletes \c item from the heap, if \c item was already
       
   239     /// stored in the heap. It is quite inefficient in Fibonacci heaps.
       
   240     void erase (const Item& item) {
       
   241       int i=iimap[item];
       
   242 
       
   243       if ( i >= 0 && container[i].in ) {
       
   244         if ( container[i].parent!=-1 ) {
       
   245           int p=container[i].parent;
       
   246           cut(i,p);
       
   247           cascade(p);
       
   248         }
       
   249         minimum=i;     //As if its prio would be -infinity
       
   250         pop();
       
   251       }
       
   252     }
       
   253 
       
   254     /// \brief Decreases the priority of \c item to \c value.
       
   255     ///
       
   256     /// This method decreases the priority of \c item to \c value.
       
   257     /// \pre \c item must be stored in the heap with priority at least \c
       
   258     ///   value relative to \c Compare.
       
   259     void decrease (Item item, const Prio& value) {
       
   260       int i=iimap[item];
       
   261       container[i].prio=value;
       
   262       int p=container[i].parent;
       
   263 
       
   264       if ( p!=-1 && comp(value, container[p].prio) ) {
       
   265         cut(i,p);
       
   266         cascade(p);
       
   267       }
       
   268       if ( comp(value, container[minimum].prio) ) minimum=i;
       
   269     }
       
   270 
       
   271     /// \brief Increases the priority of \c item to \c value.
       
   272     ///
       
   273     /// This method sets the priority of \c item to \c value. Though
       
   274     /// there is no precondition on the priority of \c item, this
       
   275     /// method should be used only if it is indeed necessary to increase
       
   276     /// (relative to \c Compare) the priority of \c item, because this
       
   277     /// method is inefficient.
       
   278     void increase (Item item, const Prio& value) {
       
   279       erase(item);
       
   280       push(item, value);
       
   281     }
       
   282 
       
   283 
       
   284     /// \brief Returns if \c item is in, has already been in, or has never
       
   285     /// been in the heap.
       
   286     ///
       
   287     /// This method returns PRE_HEAP if \c item has never been in the
       
   288     /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
       
   289     /// otherwise. In the latter case it is possible that \c item will
       
   290     /// get back to the heap again.
       
   291     State state(const Item &item) const {
       
   292       int i=iimap[item];
       
   293       if( i>=0 ) {
       
   294         if ( container[i].in ) i=0;
       
   295         else i=-2;
       
   296       }
       
   297       return State(i);
       
   298     }
       
   299 
       
   300     /// \brief Sets the state of the \c item in the heap.
       
   301     ///
       
   302     /// Sets the state of the \c item in the heap. It can be used to
       
   303     /// manually clear the heap when it is important to achive the
       
   304     /// better time complexity.
       
   305     /// \param i The item.
       
   306     /// \param st The state. It should not be \c IN_HEAP.
       
   307     void state(const Item& i, State st) {
       
   308       switch (st) {
       
   309       case POST_HEAP:
       
   310       case PRE_HEAP:
       
   311         if (state(i) == IN_HEAP) {
       
   312           erase(i);
       
   313         }
       
   314         iimap[i] = st;
       
   315         break;
       
   316       case IN_HEAP:
       
   317         break;
       
   318       }
       
   319     }
       
   320 
       
   321   private:
       
   322 
       
   323     void balance() {
       
   324 
       
   325       int maxdeg=int( std::floor( 2.08*log(double(container.size()))))+1;
       
   326 
       
   327       std::vector<int> A(maxdeg,-1);
       
   328 
       
   329       /*
       
   330        *Recall that now minimum does not point to the minimum prio element.
       
   331        *We set minimum to this during balance().
       
   332        */
       
   333       int anchor=container[minimum].left_neighbor;
       
   334       int next=minimum;
       
   335       bool end=false;
       
   336 
       
   337       do {
       
   338         int active=next;
       
   339         if ( anchor==active ) end=true;
       
   340         int d=container[active].degree;
       
   341         next=container[active].right_neighbor;
       
   342 
       
   343         while (A[d]!=-1) {
       
   344           if( comp(container[active].prio, container[A[d]].prio) ) {
       
   345             fuse(active,A[d]);
       
   346           } else {
       
   347             fuse(A[d],active);
       
   348             active=A[d];
       
   349           }
       
   350           A[d]=-1;
       
   351           ++d;
       
   352         }
       
   353         A[d]=active;
       
   354       } while ( !end );
       
   355 
       
   356 
       
   357       while ( container[minimum].parent >=0 )
       
   358         minimum=container[minimum].parent;
       
   359       int s=minimum;
       
   360       int m=minimum;
       
   361       do {
       
   362         if ( comp(container[s].prio, container[minimum].prio) ) minimum=s;
       
   363         s=container[s].right_neighbor;
       
   364       } while ( s != m );
       
   365     }
       
   366 
       
   367     void makeroot(int c) {
       
   368       int s=c;
       
   369       do {
       
   370         container[s].parent=-1;
       
   371         s=container[s].right_neighbor;
       
   372       } while ( s != c );
       
   373     }
       
   374 
       
   375     void cut(int a, int b) {
       
   376       /*
       
   377        *Replacing a from the children of b.
       
   378        */
       
   379       --container[b].degree;
       
   380 
       
   381       if ( container[b].degree !=0 ) {
       
   382         int child=container[b].child;
       
   383         if ( child==a )
       
   384           container[b].child=container[child].right_neighbor;
       
   385         unlace(a);
       
   386       }
       
   387 
       
   388 
       
   389       /*Lacing a to the roots.*/
       
   390       int right=container[minimum].right_neighbor;
       
   391       container[minimum].right_neighbor=a;
       
   392       container[a].left_neighbor=minimum;
       
   393       container[a].right_neighbor=right;
       
   394       container[right].left_neighbor=a;
       
   395 
       
   396       container[a].parent=-1;
       
   397       container[a].marked=false;
       
   398     }
       
   399 
       
   400     void cascade(int a) {
       
   401       if ( container[a].parent!=-1 ) {
       
   402         int p=container[a].parent;
       
   403 
       
   404         if ( container[a].marked==false ) container[a].marked=true;
       
   405         else {
       
   406           cut(a,p);
       
   407           cascade(p);
       
   408         }
       
   409       }
       
   410     }
       
   411 
       
   412     void fuse(int a, int b) {
       
   413       unlace(b);
       
   414 
       
   415       /*Lacing b under a.*/
       
   416       container[b].parent=a;
       
   417 
       
   418       if (container[a].degree==0) {
       
   419         container[b].left_neighbor=b;
       
   420         container[b].right_neighbor=b;
       
   421         container[a].child=b;
       
   422       } else {
       
   423         int child=container[a].child;
       
   424         int last_child=container[child].left_neighbor;
       
   425         container[child].left_neighbor=b;
       
   426         container[b].right_neighbor=child;
       
   427         container[last_child].right_neighbor=b;
       
   428         container[b].left_neighbor=last_child;
       
   429       }
       
   430 
       
   431       ++container[a].degree;
       
   432 
       
   433       container[b].marked=false;
       
   434     }
       
   435 
       
   436     /*
       
   437      *It is invoked only if a has siblings.
       
   438      */
       
   439     void unlace(int a) {
       
   440       int leftn=container[a].left_neighbor;
       
   441       int rightn=container[a].right_neighbor;
       
   442       container[leftn].right_neighbor=rightn;
       
   443       container[rightn].left_neighbor=leftn;
       
   444     }
       
   445 
       
   446 
       
   447     class store {
       
   448       friend class FibHeap;
       
   449 
       
   450       Item name;
       
   451       int parent;
       
   452       int left_neighbor;
       
   453       int right_neighbor;
       
   454       int child;
       
   455       int degree;
       
   456       bool marked;
       
   457       bool in;
       
   458       Prio prio;
       
   459 
       
   460       store() : parent(-1), child(-1), degree(), marked(false), in(true) {}
       
   461     };
       
   462   };
       
   463 
       
   464 } //namespace lemon
       
   465 
       
   466 #endif //LEMON_FIB_HEAP_H
       
   467