Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_fibonacci_heap.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
44# ifndef TPL_FIBONACCI_HEAP_H
45# define TPL_FIBONACCI_HEAP_H
46
47# include <ah-concepts.H>
48# include <ahUtils.H>
49# include <ah-errors.H>
50# include <ahFunctional.H>
51# include <vector>
52# include <algorithm>
53# include <memory>
54# include <type_traits>
55# include <utility>
56
57namespace Aleph
58{
113 template <typename T, class Compare = Aleph::less<T>>
114 requires StrictWeakOrder<Compare, T>
116 {
117 public:
129 struct Node
130 {
132 Node *parent = nullptr;
133 Node *child = nullptr;
134 Node *left = this;
135 Node *right = this;
136 size_t degree = 0;
137 bool mark = false;
138
140 explicit Node(const T & d) : data(d) {}
141
143 explicit Node(T && d) noexcept(std::is_nothrow_move_constructible_v<T>)
144 : data(std::move(d)) {}
145
157 template <typename Arg, typename... Args>
158 requires ((sizeof...(Args) >= 1) or
159 (not std::is_same_v<std::decay_t<Arg>, T> and
160 not std::is_same_v<std::decay_t<Arg>, Node>))
161 explicit Node(Arg&& arg, Args&&... args)
162 : data(std::forward<Arg>(arg), std::forward<Args>(args)...) {}
163 };
164
165 private:
172 static constexpr size_t MAX_DEGREE = 128;
173
174 Node *min_node = nullptr;
175 size_t num_nodes = 0;
176 Compare cmp;
177
184 std::vector<Node *> consolidate_array_;
185
194 static void link(Node *y, Node *x)
195 {
196 // Remove y from root list
197 y->left->right = y->right;
198 y->right->left = y->left;
199
200 // Make y a child of x
201 y->parent = x;
202 if (x->child == nullptr)
203 {
204 x->child = y;
205 y->right = y;
206 y->left = y;
207 }
208 else
209 {
210 y->left = x->child;
211 y->right = x->child->right;
212 x->child->right->left = y;
213 x->child->right = y;
214 }
215
216 ++x->degree;
217 y->mark = false;
218 }
219
232 {
233 if (min_node == nullptr)
234 return;
235
236 // Use member vector to avoid repeated allocations
237 if (consolidate_array_.size() < MAX_DEGREE)
238 consolidate_array_.resize(MAX_DEGREE, nullptr);
239 else
240 std::fill(consolidate_array_.begin(), consolidate_array_.end(), nullptr);
241
242 // The roots are counted and then visited from min_node on, by their
243 // right links. Only visited roots leave the list when they are linked,
244 // so each root but the last still links to the next one when visited
245 size_t num_roots = 0;
246 Node *curr = min_node;
247 do
248 {
249 ++num_roots;
250 curr = curr->right;
251 }
252 while (curr != min_node);
253
254 for (; num_roots > 0; --num_roots)
255 {
256 Node *x = curr;
257 curr = curr->right;
258 size_t d = x->degree;
259
260 while (d < MAX_DEGREE && consolidate_array_[d] != nullptr)
261 {
263 // Ensure x has the smaller key (maintains heap property)
264 if (cmp(y->data, x->data))
265 std::swap(x, y);
266
267 link(y, x);
268 min_node = x; // a root, if a later comparison throws
269 consolidate_array_[d] = nullptr;
270 ++d;
271 }
272
273 if (d < MAX_DEGREE)
274 consolidate_array_[d] = x;
275 }
276
277 // Find the new minimum, by degree; each root moves right after the
278 // minimum found so far. The roots move within the list, so it keeps
279 // all of them if the comparison throws
280 min_node = nullptr;
281 for (size_t i = 0; i < MAX_DEGREE; ++i)
282 {
283 Node *x = consolidate_array_[i];
284 if (x == nullptr)
285 continue;
286
287 x->parent = nullptr;
288 if (min_node == nullptr)
289 {
290 min_node = x;
291 continue;
292 }
293
294 // Move x right after min_node
295 x->left->right = x->right;
296 x->right->left = x->left;
297 x->left = min_node;
298 x->right = min_node->right;
299 min_node->right->left = x;
300 min_node->right = x;
301
302 if (cmp(x->data, min_node->data))
303 min_node = x;
304 }
305 }
306
313 void cut(Node *x, Node *y)
314 {
315 // Remove x from the child list of y
316 if (x->right == x)
317 y->child = nullptr;
318 else
319 {
320 x->left->right = x->right;
321 x->right->left = x->left;
322 if (y->child == x)
323 y->child = x->right;
324 }
325 --y->degree;
326
327 // Add x to the root list
328 x->left = min_node;
329 x->right = min_node->right;
330 min_node->right->left = x;
331 min_node->right = x;
332 x->parent = nullptr;
333 x->mark = false;
334 }
335
346 {
347 while (y != nullptr)
348 {
349 Node *z = y->parent;
350 if (z == nullptr)
351 break;
352
353 if (not y->mark)
354 {
355 y->mark = true;
356 break;
357 }
358 cut(y, z);
359 y = z; // Continue with parent (iterative instead of recursive)
360 }
361 }
362
372 void take_root_out(Node *z) noexcept
373 {
374 if (z->child != nullptr)
375 {
376 // First, set all children's parent to nullptr
377 Node *child = z->child;
378 do
379 {
380 child->parent = nullptr;
381 child = child->right;
382 }
383 while (child != z->child);
384
385 // Splice the child list into the root list
386 Node *child_left = z->child->left;
387 Node *z_right = z->right;
388
389 z->right = z->child;
390 z->child->left = z;
391 child_left->right = z_right;
392 z_right->left = child_left;
393
394 z->child = nullptr;
395 z->degree = 0;
396 }
397
398 if (z == z->right)
399 min_node = nullptr; // z was the only root
400 else
401 {
402 z->left->right = z->right;
403 z->right->left = z->left;
404 min_node = z->right;
405 }
406 }
407
422 void put_root_back(Node *z, Node *min) noexcept
423 {
424 if (min_node == nullptr)
425 z->left = z->right = z;
426 else
427 {
428 z->left = min_node;
429 z->right = min_node->right;
430 min_node->right->left = z;
431 min_node->right = z;
432 }
433 min_node = z; // a root for cut() to link after
434
435 if (Node *over = min->parent; over != nullptr)
436 {
437 cut(min, over);
438 cascading_cut(over); // it has lost a child
439 }
440 min_node = min;
441 }
442
454 {
455 if (node == nullptr)
456 return;
457
458 // Break the circular list to avoid use-after-free when checking
459 // loop termination condition against a deleted node
460 node->left->right = nullptr;
461
462 Node *curr = node;
463 while (curr != nullptr)
464 {
465 if (curr->child != nullptr) // its children go next in the list
466 {
467 Node *last_child = curr->child->left;
468 last_child->right = curr->right;
469 curr->right = curr->child;
470 }
471 Node *next = curr->right;
472 delete curr;
473 curr = next;
474 }
475 }
476
486 {
487 node->parent = nullptr;
488 if (min_node == nullptr)
489 {
490 min_node = node;
491 node->left = node;
492 node->right = node;
493 }
494 else
495 {
496 const bool is_min = cmp(node->data, min_node->data);
497
498 node->left = min_node;
499 node->right = min_node->right;
500 min_node->right->left = node;
501 min_node->right = node;
502
503 if (is_min)
504 min_node = node;
505 }
506 }
507
508 // The heap takes node, made with new by the caller. If the comparison
509 // throws, add_to_root_list() has not linked node yet, and the guard
510 // frees it. The guard is not a unique_ptr: its release() would say
511 // that the caller takes the node, and the node is the heap's
513 {
514 struct Guard
515 {
516 Node *node;
517 ~Guard() { delete node; }
518 } guard{node};
519
520 add_to_root_list(node);
521 guard.node = nullptr; // the heap took node
522 ++num_nodes;
523 return node;
524 }
525
526 public:
528 using value_type = T;
529
531 using key_compare = Compare;
532
534 using handle_type = Node *;
535
543 explicit Fibonacci_Heap(Compare compare = Compare())
544 noexcept(std::is_nothrow_copy_constructible_v<Compare>)
545 : cmp(compare)
546 {
547 // empty: extract_min() and delete_node() reserve the room of
548 // consolidate() before they change the heap
549 }
550
560 template <typename... Args>
561 explicit Fibonacci_Heap(std::in_place_t, Args&&... args)
562 noexcept(std::is_nothrow_constructible_v<Compare, Args&&...>)
563 : cmp(std::forward<Args>(args)...)
564 {
565 // empty, as the other constructor
566 }
567
574 {
575 clear();
576 }
577
580
583
593 noexcept(std::is_nothrow_move_constructible_v<Compare>)
594 : min_node(other.min_node),
595 num_nodes(other.num_nodes),
596 cmp(std::move(other.cmp)),
598 {
599 other.min_node = nullptr;
600 other.num_nodes = 0;
601 }
602
615 noexcept(std::is_nothrow_move_assignable_v<Compare> and
616 std::is_nothrow_destructible_v<T>)
617 {
618 if (this != &other)
619 {
620 clear();
621 // The comparison before the nodes: if its move throws, other
622 // still owns them, and this heap none
623 cmp = std::move(other.cmp);
624 consolidate_array_ = std::move(other.consolidate_array_);
625 min_node = other.min_node;
626 num_nodes = other.num_nodes;
627 other.min_node = nullptr;
628 other.num_nodes = 0;
629 }
630 return *this;
631 }
632
643 void swap(Fibonacci_Heap & other)
644 noexcept(std::is_nothrow_swappable_v<Compare>)
645 {
646 using std::swap;
647 swap(cmp, other.cmp); // before the nodes, which then cannot fail
648 std::swap(min_node, other.min_node);
649 std::swap(num_nodes, other.num_nodes);
650 std::swap(consolidate_array_, other.consolidate_array_);
651 }
652
667 [[nodiscard]] Node * insert(const T & val)
668 {
669 return insert_new_node(new Node(val));
670 }
671
684 [[nodiscard]]Node * insert(T && val)
685 {
686 return insert_new_node(new Node(std::move(val)));
687 }
688
703 template <typename... Args>
704 [[nodiscard]] Node * emplace(Args&&... args)
705 {
706 return insert_new_node(new Node(std::forward<Args>(args)...));
707 }
708
717 [[nodiscard]] const T & get_min() const
718 {
719 ah_underflow_error_if(is_empty()) << "Fibonacci_Heap::get_min: heap is empty";
720 return min_node->data;
721 }
722
732 [[nodiscard]] Node * get_min_node() const noexcept
733 {
734 return min_node;
735 }
736
752 {
753 ah_underflow_error_if(is_empty()) << "Fibonacci_Heap::extract_min: heap is empty";
754
755 // A heap that was moved from has no room for consolidate(); it is
756 // made before the heap changes, in case the allocation fails
758
759 Node *z = min_node;
760 take_root_out(z);
761 if (min_node != nullptr)
762 try
763 {
764 consolidate();
765 }
766 catch (...)
767 {
768 put_root_back(z, z);
769 throw;
770 }
771
772 // z is out of the heap: it is freed and counted out from here on
773 std::unique_ptr<Node> node(z);
774 --num_nodes;
775
776 return std::move(z->data);
777 }
778
798 void decrease_key(Node *x, const T & k)
799 {
800 ah_invalid_argument_if(x == nullptr)
801 << "Fibonacci_Heap::decrease_key: null node pointer";
803 << "Fibonacci_Heap::decrease_key: new key is greater than current key";
804
805 // The comparisons take the new key, and come before the heap changes;
806 // their results go to bool as a condition converts them
807 Node *y = x->parent;
808 const bool is_cut = y != nullptr and cmp(k, y->data);
809 const bool is_min = static_cast<bool>(cmp(k, min_node->data));
810
811 x->data = k;
812 if (is_cut)
813 {
814 cut(x, y);
816 }
817
818 if (is_min)
819 min_node = x;
820 }
821
833 void decrease_key(Node *x, T && k)
834 {
835 ah_invalid_argument_if(x == nullptr)
836 << "Fibonacci_Heap::decrease_key: null node pointer";
838 << "Fibonacci_Heap::decrease_key: new key is greater than current key";
839
840 // The comparisons take the new key, and come before the heap changes;
841 // their results go to bool as a condition converts them
842 Node *y = x->parent;
843 const bool is_cut = y != nullptr and cmp(k, y->data);
844 const bool is_min = static_cast<bool>(cmp(k, min_node->data));
845
846 x->data = std::move(k);
847 if (is_cut)
848 {
849 cut(x, y);
851 }
852
853 if (is_min)
854 min_node = x;
855 }
856
885 [[nodiscard]] Node * update_key(Node *x, const T & k)
886 {
887 ah_invalid_argument_if(x == nullptr)
888 << "Fibonacci_Heap::update_key: null node pointer";
889
890 if (cmp(k, x->data))
891 {
892 // New key is smaller, use decrease_key
893 decrease_key(x, k);
894 return x;
895 }
896 if (not cmp(x->data, k))
897 return x; // Keys are equal, do nothing
898
899 // New key is larger: x leaves the heap as in delete_node() and, once
900 // the rest is in order, goes back as a root with the new key, which
901 // is copied first, while a copy that throws changes nothing
902 T key(k);
904
905 Node *old_min = min_node;
906 if (x->parent != nullptr)
907 {
908 Node *parent = x->parent;
909 cut(x, parent);
910 cascading_cut(parent);
911 }
912 take_root_out(x);
913
914 bool is_min = true; // if x is the only node
915 try
916 {
917 if (min_node != nullptr)
918 {
919 consolidate();
920 is_min = static_cast<bool>(cmp(k, min_node->data));
921 }
922 if constexpr (std::is_move_assignable_v<T>)
923 x->data = std::move(key);
924 else
925 x->data = std::as_const(key); // its move assignment is deleted
926 }
927 catch (...)
928 {
929 put_root_back(x, old_min);
930 throw;
931 }
932
933 Node *min = is_min ? x : min_node;
934 put_root_back(x, min);
935 return x;
936 }
937
956 {
957 ah_invalid_argument_if(x == nullptr)
958 << "Fibonacci_Heap::delete_node: null node pointer";
959
960 // As in extract_min(), before the heap changes
962
963 Node *old_min = min_node;
964
965 // If x is not a root, cut it and perform cascading cuts
966 if (x->parent != nullptr)
967 {
968 Node *parent = x->parent; // Save parent BEFORE cut
969 cut(x, parent);
970 cascading_cut(parent); // Use saved parent
971 }
972
973 // x leaves the root list as the minimum does in extract_min(), and
974 // the rest is put in order, which finds the true minimum
975 take_root_out(x);
976 if (min_node != nullptr)
977 try
978 {
979 consolidate();
980 }
981 catch (...)
982 {
983 put_root_back(x, old_min);
984 throw;
985 }
986
987 --num_nodes;
988 delete x;
989 }
990
1005 void merge(Fibonacci_Heap & other)
1006 {
1007 if (&other == this || other.is_empty())
1008 return;
1009
1010 if (is_empty())
1011 {
1012 min_node = other.min_node;
1013 num_nodes = other.num_nodes;
1014 }
1015 else
1016 {
1017 // Compared before the lists are joined, so that if the comparison
1018 // throws each heap keeps its own nodes
1019 const bool other_is_min = cmp(other.min_node->data, min_node->data);
1020
1021 // Concatenate root lists
1022 Node *this_right = min_node->right;
1023 Node *other_left = other.min_node->left;
1024
1025 min_node->right = other.min_node;
1026 other.min_node->left = min_node;
1027 other_left->right = this_right;
1028 this_right->left = other_left;
1029
1030 // Update minimum if necessary
1031 if (other_is_min)
1032 min_node = other.min_node;
1033
1034 num_nodes += other.num_nodes;
1035 }
1036
1037 // Clear the other heap (nodes now belong to us)
1038 other.min_node = nullptr;
1039 other.num_nodes = 0;
1040 }
1041
1050 void merge(Fibonacci_Heap && other)
1051 {
1052 merge(other);
1053 }
1054
1062 [[nodiscard]] bool is_empty() const noexcept
1063 {
1064 return min_node == nullptr;
1065 }
1066
1074 [[nodiscard]] size_t size() const noexcept
1075 {
1076 return num_nodes;
1077 }
1078
1086 void clear() noexcept(std::is_nothrow_destructible_v<T>)
1087 {
1088 if (min_node != nullptr)
1089 {
1091 min_node = nullptr;
1092 num_nodes = 0;
1093 }
1094 }
1095
1096 [[nodiscard]] bool empty() const noexcept
1097 {
1098 return is_empty();
1099 }
1100
1101 void pop()
1102 {
1103 extract_min();
1104 }
1105
1106 [[nodiscard]] const T & top() const
1107 {
1108 return get_min();
1109 }
1110
1116 [[nodiscard]] Compare key_comp() const
1117 {
1118 return cmp;
1119 }
1120
1129 [[nodiscard]] Compare & get_compare() noexcept
1130 {
1131 return cmp;
1132 }
1133 };
1134
1140 template <typename T, class Compare>
1142 noexcept(noexcept(a.swap(b)))
1143 {
1144 a.swap(b);
1145 }
1146
1147} // namespace Aleph
1148
1149# endif // TPL_FIBONACCI_HEAP_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_underflow_error_if(C)
Throws std::underflow_error if condition holds.
Definition ah-errors.H:517
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
Functional programming utilities for Aleph-w containers.
General utility functions and helpers.
Implementation of a Fibonacci Heap priority queue.
static constexpr size_t MAX_DEGREE
Maximum degree tracked during consolidation.
Node * min_node
Pointer to the current minimum root.
const T & get_min() const
Returns the minimum element without removing it.
Fibonacci_Heap(Compare compare=Compare()) noexcept(std::is_nothrow_copy_constructible_v< Compare >)
Default constructor.
Node * insert(T &&val)
Inserts a new element (move).
Node * get_min_node() const noexcept
Returns a pointer to the minimum node.
Fibonacci_Heap & operator=(const Fibonacci_Heap &)=delete
Copy assignment is disabled (use merge or manual copy)
Fibonacci_Heap(Fibonacci_Heap &&other) noexcept(std::is_nothrow_move_constructible_v< Compare >)
Move constructor.
Compare key_comp() const
Returns the comparison functor.
Compare cmp
Comparison functor used to order nodes.
void clear() noexcept(std::is_nothrow_destructible_v< T >)
Removes all elements from the heap.
T value_type
Type alias for the element type.
void add_to_root_list(Node *node)
Adds a node to the root list.
void cascading_cut(Node *y)
Performs cascading cut operation.
Node * insert(const T &val)
Inserts a new element (copy).
void merge(Fibonacci_Heap &other)
Merges another heap into this one.
void decrease_key(Node *x, T &&k)
Decreases the key of a node (move version).
void put_root_back(Node *z, Node *min) noexcept
Undoes take_root_out() after a comparison threw.
static void link(Node *y, Node *x)
Links two trees of the same degree.
bool empty() const noexcept
void cut(Node *x, Node *y)
Cuts a node from its parent and adds it to the root list.
std::vector< Node * > consolidate_array_
Reusable scratch array for Fibonacci_Heap::consolidate().
Fibonacci_Heap & operator=(Fibonacci_Heap &&other) noexcept(std::is_nothrow_move_assignable_v< Compare > and std::is_nothrow_destructible_v< T >)
Move assignment operator.
Node * insert_new_node(Node *node)
void swap(Fibonacci_Heap< T, Compare > &a, Fibonacci_Heap< T, Compare > &b) noexcept(noexcept(a.swap(b)))
Swaps two Fibonacci heaps.
void swap(Fibonacci_Heap &other) noexcept(std::is_nothrow_swappable_v< Compare >)
Swaps contents with another heap.
void consolidate()
Consolidates the root list after extract_min.
Node * emplace(Args &&... args)
Constructs and inserts an element in-place.
size_t size() const noexcept
Returns the number of elements in the heap.
Fibonacci_Heap(std::in_place_t, Args &&... args) noexcept(std::is_nothrow_constructible_v< Compare, Args &&... >)
Constructor with in-place comparator construction.
T extract_min()
Extracts and returns the minimum element.
Compare & get_compare() noexcept
Returns the comparison functor that orders the heap.
size_t num_nodes
Number of elements stored in the heap.
void merge(Fibonacci_Heap &&other)
Merges another heap into this one (rvalue version).
void delete_node(Node *x)
Deletes a specific node from the heap.
Node * update_key(Node *x, const T &k)
Updates the key of a node (increase or decrease).
Compare key_compare
Type alias for the comparison functor.
void decrease_key(Node *x, const T &k)
Decreases the key of a node.
void take_root_out(Node *z) noexcept
Takes a root out of the root list, after putting its children in it as roots.
void delete_all_nodes(Node *node)
Deletes all the nodes of the trees in a circular list.
bool is_empty() const noexcept
Checks if the heap is empty.
Fibonacci_Heap(const Fibonacci_Heap &)=delete
Copy constructor is disabled (use merge or manual copy)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
Represents a node in the Fibonacci Heap.
T data
The data stored in this node.
Node * parent
Parent node (nullptr if root)
bool mark
Has this node lost a child since becoming non-root?
size_t degree
Number of children.
Node * left
Left sibling in circular list.
Node(T &&d) noexcept(std::is_nothrow_move_constructible_v< T >)
Construct a node moving d into the internal storage.
Node(Arg &&arg, Args &&... args)
Perfect-forwarding constructor for in-place construction.
Node(const T &d)
Construct a node copying d into the internal storage.
Node * child
Pointer to one child (head of child list)
Node * right
Right sibling in circular list.
static int * k