d_ary_heap.hpp 12 KB

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