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