relaxed_heap.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Copyright 2004 The Trustees of Indiana University.
  2. // Use, modification and distribution is subject to the Boost Software
  3. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // Authors: Douglas Gregor
  6. // Andrew Lumsdaine
  7. #ifndef BOOST_RELAXED_HEAP_HEADER
  8. #define BOOST_RELAXED_HEAP_HEADER
  9. #include <boost/config/header_deprecated.hpp>
  10. BOOST_HEADER_DEPRECATED("the standard heap functions")
  11. #include <functional>
  12. #include <boost/property_map/property_map.hpp>
  13. #include <boost/optional.hpp>
  14. #include <vector>
  15. #include <climits> // for CHAR_BIT
  16. #include <boost/none.hpp>
  17. #ifdef BOOST_RELAXED_HEAP_DEBUG
  18. #include <iostream>
  19. #endif // BOOST_RELAXED_HEAP_DEBUG
  20. #if defined(BOOST_MSVC)
  21. #pragma warning(push)
  22. #pragma warning(disable : 4355) // complaint about using 'this' to
  23. #endif // initialize a member
  24. namespace boost
  25. {
  26. template < typename IndexedType, typename Compare = std::less< IndexedType >,
  27. typename ID = identity_property_map >
  28. class relaxed_heap
  29. {
  30. struct group;
  31. typedef relaxed_heap self_type;
  32. typedef std::size_t rank_type;
  33. public:
  34. typedef IndexedType value_type;
  35. typedef rank_type size_type;
  36. private:
  37. /**
  38. * The kind of key that a group has. The actual values are discussed
  39. * in-depth in the documentation of the @c kind field of the @c group
  40. * structure. Note that the order of the enumerators *IS* important
  41. * and must not be changed.
  42. */
  43. enum group_key_kind
  44. {
  45. smallest_key,
  46. stored_key,
  47. largest_key
  48. };
  49. struct group
  50. {
  51. explicit group(group_key_kind kind = largest_key)
  52. : kind(kind), parent(this), rank(0)
  53. {
  54. }
  55. /** The value associated with this group. This value is only valid
  56. * when @c kind!=largest_key (which indicates a deleted
  57. * element). Note that the use of boost::optional increases the
  58. * memory requirements slightly but does not result in extraneous
  59. * memory allocations or deallocations. The optional could be
  60. * eliminated when @c value_type is a model of
  61. * DefaultConstructible.
  62. */
  63. ::boost::optional< value_type > value;
  64. /**
  65. * The kind of key stored at this group. This may be @c
  66. * smallest_key, which indicates that the key is infinitely small;
  67. * @c largest_key, which indicates that the key is infinitely
  68. * large; or @c stored_key, which means that the key is unknown,
  69. * but its relationship to other keys can be determined via the
  70. * comparison function object.
  71. */
  72. group_key_kind kind;
  73. /// The parent of this group. Will only be NULL for the dummy root group
  74. group* parent;
  75. /// The rank of this group. Equivalent to the number of children in
  76. /// the group.
  77. rank_type rank;
  78. /** The children of this group. For the dummy root group, these are
  79. * the roots. This is an array of length log n containing pointers
  80. * to the child groups.
  81. */
  82. group** children;
  83. };
  84. size_type log_base_2(size_type n) // log2 is a macro on some platforms
  85. {
  86. size_type leading_zeroes = 0;
  87. do
  88. {
  89. size_type next = n << 1;
  90. if (n == (next >> 1))
  91. {
  92. ++leading_zeroes;
  93. n = next;
  94. }
  95. else
  96. {
  97. break;
  98. }
  99. } while (true);
  100. return sizeof(size_type) * CHAR_BIT - leading_zeroes - 1;
  101. }
  102. public:
  103. relaxed_heap(
  104. size_type n, const Compare& compare = Compare(), const ID& id = ID())
  105. : compare(compare), id(id), root(smallest_key), groups(n), smallest_value(0)
  106. {
  107. if (n == 0)
  108. {
  109. root.children = new group*[1];
  110. return;
  111. }
  112. log_n = log_base_2(n);
  113. if (log_n == 0)
  114. log_n = 1;
  115. size_type g = n / log_n;
  116. if (n % log_n > 0)
  117. ++g;
  118. size_type log_g = log_base_2(g);
  119. size_type r = log_g;
  120. // Reserve an appropriate amount of space for data structures, so
  121. // that we do not need to expand them.
  122. index_to_group.resize(g);
  123. A.resize(r + 1, 0);
  124. root.rank = r + 1;
  125. root.children = new group*[(log_g + 1) * (g + 1)];
  126. for (rank_type i = 0; i < r + 1; ++i)
  127. root.children[i] = 0;
  128. // Build initial heap
  129. size_type idx = 0;
  130. while (idx < g)
  131. {
  132. root.children[r] = &index_to_group[idx];
  133. idx = build_tree(root, idx, r, log_g + 1);
  134. if (idx != g)
  135. r = static_cast< size_type >(log_base_2(g - idx));
  136. }
  137. }
  138. ~relaxed_heap() { delete[] root.children; }
  139. void push(const value_type& x)
  140. {
  141. groups[get(id, x)] = x;
  142. update(x);
  143. }
  144. void update(const value_type& x)
  145. {
  146. group* a = &index_to_group[get(id, x) / log_n];
  147. if (!a->value || *a->value == x || compare(x, *a->value))
  148. {
  149. if (a != smallest_value)
  150. smallest_value = 0;
  151. a->kind = stored_key;
  152. a->value = x;
  153. promote(a);
  154. }
  155. }
  156. void remove(const value_type& x)
  157. {
  158. group* a = &index_to_group[get(id, x) / log_n];
  159. assert(groups[get(id, x)]);
  160. a->value = x;
  161. a->kind = smallest_key;
  162. promote(a);
  163. smallest_value = a;
  164. pop();
  165. }
  166. value_type& top()
  167. {
  168. find_smallest();
  169. assert(smallest_value->value != none);
  170. return *smallest_value->value;
  171. }
  172. const value_type& top() const
  173. {
  174. find_smallest();
  175. assert(smallest_value->value != none);
  176. return *smallest_value->value;
  177. }
  178. bool empty() const
  179. {
  180. find_smallest();
  181. return !smallest_value || (smallest_value->kind == largest_key);
  182. }
  183. bool contains(const value_type& x) const
  184. {
  185. return static_cast< bool >(groups[get(id, x)]);
  186. }
  187. void pop()
  188. {
  189. // Fill in smallest_value. This is the group x.
  190. find_smallest();
  191. group* x = smallest_value;
  192. smallest_value = 0;
  193. // Make x a leaf, giving it the smallest value within its group
  194. rank_type r = x->rank;
  195. group* p = x->parent;
  196. {
  197. assert(x->value != none);
  198. // Find x's group
  199. size_type start = get(id, *x->value) - get(id, *x->value) % log_n;
  200. size_type end = start + log_n;
  201. if (end > groups.size())
  202. end = groups.size();
  203. // Remove the smallest value from the group, and find the new
  204. // smallest value.
  205. groups[get(id, *x->value)].reset();
  206. x->value.reset();
  207. x->kind = largest_key;
  208. for (size_type i = start; i < end; ++i)
  209. {
  210. if (groups[i] && (!x->value || compare(*groups[i], *x->value)))
  211. {
  212. x->kind = stored_key;
  213. x->value = groups[i];
  214. }
  215. }
  216. }
  217. x->rank = 0;
  218. // Combine prior children of x with x
  219. group* y = x;
  220. for (size_type c = 0; c < r; ++c)
  221. {
  222. group* child = x->children[c];
  223. if (A[c] == child)
  224. A[c] = 0;
  225. y = combine(y, child);
  226. }
  227. // If we got back something other than x, let y take x's place
  228. if (y != x)
  229. {
  230. y->parent = p;
  231. p->children[r] = y;
  232. assert(r == y->rank);
  233. if (A[y->rank] == x)
  234. A[y->rank] = do_compare(y, p) ? y : 0;
  235. }
  236. }
  237. #ifdef BOOST_RELAXED_HEAP_DEBUG
  238. /*************************************************************************
  239. * Debugging support *
  240. *************************************************************************/
  241. void dump_tree() { dump_tree(std::cout); }
  242. void dump_tree(std::ostream& out) { dump_tree(out, &root); }
  243. void dump_tree(std::ostream& out, group* p, bool in_progress = false)
  244. {
  245. if (!in_progress)
  246. {
  247. out << "digraph heap {\n"
  248. << " edge[dir=\"back\"];\n";
  249. }
  250. size_type p_index = 0;
  251. if (p != &root)
  252. while (&index_to_group[p_index] != p)
  253. ++p_index;
  254. for (size_type i = 0; i < p->rank; ++i)
  255. {
  256. group* c = p->children[i];
  257. if (c)
  258. {
  259. size_type c_index = 0;
  260. if (c != &root)
  261. while (&index_to_group[c_index] != c)
  262. ++c_index;
  263. out << " ";
  264. if (p == &root)
  265. out << 'p';
  266. else
  267. out << p_index;
  268. out << " -> ";
  269. if (c == &root)
  270. out << 'p';
  271. else
  272. out << c_index;
  273. if (A[c->rank] == c)
  274. out << " [style=\"dotted\"]";
  275. out << ";\n";
  276. dump_tree(out, c, true);
  277. // Emit node information
  278. out << " ";
  279. if (c == &root)
  280. out << 'p';
  281. else
  282. out << c_index;
  283. out << " [label=\"";
  284. if (c == &root)
  285. out << 'p';
  286. else
  287. out << c_index;
  288. out << ":";
  289. size_type start = c_index * log_n;
  290. size_type end = start + log_n;
  291. if (end > groups.size())
  292. end = groups.size();
  293. while (start != end)
  294. {
  295. if (groups[start])
  296. {
  297. out << " " << get(id, *groups[start]);
  298. if (*groups[start] == *c->value)
  299. out << "(*)";
  300. }
  301. ++start;
  302. }
  303. out << '"';
  304. if (do_compare(c, p))
  305. {
  306. out << " ";
  307. if (c == &root)
  308. out << 'p';
  309. else
  310. out << c_index;
  311. out << ", style=\"filled\", fillcolor=\"gray\"";
  312. }
  313. out << "];\n";
  314. }
  315. else
  316. {
  317. assert(p->parent == p);
  318. }
  319. }
  320. if (!in_progress)
  321. out << "}\n";
  322. }
  323. bool valid()
  324. {
  325. // Check that the ranks in the A array match the ranks of the
  326. // groups stored there. Also, the active groups must be the last
  327. // child of their parent.
  328. for (size_type r = 0; r < A.size(); ++r)
  329. {
  330. if (A[r] && A[r]->rank != r)
  331. return false;
  332. if (A[r] && A[r]->parent->children[A[r]->parent->rank - 1] != A[r])
  333. return false;
  334. }
  335. // The root must have no value and a key of -Infinity
  336. if (root.kind != smallest_key)
  337. return false;
  338. return valid(&root);
  339. }
  340. bool valid(group* p)
  341. {
  342. for (size_type i = 0; i < p->rank; ++i)
  343. {
  344. group* c = p->children[i];
  345. if (c)
  346. {
  347. // Check link structure
  348. if (c->parent != p)
  349. return false;
  350. if (c->rank != i)
  351. return false;
  352. // A bad group must be active
  353. if (do_compare(c, p) && A[i] != c)
  354. return false;
  355. // Check recursively
  356. if (!valid(c))
  357. return false;
  358. }
  359. else
  360. {
  361. // Only the root may
  362. if (p != &root)
  363. return false;
  364. }
  365. }
  366. return true;
  367. }
  368. #endif // BOOST_RELAXED_HEAP_DEBUG
  369. private:
  370. size_type build_tree(
  371. group& parent, size_type idx, size_type r, size_type max_rank)
  372. {
  373. group& this_group = index_to_group[idx];
  374. this_group.parent = &parent;
  375. ++idx;
  376. this_group.children = root.children + (idx * max_rank);
  377. this_group.rank = r;
  378. for (size_type i = 0; i < r; ++i)
  379. {
  380. this_group.children[i] = &index_to_group[idx];
  381. idx = build_tree(this_group, idx, i, max_rank);
  382. }
  383. return idx;
  384. }
  385. void find_smallest() const
  386. {
  387. group** roots = root.children;
  388. if (!smallest_value)
  389. {
  390. std::size_t i;
  391. for (i = 0; i < root.rank; ++i)
  392. {
  393. if (roots[i]
  394. && (!smallest_value
  395. || do_compare(roots[i], smallest_value)))
  396. {
  397. smallest_value = roots[i];
  398. }
  399. }
  400. for (i = 0; i < A.size(); ++i)
  401. {
  402. if (A[i]
  403. && (!smallest_value || do_compare(A[i], smallest_value)))
  404. smallest_value = A[i];
  405. }
  406. }
  407. }
  408. bool do_compare(group* x, group* y) const
  409. {
  410. return (x->kind < y->kind
  411. || (x->kind == y->kind && x->kind == stored_key
  412. && compare(*x->value, *y->value)));
  413. }
  414. void promote(group* a)
  415. {
  416. assert(a != 0);
  417. rank_type r = a->rank;
  418. group* p = a->parent;
  419. assert(p != 0);
  420. if (do_compare(a, p))
  421. {
  422. // s is the rank + 1 sibling
  423. group* s = p->rank > r + 1 ? p->children[r + 1] : 0;
  424. // If a is the last child of p
  425. if (r == p->rank - 1)
  426. {
  427. if (!A[r])
  428. A[r] = a;
  429. else if (A[r] != a)
  430. pair_transform(a);
  431. }
  432. else
  433. {
  434. assert(s != 0);
  435. if (A[r + 1] == s)
  436. active_sibling_transform(a, s);
  437. else
  438. good_sibling_transform(a, s);
  439. }
  440. }
  441. }
  442. group* combine(group* a1, group* a2)
  443. {
  444. assert(a1->rank == a2->rank);
  445. if (do_compare(a2, a1))
  446. do_swap(a1, a2);
  447. a1->children[a1->rank++] = a2;
  448. a2->parent = a1;
  449. clean(a1);
  450. return a1;
  451. }
  452. void clean(group* q)
  453. {
  454. if (2 > q->rank)
  455. return;
  456. group* qp = q->children[q->rank - 1];
  457. rank_type s = q->rank - 2;
  458. group* x = q->children[s];
  459. group* xp = qp->children[s];
  460. assert(s == x->rank);
  461. // If x is active, swap x and xp
  462. if (A[s] == x)
  463. {
  464. q->children[s] = xp;
  465. xp->parent = q;
  466. qp->children[s] = x;
  467. x->parent = qp;
  468. }
  469. }
  470. void pair_transform(group* a)
  471. {
  472. #if defined(BOOST_RELAXED_HEAP_DEBUG) && BOOST_RELAXED_HEAP_DEBUG > 1
  473. std::cerr << "- pair transform\n";
  474. #endif
  475. rank_type r = a->rank;
  476. // p is a's parent
  477. group* p = a->parent;
  478. assert(p != 0);
  479. // g is p's parent (a's grandparent)
  480. group* g = p->parent;
  481. assert(g != 0);
  482. // a' <- A(r)
  483. assert(A[r] != 0);
  484. group* ap = A[r];
  485. assert(ap != 0);
  486. // A(r) <- nil
  487. A[r] = 0;
  488. // let a' have parent p'
  489. group* pp = ap->parent;
  490. assert(pp != 0);
  491. // let a' have grandparent g'
  492. group* gp = pp->parent;
  493. assert(gp != 0);
  494. // Remove a and a' from their parents
  495. assert(ap
  496. == pp->children[pp->rank - 1]); // Guaranteed because ap is active
  497. --pp->rank;
  498. // Guaranteed by caller
  499. assert(a == p->children[p->rank - 1]);
  500. --p->rank;
  501. // Note: a, ap, p, pp all have rank r
  502. if (do_compare(pp, p))
  503. {
  504. do_swap(a, ap);
  505. do_swap(p, pp);
  506. do_swap(g, gp);
  507. }
  508. // Assuming k(p) <= k(p')
  509. // make p' the rank r child of p
  510. assert(r == p->rank);
  511. p->children[p->rank++] = pp;
  512. pp->parent = p;
  513. // Combine a, ap into a rank r+1 group c
  514. group* c = combine(a, ap);
  515. // make c the rank r+1 child of g'
  516. assert(gp->rank > r + 1);
  517. gp->children[r + 1] = c;
  518. c->parent = gp;
  519. #if defined(BOOST_RELAXED_HEAP_DEBUG) && BOOST_RELAXED_HEAP_DEBUG > 1
  520. std::cerr << "After pair transform...\n";
  521. dump_tree();
  522. #endif
  523. if (A[r + 1] == pp)
  524. A[r + 1] = c;
  525. else
  526. promote(c);
  527. }
  528. void active_sibling_transform(group* a, group* s)
  529. {
  530. #if defined(BOOST_RELAXED_HEAP_DEBUG) && BOOST_RELAXED_HEAP_DEBUG > 1
  531. std::cerr << "- active sibling transform\n";
  532. #endif
  533. group* p = a->parent;
  534. group* g = p->parent;
  535. // remove a, s from their parents
  536. assert(s->parent == p);
  537. assert(p->children[p->rank - 1] == s);
  538. --p->rank;
  539. assert(p->children[p->rank - 1] == a);
  540. --p->rank;
  541. rank_type r = a->rank;
  542. A[r + 1] = 0;
  543. a = combine(p, a);
  544. group* c = combine(a, s);
  545. // make c the rank r+2 child of g
  546. assert(g->children[r + 2] == p);
  547. g->children[r + 2] = c;
  548. c->parent = g;
  549. if (A[r + 2] == p)
  550. A[r + 2] = c;
  551. else
  552. promote(c);
  553. }
  554. void good_sibling_transform(group* a, group* s)
  555. {
  556. #if defined(BOOST_RELAXED_HEAP_DEBUG) && BOOST_RELAXED_HEAP_DEBUG > 1
  557. std::cerr << "- good sibling transform\n";
  558. #endif
  559. rank_type r = a->rank;
  560. group* c = s->children[s->rank - 1];
  561. assert(c->rank == r);
  562. if (A[r] == c)
  563. {
  564. #if defined(BOOST_RELAXED_HEAP_DEBUG) && BOOST_RELAXED_HEAP_DEBUG > 1
  565. std::cerr << "- good sibling pair transform\n";
  566. #endif
  567. A[r] = 0;
  568. group* p = a->parent;
  569. // Remove c from its parent
  570. --s->rank;
  571. // Make s the rank r child of p
  572. s->parent = p;
  573. p->children[r] = s;
  574. // combine a, c and let the result by the rank r+1 child of p
  575. assert(p->rank > r + 1);
  576. group* x = combine(a, c);
  577. x->parent = p;
  578. p->children[r + 1] = x;
  579. if (A[r + 1] == s)
  580. A[r + 1] = x;
  581. else
  582. promote(x);
  583. #if defined(BOOST_RELAXED_HEAP_DEBUG) && BOOST_RELAXED_HEAP_DEBUG > 1
  584. dump_tree(std::cerr);
  585. #endif
  586. // pair_transform(a);
  587. }
  588. else
  589. {
  590. // Clean operation
  591. group* p = a->parent;
  592. s->children[r] = a;
  593. a->parent = s;
  594. p->children[r] = c;
  595. c->parent = p;
  596. promote(a);
  597. }
  598. }
  599. static void do_swap(group*& x, group*& y)
  600. {
  601. group* tmp = x;
  602. x = y;
  603. y = tmp;
  604. }
  605. /// Function object that compares two values in the heap
  606. Compare compare;
  607. /// Mapping from values to indices in the range [0, n).
  608. ID id;
  609. /** The root group of the queue. This group is special because it will
  610. * never store a value, but it acts as a parent to all of the
  611. * roots. Thus, its list of children is the list of roots.
  612. */
  613. group root;
  614. /** Mapping from the group index of a value to the group associated
  615. * with that value. If a value is not in the queue, then the "value"
  616. * field will be empty.
  617. */
  618. std::vector< group > index_to_group;
  619. /** Flat data structure containing the values in each of the
  620. * groups. It will be indexed via the id of the values. The groups
  621. * are each log_n long, with the last group potentially being
  622. * smaller.
  623. */
  624. std::vector< ::boost::optional< value_type > > groups;
  625. /** The list of active groups, indexed by rank. When A[r] is null,
  626. * there is no active group of rank r. Otherwise, A[r] is the active
  627. * group of rank r.
  628. */
  629. std::vector< group* > A;
  630. /** The group containing the smallest value in the queue, which must
  631. * be either a root or an active group. If this group is null, then we
  632. * will need to search for this group when it is needed.
  633. */
  634. mutable group* smallest_value;
  635. /// Cached value log_base_2(n)
  636. size_type log_n;
  637. };
  638. } // end namespace boost
  639. #if defined(BOOST_MSVC)
  640. #pragma warning(pop)
  641. #endif
  642. #endif // BOOST_RELAXED_HEAP_HEADER