d_ary_heap.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. //
  2. //=======================================================================
  3. // Copyright 2009 Trustees of Indiana University
  4. // Authors: Jeremiah J. Willcock, Andrew Lumsdaine
  5. //
  6. // Distributed under the Boost Software License, Version 1.0. (See
  7. // accompanying file LICENSE_1_0.txt or copy at
  8. // http://www.boost.org/LICENSE_1_0.txt)
  9. //=======================================================================
  10. //
  11. #ifndef BOOST_D_ARY_HEAP_HPP
  12. #define BOOST_D_ARY_HEAP_HPP
  13. #include <vector>
  14. #include <cstddef>
  15. #include <algorithm>
  16. #include <utility>
  17. #include <boost/assert.hpp>
  18. #include <boost/static_assert.hpp>
  19. #include <boost/shared_array.hpp>
  20. #include <boost/property_map/property_map.hpp>
  21. // WARNING: it is not safe to copy a d_ary_heap_indirect and then modify one of
  22. // the copies. The class is required to be copyable so it can be passed around
  23. // (without move support from C++11), but it deep-copies the heap contents yet
  24. // shallow-copies the index_in_heap_map.
  25. namespace boost {
  26. // Swap two elements in a property map without assuming they model
  27. // LvaluePropertyMap -- currently not used
  28. template <typename PropMap>
  29. inline void property_map_swap(
  30. PropMap prop_map,
  31. const typename boost::property_traits<PropMap>::key_type& ka,
  32. const typename boost::property_traits<PropMap>::key_type& kb) {
  33. typename boost::property_traits<PropMap>::value_type va = get(prop_map, ka);
  34. put(prop_map, ka, get(prop_map, kb));
  35. put(prop_map, kb, va);
  36. }
  37. namespace detail {
  38. template <typename Value>
  39. class fixed_max_size_vector {
  40. boost::shared_array<Value> m_data;
  41. std::size_t m_size;
  42. public:
  43. typedef std::size_t size_type;
  44. fixed_max_size_vector(std::size_t max_size)
  45. : m_data(new Value[max_size]), m_size(0) {}
  46. std::size_t size() const {return m_size;}
  47. bool empty() const {return m_size == 0;}
  48. Value& operator[](std::size_t i) {return m_data[i];}
  49. const Value& operator[](std::size_t i) const {return m_data[i];}
  50. void push_back(Value v) {m_data[m_size++] = v;}
  51. void pop_back() {--m_size;}
  52. Value& back() {return m_data[m_size - 1];}
  53. const Value& back() const {return m_data[m_size - 1];}
  54. };
  55. }
  56. // D-ary heap using an indirect compare operator (use identity_property_map
  57. // as DistanceMap to get a direct compare operator). This heap appears to be
  58. // commonly used for Dijkstra's algorithm for its good practical performance
  59. // on some platforms; asymptotically, it has an O(lg N) decrease-key
  60. // operation while that can be done in constant time on a relaxed heap. The
  61. // implementation is mostly based on the binary heap page on Wikipedia and
  62. // online sources that state that the operations are the same for d-ary
  63. // heaps. This code is not based on the old Boost d-ary heap code.
  64. //
  65. // - d_ary_heap_indirect is a model of UpdatableQueue as is needed for
  66. // dijkstra_shortest_paths.
  67. //
  68. // - Value must model Assignable.
  69. // - Arity must be at least 2 (optimal value appears to be 4, both in my and
  70. // third-party experiments).
  71. // - IndexInHeapMap must be a ReadWritePropertyMap from Value to
  72. // Container::size_type (to store the index of each stored value within the
  73. // heap for decrease-key aka update).
  74. // - DistanceMap must be a ReadablePropertyMap from Value to something
  75. // (typedef'ed as distance_type).
  76. // - Compare must be a BinaryPredicate used as a less-than operator on
  77. // distance_type.
  78. // - Container must be a random-access, contiguous container (in practice,
  79. // the operations used probably require that it is std::vector<Value>).
  80. //
  81. template <typename Value,
  82. std::size_t Arity,
  83. typename IndexInHeapPropertyMap,
  84. typename DistanceMap,
  85. typename Compare = std::less<Value>,
  86. typename Container = std::vector<Value> >
  87. class d_ary_heap_indirect {
  88. BOOST_STATIC_ASSERT (Arity >= 2);
  89. public:
  90. typedef typename Container::size_type size_type;
  91. typedef Value value_type;
  92. typedef typename boost::property_traits<DistanceMap>::value_type key_type;
  93. typedef DistanceMap key_map;
  94. d_ary_heap_indirect(DistanceMap distance,
  95. IndexInHeapPropertyMap index_in_heap,
  96. const Compare& compare = Compare(),
  97. const Container& data = Container())
  98. : compare(compare), data(data), distance(distance),
  99. index_in_heap(index_in_heap) {}
  100. /* Implicit copy constructor */
  101. /* Implicit assignment operator */
  102. size_type size() const {
  103. return data.size();
  104. }
  105. bool empty() const {
  106. return data.empty();
  107. }
  108. void push(const Value& v) {
  109. size_type index = data.size();
  110. data.push_back(v);
  111. put(index_in_heap, v, index);
  112. preserve_heap_property_up(index);
  113. verify_heap();
  114. }
  115. Value& top() {
  116. BOOST_ASSERT (!this->empty());
  117. return data[0];
  118. }
  119. const Value& top() const {
  120. BOOST_ASSERT (!this->empty());
  121. return data[0];
  122. }
  123. void pop() {
  124. BOOST_ASSERT (!this->empty());
  125. put(index_in_heap, data[0], (size_type)(-1));
  126. if (data.size() != 1) {
  127. data[0] = data.back();
  128. put(index_in_heap, data[0], (size_type)(0));
  129. data.pop_back();
  130. preserve_heap_property_down();
  131. verify_heap();
  132. } else {
  133. data.pop_back();
  134. }
  135. }
  136. // This function assumes the key has been updated (using an external write
  137. // to the distance map or such)
  138. // See http://coding.derkeiler.com/Archive/General/comp.theory/2007-05/msg00043.html
  139. void update(const Value& v) { /* decrease-key */
  140. size_type index = get(index_in_heap, v);
  141. preserve_heap_property_up(index);
  142. verify_heap();
  143. }
  144. bool contains(const Value& v) const {
  145. size_type index = get(index_in_heap, v);
  146. return (index != (size_type)(-1));
  147. }
  148. void push_or_update(const Value& v) { /* insert if not present, else update */
  149. size_type index = get(index_in_heap, v);
  150. if (index == (size_type)(-1)) {
  151. index = data.size();
  152. data.push_back(v);
  153. put(index_in_heap, v, index);
  154. }
  155. preserve_heap_property_up(index);
  156. verify_heap();
  157. }
  158. DistanceMap keys() const {
  159. return distance;
  160. }
  161. private:
  162. Compare compare;
  163. Container data;
  164. DistanceMap distance;
  165. IndexInHeapPropertyMap index_in_heap;
  166. // The distances being compared using compare and that are stored in the
  167. // distance map
  168. typedef typename boost::property_traits<DistanceMap>::value_type distance_type;
  169. // Get the parent of a given node in the heap
  170. static size_type parent(size_type index) {
  171. return (index - 1) / Arity;
  172. }
  173. // Get the child_idx'th child of a given node; 0 <= child_idx < Arity
  174. static size_type child(size_type index, std::size_t child_idx) {
  175. return index * Arity + child_idx + 1;
  176. }
  177. // Swap two elements in the heap by index, updating index_in_heap
  178. void swap_heap_elements(size_type index_a, size_type index_b) {
  179. using std::swap;
  180. Value value_a = data[index_a];
  181. Value value_b = data[index_b];
  182. data[index_a] = value_b;
  183. data[index_b] = value_a;
  184. put(index_in_heap, value_a, index_b);
  185. put(index_in_heap, value_b, index_a);
  186. }
  187. // Emulate the indirect_cmp that is now folded into this heap class
  188. bool compare_indirect(const Value& a, const Value& b) const {
  189. return compare(get(distance, a), get(distance, b));
  190. }
  191. // Verify that the array forms a heap; commented out by default
  192. void verify_heap() const {
  193. // This is a very expensive test so it should be disabled even when
  194. // NDEBUG is not defined
  195. #if 0
  196. for (size_t i = 1; i < data.size(); ++i) {
  197. if (compare_indirect(data[i], data[parent(i)])) {
  198. BOOST_ASSERT (!"Element is smaller than its parent");
  199. }
  200. }
  201. #endif
  202. }
  203. // Starting at a node, move up the tree swapping elements to preserve the
  204. // heap property
  205. void preserve_heap_property_up(size_type index) {
  206. size_type orig_index = index;
  207. size_type num_levels_moved = 0;
  208. // The first loop just saves swaps that need to be done in order to avoid
  209. // aliasing issues in its search; there is a second loop that does the
  210. // necessary swap operations
  211. if (index == 0) return; // Do nothing on root
  212. Value currently_being_moved = data[index];
  213. distance_type currently_being_moved_dist =
  214. get(distance, currently_being_moved);
  215. for (;;) {
  216. if (index == 0) break; // Stop at root
  217. size_type parent_index = parent(index);
  218. Value parent_value = data[parent_index];
  219. if (compare(currently_being_moved_dist, get(distance, parent_value))) {
  220. ++num_levels_moved;
  221. index = parent_index;
  222. continue;
  223. } else {
  224. break; // Heap property satisfied
  225. }
  226. }
  227. // Actually do the moves -- move num_levels_moved elements down in the
  228. // tree, then put currently_being_moved at the top
  229. index = orig_index;
  230. for (size_type i = 0; i < num_levels_moved; ++i) {
  231. size_type parent_index = parent(index);
  232. Value parent_value = data[parent_index];
  233. put(index_in_heap, parent_value, index);
  234. data[index] = parent_value;
  235. index = parent_index;
  236. }
  237. data[index] = currently_being_moved;
  238. put(index_in_heap, currently_being_moved, index);
  239. verify_heap();
  240. }
  241. // From the root, swap elements (each one with its smallest child) if there
  242. // are any parent-child pairs that violate the heap property
  243. void preserve_heap_property_down() {
  244. if (data.empty()) return;
  245. size_type index = 0;
  246. Value currently_being_moved = data[0];
  247. distance_type currently_being_moved_dist =
  248. get(distance, currently_being_moved);
  249. size_type heap_size = data.size();
  250. Value* data_ptr = &data[0];
  251. for (;;) {
  252. size_type first_child_index = child(index, 0);
  253. if (first_child_index >= heap_size) break; /* No children */
  254. Value* child_base_ptr = data_ptr + first_child_index;
  255. size_type smallest_child_index = 0;
  256. distance_type smallest_child_dist = get(distance, child_base_ptr[smallest_child_index]);
  257. if (first_child_index + Arity <= heap_size) {
  258. // Special case for a statically known loop count (common case)
  259. for (size_t i = 1; i < Arity; ++i) {
  260. Value i_value = child_base_ptr[i];
  261. distance_type i_dist = get(distance, i_value);
  262. if (compare(i_dist, smallest_child_dist)) {
  263. smallest_child_index = i;
  264. smallest_child_dist = i_dist;
  265. }
  266. }
  267. } else {
  268. for (size_t i = 1; i < heap_size - first_child_index; ++i) {
  269. distance_type i_dist = get(distance, child_base_ptr[i]);
  270. if (compare(i_dist, smallest_child_dist)) {
  271. smallest_child_index = i;
  272. smallest_child_dist = i_dist;
  273. }
  274. }
  275. }
  276. if (compare(smallest_child_dist, currently_being_moved_dist)) {
  277. swap_heap_elements(smallest_child_index + first_child_index, index);
  278. index = smallest_child_index + first_child_index;
  279. continue;
  280. } else {
  281. break; // Heap property satisfied
  282. }
  283. }
  284. verify_heap();
  285. }
  286. };
  287. } // namespace boost
  288. #endif // BOOST_D_ARY_HEAP_HPP