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