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