lemon/radix_heap.h
author deba
Fri, 19 Oct 2007 17:07:50 +0000
changeset 2500 9d9855af1de1
parent 2386 81b47fc5c444
child 2547 f393a8162688
permissions -rw-r--r--
planar doxygen group
deba@1186
     1
/* -*- C++ -*-
deba@1186
     2
 *
alpar@1956
     3
 * This file is a part of LEMON, a generic C++ optimization library
alpar@1956
     4
 *
alpar@2391
     5
 * Copyright (C) 2003-2007
alpar@1956
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@1359
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
deba@1186
     8
 *
deba@1186
     9
 * Permission to use, modify and distribute this software is granted
deba@1186
    10
 * provided that this copyright notice appears in all copies. For
deba@1186
    11
 * precise terms see the accompanying LICENSE file.
deba@1186
    12
 *
deba@1186
    13
 * This software is provided "AS IS" with no warranty of any kind,
deba@1186
    14
 * express or implied, and with no claim as to its suitability for any
deba@1186
    15
 * purpose.
deba@1186
    16
 *
deba@1186
    17
 */
deba@1186
    18
deba@1186
    19
#ifndef LEMON_RADIX_HEAP_H
deba@1186
    20
#define LEMON_RADIX_HEAP_H
deba@1186
    21
deba@1186
    22
///\ingroup auxdat
deba@1186
    23
///\file
deba@1186
    24
///\brief Radix Heap implementation.
deba@1186
    25
deba@1186
    26
#include <vector>
deba@1186
    27
#include <lemon/error.h>
deba@1186
    28
deba@1186
    29
namespace lemon {
deba@1186
    30
deba@1331
    31
  /// \brief Exception thrown by RadixHeap.
deba@1331
    32
  ///  
deba@1331
    33
  /// This Exception is thrown when a smaller priority
deba@1331
    34
  /// is inserted into the \e RadixHeap then the last time erased.
deba@1331
    35
  /// \see RadixHeap
deba@1331
    36
  /// \author Balazs Dezso
deba@1186
    37
deba@1331
    38
  class UnderFlowPriorityError : public RuntimeError {
deba@1186
    39
  public:
alpar@2151
    40
    virtual const char* what() const throw() {
deba@1331
    41
      return "lemon::UnderFlowPriorityError";
deba@1186
    42
    }  
deba@1186
    43
  };
deba@1186
    44
deba@1717
    45
  /// \ingroup auxdata
deba@1717
    46
  ///
deba@1331
    47
  /// \brief A Radix Heap implementation.
deba@1331
    48
  ///
deba@1331
    49
  /// This class implements the \e radix \e heap data structure. A \e heap
deba@1331
    50
  /// is a data structure for storing items with specified values called \e
deba@1331
    51
  /// priorities in such a way that finding the item with minimum priority is
deba@1331
    52
  /// efficient. This heap type can store only items with \e int priority.
deba@1331
    53
  /// In a heap one can change the priority of an item, add or erase an 
deba@1331
    54
  /// item, but the priority cannot be decreased under the last removed 
deba@1331
    55
  /// item's priority.
deba@1331
    56
  ///
deba@1331
    57
  /// \param _ItemIntMap A read and writable Item int map, used internally
deba@1331
    58
  /// to handle the cross references.
deba@1331
    59
  ///
deba@1331
    60
  /// \see BinHeap
deba@1331
    61
  /// \see Dijkstra
deba@1331
    62
  /// \author Balazs Dezso
deba@1331
    63
mqrelly@2263
    64
  template <typename _ItemIntMap>
deba@1186
    65
  class RadixHeap {
deba@1186
    66
deba@1186
    67
  public:
mqrelly@2263
    68
    typedef typename _ItemIntMap::Key Item;
deba@1186
    69
    typedef int Prio;
deba@1186
    70
    typedef _ItemIntMap ItemIntMap;
deba@1186
    71
deba@1331
    72
    /// \brief Type to represent the items states.
deba@1186
    73
    ///
deba@1331
    74
    /// Each Item element have a state associated to it. It may be "in heap",
alpar@1336
    75
    /// "pre heap" or "post heap". The latter two are indifferent from the
deba@1331
    76
    /// heap's point of view, but may be useful to the user.
deba@1331
    77
    ///
alpar@1336
    78
    /// The ItemIntMap \e should be initialized in such way that it maps
deba@1331
    79
    /// PRE_HEAP (-1) to any element to be put in the heap...
deba@1186
    80
    enum state_enum {
deba@1186
    81
      IN_HEAP = 0,
deba@1186
    82
      PRE_HEAP = -1,
deba@1186
    83
      POST_HEAP = -2
deba@1186
    84
    };
deba@1186
    85
deba@1186
    86
  private:
deba@1186
    87
    
deba@1186
    88
    struct RadixItem {
deba@1186
    89
      int prev, next, box;
deba@1186
    90
      Item item;
deba@1186
    91
      int prio;
deba@1186
    92
      RadixItem(Item _item, int _prio) : item(_item), prio(_prio) {}
deba@1186
    93
    };
deba@1186
    94
deba@1186
    95
    struct RadixBox {
deba@1186
    96
      int first;
deba@1186
    97
      int min, size;
deba@1186
    98
      RadixBox(int _min, int _size) : first(-1), min(_min), size(_size) {}
deba@1186
    99
    };
deba@1186
   100
deba@1186
   101
    std::vector<RadixItem> data;
deba@1186
   102
    std::vector<RadixBox> boxes;
deba@1186
   103
deba@1186
   104
    ItemIntMap &iim;
deba@1186
   105
deba@1186
   106
deba@1186
   107
  public:
deba@1331
   108
    /// \brief The constructor.
deba@1331
   109
    ///
deba@1331
   110
    /// The constructor.
deba@1331
   111
    ///
deba@1331
   112
    /// \param _iim It should be given to the constructor, since it is used
deba@1331
   113
    /// internally to handle the cross references. The value of the map
deba@1331
   114
    /// should be PRE_HEAP (-1) for each element.
deba@1331
   115
    ///
deba@1717
   116
    /// \param minimal The initial minimal value of the heap.
deba@1331
   117
    /// \param capacity It determines the initial capacity of the heap. 
deba@1717
   118
    RadixHeap(ItemIntMap &_iim, int minimal = 0, int capacity = 0) 
deba@1717
   119
      : iim(_iim) {
deba@1717
   120
      boxes.push_back(RadixBox(minimal, 1));
deba@1717
   121
      boxes.push_back(RadixBox(minimal + 1, 1));
deba@1717
   122
      while (lower(boxes.size() - 1, capacity + minimal - 1)) {
deba@1186
   123
	extend();
deba@1186
   124
      }
deba@1186
   125
    }
deba@1186
   126
deba@1331
   127
    /// The number of items stored in the heap.
deba@1331
   128
    ///
deba@1331
   129
    /// \brief Returns the number of items stored in the heap.
deba@1186
   130
    int size() const { return data.size(); }
deba@1331
   131
    /// \brief Checks if the heap stores no items.
deba@1331
   132
    ///
deba@1331
   133
    /// Returns \c true if and only if the heap stores no items.
deba@1186
   134
    bool empty() const { return data.empty(); }
deba@1186
   135
deba@1717
   136
    /// \brief Make empty this heap.
deba@1717
   137
    /// 
deba@2050
   138
    /// Make empty this heap. It does not change the cross reference
deba@2050
   139
    /// map.  If you want to reuse a heap what is not surely empty you
deba@2050
   140
    /// should first clear the heap and after that you should set the
deba@2050
   141
    /// cross reference map for each item to \c PRE_HEAP.
deba@1717
   142
    void clear(int minimal = 0, int capacity = 0) { 
deba@1717
   143
      data.clear(); boxes.clear(); 
deba@1717
   144
      boxes.push_back(RadixBox(minimal, 1));
deba@1717
   145
      boxes.push_back(RadixBox(minimal + 1, 1));
deba@1717
   146
      while (lower(boxes.size() - 1, capacity + minimal - 1)) {
deba@1717
   147
	extend();
deba@1717
   148
      }
deba@1717
   149
    }
deba@1717
   150
deba@1186
   151
  private:
deba@1186
   152
deba@2386
   153
    bool upper(int box, Prio pr) {
deba@2386
   154
      return pr < boxes[box].min;
deba@1186
   155
    }
deba@1186
   156
deba@2386
   157
    bool lower(int box, Prio pr) {
deba@2386
   158
      return pr >= boxes[box].min + boxes[box].size;
deba@1186
   159
    }
deba@1186
   160
deba@1186
   161
    /// \brief Remove item from the box list.
deba@1186
   162
    void remove(int index) {
deba@1186
   163
      if (data[index].prev >= 0) {
deba@1186
   164
	data[data[index].prev].next = data[index].next;
deba@1186
   165
      } else {
deba@1186
   166
	boxes[data[index].box].first = data[index].next;
deba@1186
   167
      }
deba@1186
   168
      if (data[index].next >= 0) {
deba@1186
   169
	data[data[index].next].prev = data[index].prev;
deba@1186
   170
      }
deba@1186
   171
    }
deba@1186
   172
deba@1186
   173
    /// \brief Insert item into the box list.
deba@1186
   174
    void insert(int box, int index) {
deba@1186
   175
      if (boxes[box].first == -1) {
deba@1186
   176
	boxes[box].first = index;
deba@1186
   177
	data[index].next = data[index].prev = -1;
deba@1186
   178
      } else {
deba@1186
   179
	data[index].next = boxes[box].first;
deba@1186
   180
	data[boxes[box].first].prev = index;
deba@1186
   181
	data[index].prev = -1;
deba@1186
   182
	boxes[box].first = index;
deba@1186
   183
      }
deba@1186
   184
      data[index].box = box;
deba@1186
   185
    }
deba@1186
   186
deba@1186
   187
    /// \brief Add a new box to the box list.
deba@1186
   188
    void extend() {
deba@1186
   189
      int min = boxes.back().min + boxes.back().size;
deba@2386
   190
      int bs = 2 * boxes.back().size;
deba@2386
   191
      boxes.push_back(RadixBox(min, bs));
deba@1186
   192
    }
deba@1186
   193
deba@1186
   194
    /// \brief Move an item up into the proper box.
deba@1186
   195
    void bubble_up(int index) {
deba@1205
   196
      if (!lower(data[index].box, data[index].prio)) return;
deba@1186
   197
      remove(index);
deba@1186
   198
      int box = findUp(data[index].box, data[index].prio);
deba@1186
   199
      insert(box, index);      
deba@1186
   200
    }
deba@1186
   201
deba@1186
   202
    /// \brief Find up the proper box for the item with the given prio.
deba@2386
   203
    int findUp(int start, int pr) {
deba@2386
   204
      while (lower(start, pr)) {
deba@2386
   205
	if (++start == int(boxes.size())) {
deba@1186
   206
	  extend();
deba@1186
   207
	}
deba@1186
   208
      }
deba@1186
   209
      return start;
deba@1186
   210
    }
deba@1186
   211
deba@1186
   212
    /// \brief Move an item down into the proper box.
deba@1186
   213
    void bubble_down(int index) {
deba@1186
   214
      if (!upper(data[index].box, data[index].prio)) return;
deba@1186
   215
      remove(index);
deba@1186
   216
      int box = findDown(data[index].box, data[index].prio);
deba@1186
   217
      insert(box, index);
deba@1186
   218
    }
deba@1186
   219
deba@1186
   220
    /// \brief Find up the proper box for the item with the given prio.
deba@2386
   221
    int findDown(int start, int pr) {
deba@2386
   222
      while (upper(start, pr)) {
deba@1331
   223
	if (--start < 0) throw UnderFlowPriorityError();
deba@1186
   224
      }
deba@1186
   225
      return start;
deba@1186
   226
    }
deba@1186
   227
deba@1186
   228
    /// \brief Find the first not empty box.
deba@1186
   229
    int findFirst() {
deba@1186
   230
      int first = 0;
deba@1186
   231
      while (boxes[first].first == -1) ++first;
deba@1186
   232
      return first;
deba@1186
   233
    }
deba@1186
   234
deba@1186
   235
    /// \brief Gives back the minimal prio of the box.
deba@1186
   236
    int minValue(int box) {
deba@1186
   237
      int min = data[boxes[box].first].prio;
deba@1186
   238
      for (int k = boxes[box].first; k != -1; k = data[k].next) {
deba@1186
   239
	if (data[k].prio < min) min = data[k].prio;
deba@1186
   240
      }
deba@1186
   241
      return min;
deba@1186
   242
    }
deba@1186
   243
deba@1186
   244
    /// \brief Rearrange the items of the heap and makes the 
deba@1186
   245
    /// first box not empty.
deba@1186
   246
    void moveDown() {
deba@1186
   247
      int box = findFirst();
deba@1186
   248
      if (box == 0) return;
deba@1186
   249
      int min = minValue(box);
deba@1186
   250
      for (int i = 0; i <= box; ++i) {
deba@1186
   251
	boxes[i].min = min;
deba@1186
   252
	min += boxes[i].size;
deba@1186
   253
      }
deba@1186
   254
      int curr = boxes[box].first, next;
deba@1186
   255
      while (curr != -1) {
deba@1186
   256
	next = data[curr].next;
deba@1186
   257
	bubble_down(curr);
deba@1186
   258
	curr = next;
deba@1186
   259
      }      
deba@1186
   260
    }
deba@1186
   261
deba@1186
   262
    void relocate_last(int index) {
deba@2386
   263
      if (index != int(data.size()) - 1) {
deba@1186
   264
	data[index] = data.back();
deba@1186
   265
	if (data[index].prev != -1) {
deba@1186
   266
	  data[data[index].prev].next = index;
deba@1186
   267
	} else {
deba@1186
   268
	  boxes[data[index].box].first = index;
deba@1186
   269
	}
deba@1186
   270
	if (data[index].next != -1) {
deba@1186
   271
	  data[data[index].next].prev = index;
deba@1186
   272
	}
deba@1186
   273
	iim[data[index].item] = index;
deba@1186
   274
      }
deba@1186
   275
      data.pop_back();
deba@1186
   276
    }
deba@1186
   277
deba@1186
   278
  public:
deba@1186
   279
deba@1717
   280
    /// \brief Insert an item into the heap with the given priority.
deba@1331
   281
    ///    
deba@1331
   282
    /// Adds \c i to the heap with priority \c p. 
deba@1331
   283
    /// \param i The item to insert.
deba@1331
   284
    /// \param p The priority of the item.
deba@1186
   285
    void push(const Item &i, const Prio &p) {
deba@1186
   286
      int n = data.size();
deba@1186
   287
      iim.set(i, n);
deba@1186
   288
      data.push_back(RadixItem(i, p));
deba@1186
   289
      while (lower(boxes.size() - 1, p)) {
deba@1186
   290
	extend();
deba@1186
   291
      }
deba@1186
   292
      int box = findDown(boxes.size() - 1, p);
deba@1186
   293
      insert(box, n);
deba@1186
   294
    }
deba@1186
   295
deba@1331
   296
    /// \brief Returns the item with minimum priority.
deba@1331
   297
    ///
deba@1331
   298
    /// This method returns the item with minimum priority.  
deba@1331
   299
    /// \pre The heap must be nonempty.  
deba@1186
   300
    Item top() const {
mqrelly@2263
   301
      const_cast<RadixHeap<ItemIntMap>&>(*this).moveDown();
deba@1186
   302
      return data[boxes[0].first].item;
deba@1186
   303
    }
deba@1186
   304
deba@1331
   305
    /// \brief Returns the minimum priority.
deba@1331
   306
    ///
deba@1331
   307
    /// It returns the minimum priority.
deba@1331
   308
    /// \pre The heap must be nonempty.
deba@1186
   309
    Prio prio() const {
mqrelly@2263
   310
      const_cast<RadixHeap<ItemIntMap>&>(*this).moveDown();
deba@1186
   311
      return data[boxes[0].first].prio;
deba@1186
   312
     }
deba@1186
   313
deba@1331
   314
    /// \brief Deletes the item with minimum priority.
deba@1331
   315
    ///
deba@1331
   316
    /// This method deletes the item with minimum priority.
deba@1331
   317
    /// \pre The heap must be non-empty.  
deba@1186
   318
    void pop() {
deba@1186
   319
      moveDown();
deba@1186
   320
      int index = boxes[0].first;
deba@1186
   321
      iim[data[index].item] = POST_HEAP;
deba@1186
   322
      remove(index);
deba@1186
   323
      relocate_last(index);
deba@1186
   324
    }
deba@1186
   325
deba@1331
   326
    /// \brief Deletes \c i from the heap.
deba@1331
   327
    ///
deba@1331
   328
    /// This method deletes item \c i from the heap, if \c i was
deba@1331
   329
    /// already stored in the heap.
deba@1331
   330
    /// \param i The item to erase. 
deba@1186
   331
    void erase(const Item &i) {
deba@1186
   332
      int index = iim[i];
deba@1186
   333
      iim[i] = POST_HEAP;
deba@1186
   334
      remove(index);
deba@1186
   335
      relocate_last(index);
deba@1186
   336
   }
deba@1186
   337
deba@1331
   338
    /// \brief Returns the priority of \c i.
deba@1331
   339
    ///
deba@1331
   340
    /// This function returns the priority of item \c i.  
deba@1331
   341
    /// \pre \c i must be in the heap.
deba@1331
   342
    /// \param i The item.
deba@1186
   343
    Prio operator[](const Item &i) const {
deba@1186
   344
      int idx = iim[i];
deba@1186
   345
      return data[idx].prio;
deba@1186
   346
    }
deba@1186
   347
deba@1331
   348
    /// \brief \c i gets to the heap with priority \c p independently 
deba@1331
   349
    /// if \c i was already there.
deba@1331
   350
    ///
deba@1331
   351
    /// This method calls \ref push(\c i, \c p) if \c i is not stored
deba@1331
   352
    /// in the heap and sets the priority of \c i to \c p otherwise.
deba@1331
   353
    /// It may throw an \e UnderFlowPriorityException. 
deba@1331
   354
    /// \param i The item.
deba@1331
   355
    /// \param p The priority.
deba@1186
   356
    void set(const Item &i, const Prio &p) {
deba@1186
   357
      int idx = iim[i];
deba@1186
   358
      if( idx < 0 ) {
deba@1186
   359
	push(i, p);
deba@1186
   360
      }
deba@1186
   361
      else if( p >= data[idx].prio ) {
deba@1186
   362
	data[idx].prio = p;
deba@1186
   363
	bubble_up(idx);
deba@1186
   364
      } else {
deba@1186
   365
	data[idx].prio = p;
deba@1186
   366
	bubble_down(idx);
deba@1186
   367
      }
deba@1186
   368
    }
deba@1186
   369
deba@1331
   370
deba@1331
   371
    /// \brief Decreases the priority of \c i to \c p.
deba@1331
   372
    ///
deba@1331
   373
    /// This method decreases the priority of item \c i to \c p.
deba@1331
   374
    /// \pre \c i must be stored in the heap with priority at least \c p, and
deba@1758
   375
    /// \c should be greater or equal to the last removed item's priority.
deba@1331
   376
    /// \param i The item.
deba@1331
   377
    /// \param p The priority.
deba@1186
   378
    void decrease(const Item &i, const Prio &p) {
deba@1186
   379
      int idx = iim[i];
deba@1186
   380
      data[idx].prio = p;
deba@1186
   381
      bubble_down(idx);
deba@1186
   382
    }
deba@1186
   383
deba@1331
   384
    /// \brief Increases the priority of \c i to \c p.
deba@1331
   385
    ///
deba@1331
   386
    /// This method sets the priority of item \c i to \c p. 
deba@1758
   387
    /// \pre \c i must be stored in the heap with priority at most \c p
deba@1331
   388
    /// \param i The item.
deba@1331
   389
    /// \param p The priority.
deba@1186
   390
    void increase(const Item &i, const Prio &p) {
deba@1186
   391
      int idx = iim[i];
deba@1186
   392
      data[idx].prio = p;
deba@1186
   393
      bubble_up(idx);
deba@1186
   394
    }
deba@1186
   395
deba@1331
   396
    /// \brief Returns if \c item is in, has already been in, or has 
deba@1331
   397
    /// never been in the heap.
deba@1331
   398
    ///
deba@1331
   399
    /// This method returns PRE_HEAP if \c item has never been in the
deba@1331
   400
    /// heap, IN_HEAP if it is in the heap at the moment, and POST_HEAP
deba@1331
   401
    /// otherwise. In the latter case it is possible that \c item will
deba@1331
   402
    /// get back to the heap again.
deba@1331
   403
    /// \param i The item.
deba@1186
   404
    state_enum state(const Item &i) const {
deba@1186
   405
      int s = iim[i];
deba@1186
   406
      if( s >= 0 ) s = 0;
deba@1186
   407
      return state_enum(s);
deba@1186
   408
    }
deba@1186
   409
deba@1902
   410
    /// \brief Sets the state of the \c item in the heap.
deba@1902
   411
    ///
deba@1902
   412
    /// Sets the state of the \c item in the heap. It can be used to
deba@1902
   413
    /// manually clear the heap when it is important to achive the
deba@1902
   414
    /// better time complexity.
deba@1902
   415
    /// \param i The item.
deba@1902
   416
    /// \param st The state. It should not be \c IN_HEAP. 
deba@1902
   417
    void state(const Item& i, state_enum st) {
deba@1902
   418
      switch (st) {
deba@1902
   419
      case POST_HEAP:
deba@1902
   420
      case PRE_HEAP:
deba@1902
   421
        if (state(i) == IN_HEAP) {
deba@1902
   422
          erase(i);
deba@1902
   423
        }
deba@1903
   424
        iim[i] = st;
deba@1902
   425
        break;
deba@1906
   426
      case IN_HEAP:
deba@1906
   427
        break;
deba@1902
   428
      }
deba@1902
   429
    }
deba@1902
   430
deba@1186
   431
  }; // class RadixHeap
deba@1186
   432
deba@1186
   433
} // namespace lemon
deba@1186
   434
deba@1186
   435
#endif // LEMON_RADIX_HEAP_H