relaxed_heap.hpp 20 KB

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