1 /* $Id: binaryheap.hpp 24900 2013-01-08 22:46:42Z planetmaker $ */
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file binaryheap.hpp Binary heap implementation. */
12 #ifndef BINARYHEAP_HPP
13 #define BINARYHEAP_HPP
15 #include "../core/alloc_func.hpp"
17 /** Enable it if you suspect binary heap doesn't work well */
18 #define BINARYHEAP_CHECK 0
21 /** Check for consistency. */
22 #define CHECK_CONSISTY() this->CheckConsistency()
24 /** Don't check for consistency. */
25 #define CHECK_CONSISTY() ;
29 * Binary Heap as C++ template.
30 * A carrier which keeps its items automatically holds the smallest item at
31 * the first position. The order of items is maintained by using a binary tree.
32 * The implementation is used for priority queue's.
34 * @par Usage information:
35 * Item of the binary heap should support the 'lower-than' operator '<'.
36 * It is used for comparing items before moving them to their position.
39 * This binary heap allocates just the space for item pointers. The items
40 * are allocated elsewhere.
42 * @par Implementation notes:
43 * Internally the first item is never used, because that simplifies the
47 * For further information about the Binary Heap algorithm, see
48 * http://www.policyalmanac.org/games/binaryHeaps.htm
50 * @tparam T Type of the items stored in the binary heap
55 uint items
; ///< Number of items in the heap
56 uint capacity
; ///< Maximum number of items the heap can hold
57 T
**data
; ///< The pointer to the heap item pointers
61 * Create a binary heap.
62 * @param max_items The limit of the heap
64 explicit CBinaryHeapT(uint max_items
)
68 this->data
= MallocT
<T
*>(max_items
+ 1);
80 * Get position for fixing a gap (downwards).
81 * The gap is moved downwards in the binary tree until it
84 * @param gap The position of the gap
85 * @param item The proposed item for filling the gap
86 * @return The (gap)position where the item fits
88 inline uint
HeapifyDown(uint gap
, T
*item
)
92 /* The first child of the gap is at [parent * 2] */
95 /* while children are valid */
96 while (child
<= this->items
) {
97 /* choose the smaller child */
98 if (child
< this->items
&& *this->data
[child
+ 1] < *this->data
[child
]) {
101 /* is it smaller than our parent? */
102 if (!(*this->data
[child
] < *item
)) {
103 /* the smaller child is still bigger or same as parent => we are done */
106 /* if smaller child is smaller than parent, it will become new parent */
107 this->data
[gap
] = this->data
[child
];
109 /* where do we have our new children? */
116 * Get position for fixing a gap (upwards).
117 * The gap is moved upwards in the binary tree until the
120 * @param gap The position of the gap
121 * @param item The proposed item for filling the gap
122 * @return The (gap)position where the item fits
124 inline uint
HeapifyUp(uint gap
, T
*item
)
131 /* compare [gap] with its parent */
133 if (!(*item
< *this->data
[parent
])) {
134 /* we don't need to continue upstairs */
137 this->data
[gap
] = this->data
[parent
];
144 /** Verify the heap consistency */
145 inline void CheckConsistency()
147 for (uint child
= 2; child
<= this->items
; child
++) {
148 uint parent
= child
/ 2;
149 assert(!(*this->data
[child
] < *this->data
[parent
]));
156 * Get the number of items stored in the priority queue.
158 * @return The number of items in the queue
160 inline uint
Length() const
166 * Test if the priority queue is empty.
168 * @return True if empty
170 inline bool IsEmpty() const
172 return this->items
== 0;
176 * Test if the priority queue is full.
178 * @return True if full.
180 inline bool IsFull() const
182 return this->items
>= this->capacity
;
186 * Get the smallest item in the binary tree.
188 * @return The smallest item, or throw assert if empty.
192 assert(!this->IsEmpty());
193 return this->data
[1];
197 * Get the LAST item in the binary tree.
199 * @note The last item is not necessary the biggest!
201 * @return The last item
205 return this->data
[1 + this->items
];
209 * Insert new item into the priority queue, maintaining heap order.
211 * @param new_item The pointer to the new item
213 inline void Include(T
*new_item
)
215 if (this->IsFull()) {
216 assert(this->capacity
< UINT_MAX
/ 2);
219 this->data
= ReallocT
<T
*>(this->data
, this->capacity
+ 1);
222 /* Make place for new item. A gap is now at the end of the tree. */
223 uint gap
= this->HeapifyUp(++items
, new_item
);
224 this->data
[gap
] = new_item
;
229 * Remove and return the smallest (and also first) item
230 * from the priority queue.
232 * @return The pointer to the removed item
236 assert(!this->IsEmpty());
238 T
*first
= this->Begin();
241 /* at index 1 we have a gap now */
242 T
*last
= this->End();
243 uint gap
= this->HeapifyDown(1, last
);
244 /* move last item to the proper place */
245 if (!this->IsEmpty()) this->data
[gap
] = last
;
252 * Remove item at given index from the priority queue.
254 * @param index The position of the item in the heap
256 inline void Remove(uint index
)
258 if (index
< this->items
) {
261 /* at position index we have a gap now */
263 T
*last
= this->End();
264 /* Fix binary tree up and downwards */
265 uint gap
= this->HeapifyUp(index
, last
);
266 gap
= this->HeapifyDown(gap
, last
);
267 /* move last item to the proper place */
268 if (!this->IsEmpty()) this->data
[gap
] = last
;
270 assert(index
== this->items
);
277 * Search for an item in the priority queue.
278 * Matching is done by comparing address of the
281 * @param item The reference to the item
282 * @return The index of the item or zero if not found
284 inline uint
FindIndex(const T
&item
) const
286 if (this->IsEmpty()) return 0;
287 for (T
**ppI
= this->data
+ 1, **ppLast
= ppI
+ this->items
; ppI
<= ppLast
; ppI
++) {
289 return ppI
- this->data
;
296 * Make the priority queue empty.
297 * All remaining items will remain untouched.
305 #endif /* BINARYHEAP_HPP */