gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Make K a template parameter in KaryHeap (#301)
0 1 0
default
1 file changed with 13 insertions and 9 deletions:
↑ Collapse diff ↑
Ignore white space 192 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_KARY_HEAP_H
20 20
#define LEMON_KARY_HEAP_H
21 21

	
22 22
///\ingroup heaps
23 23
///\file
24 24
///\brief Fourary heap implementation.
25 25

	
26 26
#include <vector>
27 27
#include <utility>
28 28
#include <functional>
29 29

	
30 30
namespace lemon {
31 31

	
32 32
  /// \ingroup heaps
33 33
  ///
34 34
  ///\brief K-ary heap data structure.
35 35
  ///
36 36
  /// This class implements the \e K-ary \e heap data structure.
37 37
  /// It fully conforms to the \ref concepts::Heap "heap concept".
38 38
  ///
39 39
  /// The \ref KaryHeap "K-ary heap" is a generalization of the
40 40
  /// \ref BinHeap "binary heap" structure, its nodes have at most
41 41
  /// \c K children, instead of two.
42 42
  /// \ref BinHeap and \ref FouraryHeap are specialized implementations
43 43
  /// of this structure for <tt>K=2</tt> and <tt>K=4</tt>, respectively.
44 44
  ///
45 45
  /// \tparam PR Type of the priorities of the items.
46 46
  /// \tparam IM A read-writable item map with \c int values, used
47 47
  /// internally to handle the cross references.
48
  /// \tparam K The degree of the heap, each node have at most \e K
49
  /// children. The default is 16. Powers of two are suggested to use
50
  /// so that the multiplications and divisions needed to traverse the
51
  /// nodes of the heap could be performed faster.
48 52
  /// \tparam CMP A functor class for comparing the priorities.
49 53
  /// The default is \c std::less<PR>.
50 54
  ///
51 55
  ///\sa BinHeap
52 56
  ///\sa FouraryHeap
53 57
#ifdef DOXYGEN
54
  template <typename PR, typename IM, typename CMP>
58
  template <typename PR, typename IM, int K, typename CMP>
55 59
#else
56
  template <typename PR, typename IM, typename CMP = std::less<PR> >
60
  template <typename PR, typename IM, int K = 16,
61
            typename CMP = std::less<PR> >
57 62
#endif
58 63
  class KaryHeap {
59 64
  public:
60 65
    /// Type of the item-int map.
61 66
    typedef IM ItemIntMap;
62 67
    /// Type of the priorities.
63 68
    typedef PR Prio;
64 69
    /// Type of the items stored in the heap.
65 70
    typedef typename ItemIntMap::Key Item;
66 71
    /// Type of the item-priority pairs.
67 72
    typedef std::pair<Item,Prio> Pair;
68 73
    /// Functor type for comparing the priorities.
69 74
    typedef CMP Compare;
70 75

	
71 76
    /// \brief Type to represent the states of the items.
72 77
    ///
73 78
    /// Each item has a state associated to it. It can be "in heap",
74 79
    /// "pre-heap" or "post-heap". The latter two are indifferent from the
75 80
    /// heap's point of view, but may be useful to the user.
76 81
    ///
77 82
    /// The item-int map must be initialized in such way that it assigns
78 83
    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
79 84
    enum State {
80 85
      IN_HEAP = 0,    ///< = 0.
81 86
      PRE_HEAP = -1,  ///< = -1.
82 87
      POST_HEAP = -2  ///< = -2.
83 88
    };
84 89

	
85 90
  private:
86 91
    std::vector<Pair> _data;
87 92
    Compare _comp;
88 93
    ItemIntMap &_iim;
89
    int _K;
90 94

	
91 95
  public:
92 96
    /// \brief Constructor.
93 97
    ///
94 98
    /// Constructor.
95 99
    /// \param map A map that assigns \c int values to the items.
96 100
    /// It is used internally to handle the cross references.
97 101
    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
98
    explicit KaryHeap(ItemIntMap &map, int K=32) : _iim(map), _K(K) {}
102
    explicit KaryHeap(ItemIntMap &map) : _iim(map) {}
99 103

	
100 104
    /// \brief Constructor.
101 105
    ///
102 106
    /// Constructor.
103 107
    /// \param map A map that assigns \c int values to the items.
104 108
    /// It is used internally to handle the cross references.
105 109
    /// The assigned value must be \c PRE_HEAP (<tt>-1</tt>) for each item.
106 110
    /// \param comp The function object used for comparing the priorities.
107
    KaryHeap(ItemIntMap &map, const Compare &comp, int K=32)
108
      : _iim(map), _comp(comp), _K(K) {}
111
    KaryHeap(ItemIntMap &map, const Compare &comp)
112
      : _iim(map), _comp(comp) {}
109 113

	
110 114
    /// \brief The number of items stored in the heap.
111 115
    ///
112 116
    /// This function returns the number of items stored in the heap.
113 117
    int size() const { return _data.size(); }
114 118

	
115 119
    /// \brief Check if the heap is empty.
116 120
    ///
117 121
    /// This function returns \c true if the heap is empty.
118 122
    bool empty() const { return _data.empty(); }
119 123

	
120 124
    /// \brief Make the heap empty.
121 125
    ///
122 126
    /// This functon makes the heap empty.
123 127
    /// It does not change the cross reference map. If you want to reuse
124 128
    /// a heap that is not surely empty, you should first clear it and
125 129
    /// then you should set the cross reference map to \c PRE_HEAP
126 130
    /// for each item.
127 131
    void clear() { _data.clear(); }
128 132

	
129 133
  private:
130
    int parent(int i) { return (i-1)/_K; }
131
    int firstChild(int i) { return _K*i+1; }
134
    int parent(int i) { return (i-1)/K; }
135
    int firstChild(int i) { return K*i+1; }
132 136

	
133 137
    bool less(const Pair &p1, const Pair &p2) const {
134 138
      return _comp(p1.second, p2.second);
135 139
    }
136 140

	
137 141
    int findMin(const int child, const int length) {
138 142
      int min=child, i=1;
139
      while( i<_K && child+i<length ) {
143
      while( i<K && child+i<length ) {
140 144
        if( less(_data[child+i], _data[min]) )
141 145
          min=child+i;
142 146
        ++i;
143 147
      }
144 148
      return min;
145 149
    }
146 150

	
147 151
    void bubbleUp(int hole, Pair p) {
148 152
      int par = parent(hole);
149 153
      while( hole>0 && less(p,_data[par]) ) {
150 154
        move(_data[par],hole);
151 155
        hole = par;
152 156
        par = parent(hole);
153 157
      }
154 158
      move(p, hole);
155 159
    }
156 160

	
157 161
    void bubbleDown(int hole, Pair p, int length) {
158 162
      if( length>1 ) {
159 163
        int child = firstChild(hole);
160 164
        while( child<length ) {
161 165
          child = findMin(child, length);
162 166
          if( !less(_data[child], p) )
163 167
            goto ok;
164 168
          move(_data[child], hole);
165 169
          hole = child;
166 170
          child = firstChild(hole);
167 171
        }
168 172
      }
169 173
    ok:
170 174
      move(p, hole);
171 175
    }
172 176

	
173 177
    void move(const Pair &p, int i) {
174 178
      _data[i] = p;
175 179
      _iim.set(p.first, i);
176 180
    }
177 181

	
178 182
  public:
179 183
    /// \brief Insert a pair of item and priority into the heap.
180 184
    ///
181 185
    /// This function inserts \c p.first to the heap with priority
182 186
    /// \c p.second.
183 187
    /// \param p The pair to insert.
184 188
    /// \pre \c p.first must not be stored in the heap.
185 189
    void push(const Pair &p) {
186 190
      int n = _data.size();
187 191
      _data.resize(n+1);
188 192
      bubbleUp(n, p);
189 193
    }
190 194

	
191 195
    /// \brief Insert an item into the heap with the given priority.
192 196
    ///
193 197
    /// This function inserts the given item into the heap with the
194 198
    /// given priority.
195 199
    /// \param i The item to insert.
196 200
    /// \param p The priority of the item.
197 201
    /// \pre \e i must not be stored in the heap.
198 202
    void push(const Item &i, const Prio &p) { push(Pair(i,p)); }
199 203

	
200 204
    /// \brief Return the item having minimum priority.
201 205
    ///
202 206
    /// This function returns the item having minimum priority.
203 207
    /// \pre The heap must be non-empty.
204 208
    Item top() const { return _data[0].first; }
205 209

	
206 210
    /// \brief The minimum priority.
207 211
    ///
208 212
    /// This function returns the minimum priority.
209 213
    /// \pre The heap must be non-empty.
210 214
    Prio prio() const { return _data[0].second; }
211 215

	
212 216
    /// \brief Remove the item having minimum priority.
213 217
    ///
214 218
    /// This function removes the item having minimum priority.
215 219
    /// \pre The heap must be non-empty.
216 220
    void pop() {
217 221
      int n = _data.size()-1;
218 222
      _iim.set(_data[0].first, POST_HEAP);
219 223
      if (n>0) bubbleDown(0, _data[n], n);
220 224
      _data.pop_back();
221 225
    }
222 226

	
223 227
    /// \brief Remove the given item from the heap.
224 228
    ///
225 229
    /// This function removes the given item from the heap if it is
226 230
    /// already stored.
227 231
    /// \param i The item to delete.
228 232
    /// \pre \e i must be in the heap.
229 233
    void erase(const Item &i) {
230 234
      int h = _iim[i];
231 235
      int n = _data.size()-1;
232 236
      _iim.set(_data[h].first, POST_HEAP);
233 237
      if( h<n ) {
234 238
        if( less(_data[parent(h)], _data[n]) )
235 239
          bubbleDown(h, _data[n], n);
0 comments (0 inline)