MinHeap.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <vector>
  9. // A min-heap is a binary tree whose nodes have weights and with the
  10. // constraint that the weight of a parent node is less than or equal to the
  11. // weights of its children. This data structure may be used as a priority
  12. // queue. If the std::priority_queue interface suffices for your needs, use
  13. // that instead. However, for some geometric algorithms, that interface is
  14. // insufficient for optimal performance. For example, if you have a polyline
  15. // vertices that you want to decimate, each vertex's weight depends on its
  16. // neighbors' locations. If the minimum-weight vertex is removed from the
  17. // min-heap, the neighboring vertex weights must be updated--something that
  18. // is O(1) time when you store the vertices as a doubly linked list. The
  19. // neighbors are already in the min-heap, so modifying their weights without
  20. // removing then from--and then reinserting into--the min-heap requires they
  21. // must be moved to their proper places to restore the invariant of the
  22. // min-heap. With std::priority_queue, you have no direct access to the
  23. // modified vertices, forcing you to search for those vertices, remove them,
  24. // update their weights, and re-insert them. The min-heap implementation here
  25. // does support the update without removal and reinsertion.
  26. //
  27. // The ValueType represents the weight and it must support comparisons
  28. // "<" and "<=". Additional information can be stored in the min-heap for
  29. // convenient access; this is stored as the KeyType. In the (open) polyline
  30. // decimation example, the KeyType is a structure that stores indices to
  31. // a vertex and its neighbors. The following code illustrates the creation
  32. // and use of the min-heap. The Weight() function is whatever you choose to
  33. // guide which vertices are removed first from the polyline.
  34. //
  35. // struct Vertex { int previous, current, next; };
  36. // int numVertices = <number of polyline vertices>;
  37. // std::vector<Vector<N, Real>> positions(numVertices);
  38. // <assign all positions[*]>;
  39. // MinHeap<Vertex, Real> minHeap(numVertices);
  40. // std::vector<MinHeap<Vertex, Real>::Record*> records(numVertices);
  41. // for (int i = 0; i < numVertices; ++i)
  42. // {
  43. // Vertex vertex;
  44. // vertex.previous = (i + numVertices - 1) % numVertices;
  45. // vertex.current = i;
  46. // vertex.next = (i + 1) % numVertices;
  47. // records[i] = minHeap.Insert(vertex, Weight(positions, vertex));
  48. // }
  49. //
  50. // while (minHeap.GetNumElements() >= 2)
  51. // {
  52. // Vertex vertex;
  53. // Real weight;
  54. // minHeap.Remove(vertex, weight);
  55. // <consume the 'vertex' according to your application's needs>;
  56. //
  57. // // Remove 'vertex' from the doubly linked list.
  58. // Vertex& vp = records[vertex.previous]->key;
  59. // Vertex& vc = records[vertex.current]->key;
  60. // Vertex& vn = records[vertex.next]->key;
  61. // vp.next = vc.next;
  62. // vn.previous = vc.previous;
  63. //
  64. // // Update the neighbors' weights in the min-heap.
  65. // minHeap.Update(records[vertex.previous], Weight(positions, vp));
  66. // minHeap.Update(records[vertex.next], Weight(positions, vn));
  67. // }
  68. namespace WwiseGTE
  69. {
  70. template <typename KeyType, typename ValueType>
  71. class MinHeap
  72. {
  73. public:
  74. struct Record
  75. {
  76. KeyType key;
  77. ValueType value;
  78. int index;
  79. };
  80. // Construction. The record 'value' members are uninitialized for
  81. // native types chosen for ValueType. If ValueType is of class type,
  82. // then the default constructor is used to set the 'value' members.
  83. MinHeap(int maxElements = 0)
  84. {
  85. Reset(maxElements);
  86. }
  87. MinHeap(MinHeap const& minHeap)
  88. {
  89. *this = minHeap;
  90. }
  91. // Assignment.
  92. MinHeap& operator=(MinHeap const& minHeap)
  93. {
  94. mNumElements = minHeap.mNumElements;
  95. mRecords = minHeap.mRecords;
  96. mPointers.resize(minHeap.mPointers.size());
  97. for (auto& record : mRecords)
  98. {
  99. mPointers[record.index] = &record;
  100. }
  101. return *this;
  102. }
  103. // Clear the min-heap so that it has the specified max elements,
  104. // mNumElements is zero, and mPointers are set to the natural ordering
  105. // of mRecords.
  106. void Reset(int maxElements)
  107. {
  108. mNumElements = 0;
  109. if (maxElements > 0)
  110. {
  111. mRecords.resize(maxElements);
  112. mPointers.resize(maxElements);
  113. for (int i = 0; i < maxElements; ++i)
  114. {
  115. mPointers[i] = &mRecords[i];
  116. mPointers[i]->index = i;
  117. }
  118. }
  119. else
  120. {
  121. mRecords.clear();
  122. mPointers.clear();
  123. }
  124. }
  125. // Get the remaining number of elements in the min-heap. This number
  126. // is in the range {0..maxElements}.
  127. inline int GetNumElements() const
  128. {
  129. return mNumElements;
  130. }
  131. // Get the root of the min-heap. The return value is 'true' whenever
  132. // the min-heap is not empty. This function reads the root but does
  133. // not remove the element from the min-heap.
  134. bool GetMinimum(KeyType& key, ValueType& value) const
  135. {
  136. if (mNumElements > 0)
  137. {
  138. key = mPointers[0]->key;
  139. value = mPointers[0]->value;
  140. return true;
  141. }
  142. else
  143. {
  144. return false;
  145. }
  146. }
  147. // Insert into the min-heap the 'value' that corresponds to the 'key'.
  148. // The return value is a pointer to the heap record that stores a copy
  149. // of 'value', and the pointer value is constant for the life of the
  150. // min-heap. If you must update a member of the min-heap, say, as
  151. // illustrated in the polyline decimation example, pass the pointer to
  152. // Update:
  153. // auto* valueRecord = minHeap.Insert(key, value);
  154. // <do whatever>;
  155. // minHeap.Update(valueRecord, newValue).
  156. Record* Insert(KeyType const& key, ValueType const& value)
  157. {
  158. // Return immediately when the heap is full.
  159. if (mNumElements == static_cast<int>(mRecords.size()))
  160. {
  161. return nullptr;
  162. }
  163. // Store the input information in the last heap record, which is
  164. // the last leaf in the tree.
  165. int child = mNumElements++;
  166. Record* record = mPointers[child];
  167. record->key = key;
  168. record->value = value;
  169. // Propagate the information toward the root of the tree until it
  170. // reaches its correct position, thus restoring the tree to a
  171. // valid heap.
  172. while (child > 0)
  173. {
  174. int parent = (child - 1) / 2;
  175. if (mPointers[parent]->value <= value)
  176. {
  177. // The parent has a value smaller than or equal to the
  178. // child's value, so we now have a valid heap.
  179. break;
  180. }
  181. // The parent has a larger value than the child's value. Swap
  182. // the parent and child:
  183. // Move the parent into the child's slot.
  184. mPointers[child] = mPointers[parent];
  185. mPointers[child]->index = child;
  186. // Move the child into the parent's slot.
  187. mPointers[parent] = record;
  188. mPointers[parent]->index = parent;
  189. child = parent;
  190. }
  191. return mPointers[child];
  192. }
  193. // Remove the root of the heap and return its 'key' and 'value
  194. // members. The root contains the minimum value of all heap elements.
  195. // The return value is 'true' whenever the min-heap was not empty
  196. // before the Remove call.
  197. bool Remove(KeyType& key, ValueType& value)
  198. {
  199. // Return immediately when the heap is empty.
  200. if (mNumElements == 0)
  201. {
  202. return false;
  203. }
  204. // Get the information from the root of the heap.
  205. Record* root = mPointers[0];
  206. key = root->key;
  207. value = root->value;
  208. // Restore the tree to a heap. Abstractly, record is the new root
  209. // of the heap. It is moved down the tree via parent-child swaps
  210. // until it is in a location that restores the tree to a heap.
  211. int last = --mNumElements;
  212. Record* record = mPointers[last];
  213. int parent = 0, child = 1;
  214. while (child <= last)
  215. {
  216. if (child < last)
  217. {
  218. // Select the child with smallest value to be the one that
  219. // is swapped with the parent, if necessary.
  220. int childP1 = child + 1;
  221. if (mPointers[childP1]->value < mPointers[child]->value)
  222. {
  223. child = childP1;
  224. }
  225. }
  226. if (record->value <= mPointers[child]->value)
  227. {
  228. // The tree is now a heap.
  229. break;
  230. }
  231. // Move the child into the parent's slot.
  232. mPointers[parent] = mPointers[child];
  233. mPointers[parent]->index = parent;
  234. parent = child;
  235. child = 2 * child + 1;
  236. }
  237. // The previous 'last' record was moved to the root and propagated
  238. // down the tree to its final resting place, restoring the tree to
  239. // a heap. The slot mPointers[parent] is that resting place.
  240. mPointers[parent] = record;
  241. mPointers[parent]->index = parent;
  242. // The old root record must not be lost. Attach it to the slot
  243. // that contained the old last record.
  244. mPointers[last] = root;
  245. mPointers[last]->index = last;
  246. return true;
  247. }
  248. // The value of a heap record must be modified through this function
  249. // call. The side effect is that the heap is updated accordingly to
  250. // restore the data structure to a min-heap. The input 'record'
  251. // should be a pointer returned by Insert(value); see the comments for
  252. // the Insert() function.
  253. void Update(Record* record, ValueType const& value)
  254. {
  255. // Return immediately on invalid record.
  256. if (!record)
  257. {
  258. return;
  259. }
  260. int parent, child, childP1, maxChild;
  261. if (record->value < value)
  262. {
  263. record->value = value;
  264. // The new value is larger than the old value. Propagate it
  265. // toward the leaves.
  266. parent = record->index;
  267. child = 2 * parent + 1;
  268. while (child < mNumElements)
  269. {
  270. // At least one child exists. Locate the one of maximum
  271. // value.
  272. childP1 = child + 1;
  273. if (childP1 < mNumElements)
  274. {
  275. // Two children exist.
  276. if (mPointers[child]->value <= mPointers[childP1]->value)
  277. {
  278. maxChild = child;
  279. }
  280. else
  281. {
  282. maxChild = childP1;
  283. }
  284. }
  285. else
  286. {
  287. // One child exists.
  288. maxChild = child;
  289. }
  290. if (value <= mPointers[maxChild]->value)
  291. {
  292. // The new value is in the correct place to restore
  293. // the tree to a heap.
  294. break;
  295. }
  296. // The child has a larger value than the parent's value.
  297. // Swap the parent and child:
  298. // Move the child into the parent's slot.
  299. mPointers[parent] = mPointers[maxChild];
  300. mPointers[parent]->index = parent;
  301. // Move the parent into the child's slot.
  302. mPointers[maxChild] = record;
  303. mPointers[maxChild]->index = maxChild;
  304. parent = maxChild;
  305. child = 2 * parent + 1;
  306. }
  307. }
  308. else if (value < record->value)
  309. {
  310. record->value = value;
  311. // The new weight is smaller than the old weight. Propagate
  312. // it toward the root.
  313. child = record->index;
  314. while (child > 0)
  315. {
  316. // A parent exists.
  317. parent = (child - 1) / 2;
  318. if (mPointers[parent]->value <= value)
  319. {
  320. // The new value is in the correct place to restore
  321. // the tree to a heap.
  322. break;
  323. }
  324. // The parent has a smaller value than the child's value.
  325. // Swap the child and parent.
  326. // Move the parent into the child's slot.
  327. mPointers[child] = mPointers[parent];
  328. mPointers[child]->index = child;
  329. // Move the child into the parent's slot.
  330. mPointers[parent] = record;
  331. mPointers[parent]->index = parent;
  332. child = parent;
  333. }
  334. }
  335. }
  336. // Support for debugging. The functions test whether the data
  337. // structure is a valid min-heap.
  338. bool IsValid() const
  339. {
  340. for (int child = 0; child < mNumElements; ++child)
  341. {
  342. int parent = (child - 1) / 2;
  343. if (parent > 0)
  344. {
  345. if (mPointers[child]->value < mPointers[parent]->value)
  346. {
  347. return false;
  348. }
  349. if (mPointers[parent]->index != parent)
  350. {
  351. return false;
  352. }
  353. }
  354. }
  355. return true;
  356. }
  357. private:
  358. // A 2-level storage system is used. The pointers have two roles.
  359. // Firstly, they are unique to each inserted value in order to support
  360. // the Update() capability of the min-heap. Secondly, they avoid
  361. // potentially expensive copying of Record objects as sorting occurs
  362. // in the heap.
  363. int mNumElements;
  364. std::vector<Record> mRecords;
  365. std::vector<Record*> mPointers;
  366. };
  367. }