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