Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
fibonacci_heap_test.cc
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
33
38# include <gtest/gtest.h>
39# include <numeric>
40# include <tpl_fibonacci_heap.H>
41# include <vector>
42# include <algorithm>
43# include <random>
44# include <string>
45# include <set>
46# include <chrono>
47# include <functional>
48# include <map>
49# include <memory>
50# include <ostream>
51# include <sstream>
52# include <stdexcept>
53# include <type_traits>
54# include <utility>
55# if defined(__unix__) || defined(__APPLE__)
56# include <pthread.h>
57# endif
58
59using namespace Aleph;
60
61// =============================================================================
62// Test Fixtures
63// =============================================================================
64
65class FibonacciHeapTest : public ::testing::Test
66{
67protected:
69
70 void SetUp() override
71 {
72 // Fresh heap for each test
73 }
74};
75
76class FibonacciHeapWithDataTest : public ::testing::Test
77{
78protected:
80 std::vector<Fibonacci_Heap<int>::Node *> nodes;
81
82 void SetUp() override
83 {
84 // Insert some test data
85 for (int i = 10; i >= 1; --i)
86 nodes.push_back(heap.insert(i * 10)); // 100, 90, 80, ..., 10
87 }
88};
89
90// =============================================================================
91// Basic Construction Tests
92// =============================================================================
93
94namespace
95{
96 // A comparison whose copy, move and swap may throw
97 struct Throwing_Copy_Less
98 {
99 Throwing_Copy_Less() noexcept = default;
100 Throwing_Copy_Less(const Throwing_Copy_Less &) noexcept(false) {}
101 Throwing_Copy_Less(Throwing_Copy_Less &&) noexcept(false) {}
102 Throwing_Copy_Less & operator = (const Throwing_Copy_Less &) noexcept(false)
103 {
104 return *this;
105 }
106 Throwing_Copy_Less & operator = (Throwing_Copy_Less &&) noexcept(false)
107 {
108 return *this;
109 }
110
111 bool operator()(const int a, const int b) const noexcept { return a < b; }
112 };
113
114 using Fragile_Compare_Heap = Fibonacci_Heap<int, Throwing_Copy_Less>;
115} // namespace
116
117// The constructors, the moves and swap were noexcept whatever the
118// comparison, which they copy, move or swap
119static_assert(std::is_nothrow_default_constructible_v<Fibonacci_Heap<int>>);
120static_assert(std::is_nothrow_move_constructible_v<Fibonacci_Heap<int>>);
121static_assert(std::is_nothrow_move_assignable_v<Fibonacci_Heap<int>>);
122static_assert(std::is_nothrow_swappable_v<Fibonacci_Heap<int>>);
123static_assert(not std::is_nothrow_default_constructible_v<Fragile_Compare_Heap>);
124static_assert(not noexcept(Fragile_Compare_Heap(std::in_place,
125 std::declval<const Throwing_Copy_Less &>())));
126static_assert(noexcept(Fragile_Compare_Heap(std::in_place)));
127static_assert(not std::is_nothrow_move_constructible_v<Fragile_Compare_Heap>);
128static_assert(not std::is_nothrow_move_assignable_v<Fragile_Compare_Heap>);
129static_assert(not std::is_nothrow_swappable_v<Fragile_Compare_Heap>);
130
131TEST(FibonacciHeapConstruction, DefaultConstructor)
132{
134 EXPECT_TRUE(h.is_empty());
135 EXPECT_EQ(h.size(), 0u);
136 EXPECT_EQ(h.get_min_node(), nullptr);
137}
138
139TEST(FibonacciHeapConstruction, ConstructorWithComparator)
140{
142 max_heap.insert(5);
143 max_heap.insert(10);
144 max_heap.insert(3);
145 EXPECT_EQ(max_heap.get_min(), 10); // Max heap, so "min" is actually max
146}
147
148TEST(FibonacciHeapConstruction, MoveConstructor)
149{
151 h1.insert(5);
152 h1.insert(3);
153 h1.insert(7);
154
155 Fibonacci_Heap<int> h2(std::move(h1));
156
157 EXPECT_TRUE(h1.is_empty());
158 EXPECT_EQ(h1.size(), 0u);
159
160 EXPECT_FALSE(h2.is_empty());
161 EXPECT_EQ(h2.size(), 3u);
162 EXPECT_EQ(h2.get_min(), 3);
163}
164
165TEST(FibonacciHeapConstruction, MoveAssignment)
166{
168 h1.insert(5);
169 h1.insert(3);
170
172 h2.insert(100);
173
174 h2 = std::move(h1);
175
176 EXPECT_TRUE(h1.is_empty());
177 EXPECT_EQ(h2.size(), 2u);
178 EXPECT_EQ(h2.get_min(), 3);
179}
180
181TEST(FibonacciHeapConstruction, MoveAssignmentRoundtrip)
182{
184 h.insert(5);
185 h.insert(3);
186
187 const auto original_size = h.size();
188 Fibonacci_Heap<int> tmp(std::move(h));
189 h = std::move(tmp);
190
191 EXPECT_EQ(h.size(), original_size);
192 EXPECT_EQ(h.get_min(), 3);
193}
194
195namespace
196{
197 // A comparison whose move assignment throws while armed
198 struct Armed_Move_Less
199 {
200 static inline bool armed = false;
201
202 Armed_Move_Less() noexcept = default;
203 Armed_Move_Less(const Armed_Move_Less &) noexcept = default;
204 Armed_Move_Less & operator = (const Armed_Move_Less &) noexcept = default;
205 Armed_Move_Less & operator = (Armed_Move_Less &&) noexcept(false)
206 {
207 if (armed)
208 throw std::runtime_error("Armed_Move_Less");
209 return *this;
210 }
211
212 bool operator()(const int a, const int b) const noexcept { return a < b; }
213 };
214
215 // A comparison, ascending or descending by its order, whose moves throw
216 // and whose own swap does not
217 struct Own_Swap_Order
218 {
219 bool descending = false;
220
221 explicit Own_Swap_Order(const bool d = false) noexcept : descending(d) {}
222 Own_Swap_Order(const Own_Swap_Order &) noexcept = default;
223 Own_Swap_Order(Own_Swap_Order &&) noexcept(false)
224 {
225 throw std::runtime_error("Own_Swap_Order");
226 }
227 Own_Swap_Order & operator = (const Own_Swap_Order &) noexcept = default;
228 Own_Swap_Order & operator = (Own_Swap_Order &&) noexcept(false)
229 {
230 throw std::runtime_error("Own_Swap_Order");
231 }
232
233 friend void swap(Own_Swap_Order & a, Own_Swap_Order & b) noexcept
234 {
235 std::swap(a.descending, b.descending);
236 }
237
238 bool operator()(const int a, const int b) const noexcept
239 {
240 return descending ? b < a : a < b;
241 }
242 };
243} // namespace
244
245// The move assignment took the nodes of the other heap before it moved the
246// comparison: when the move threw, both heaps owned the nodes, and each
247// freed them
248TEST(FibonacciHeapConstruction, MoveAssignmentWhoseComparisonThrows)
249{
251 to.insert(7);
252 for (int i = 0; i < 5; ++i)
253 from.insert(i);
254
255 Armed_Move_Less::armed = true;
256 EXPECT_THROW(to = std::move(from), std::runtime_error);
257 Armed_Move_Less::armed = false;
258
259 EXPECT_TRUE(to.is_empty());
260 ASSERT_EQ(from.size(), 5u);
261 for (int i = 0; i < 5; ++i)
262 EXPECT_EQ(from.extract_min(), i);
263}
264
265// swap() said noexcept for the swap of the comparisons that ADL finds, but
266// called std::swap, which moves: with the swap of Own_Swap_Order, which
267// does not throw, it ended the program
268static_assert(std::is_nothrow_swappable_v<Fibonacci_Heap<int, Own_Swap_Order>>);
269
270TEST(FibonacciHeapConstruction, SwapUsesTheSwapOfTheComparison)
271{
272 Fibonacci_Heap<int, Own_Swap_Order> up(std::in_place, false);
273 Fibonacci_Heap<int, Own_Swap_Order> down(std::in_place, true);
274 for (int i = 0; i < 4; ++i)
275 {
276 up.insert(i);
277 down.insert(10 + i);
278 }
279
280 EXPECT_NO_THROW(up.swap(down));
281 EXPECT_TRUE(up.get_compare().descending);
282 EXPECT_FALSE(down.get_compare().descending);
283 EXPECT_EQ(up.extract_min(), 13);
284 EXPECT_EQ(down.extract_min(), 0);
285
286 EXPECT_NO_THROW(swap(up, down));
287 EXPECT_EQ(up.extract_min(), 1);
288 EXPECT_EQ(down.extract_min(), 12);
289}
290
291// =============================================================================
292// Insert Tests
293// =============================================================================
294
295TEST_F(FibonacciHeapTest, InsertSingleElement)
296{
297 auto node = heap.insert(42);
298
299 EXPECT_FALSE(heap.is_empty());
300 EXPECT_EQ(heap.size(), 1u);
301 EXPECT_EQ(heap.get_min(), 42);
302 EXPECT_EQ(node->data, 42);
303}
304
305TEST_F(FibonacciHeapTest, InsertMultipleElements)
306{
307 heap.insert(10);
308 heap.insert(5);
309 heap.insert(15);
310 heap.insert(3);
311 heap.insert(8);
312
313 EXPECT_EQ(heap.size(), 5u);
314 EXPECT_EQ(heap.get_min(), 3);
315}
316
317TEST_F(FibonacciHeapTest, InsertDescendingOrder)
318{
319 for (int i = 100; i >= 1; --i)
320 heap.insert(i);
321
322 EXPECT_EQ(heap.size(), 100u);
323 EXPECT_EQ(heap.get_min(), 1);
324}
325
326TEST_F(FibonacciHeapTest, InsertAscendingOrder)
327{
328 for (int i = 1; i <= 100; ++i)
329 heap.insert(i);
330
331 EXPECT_EQ(heap.size(), 100u);
332 EXPECT_EQ(heap.get_min(), 1);
333}
334
335TEST_F(FibonacciHeapTest, InsertDuplicates)
336{
337 for (int i = 0; i < 10; ++i)
338 heap.insert(42);
339
340 EXPECT_EQ(heap.size(), 10u);
341 EXPECT_EQ(heap.get_min(), 42);
342
343 // All extractions should return 42
344 for (int i = 0; i < 10; ++i)
345 EXPECT_EQ(heap.extract_min(), 42);
346
347 EXPECT_TRUE(heap.is_empty());
348}
349
350TEST_F(FibonacciHeapTest, InsertWithMoveSemantics)
351{
352 std::string s = "hello world";
353 Fibonacci_Heap<std::string> string_heap;
354
355 auto node = string_heap.insert(std::move(s));
356
357 EXPECT_EQ(node->data, "hello world");
358 EXPECT_TRUE(s.empty() || s != "hello world"); // s should be moved-from
359}
360
361TEST_F(FibonacciHeapTest, EmplaceConstruction)
362{
364
365 auto node = pair_heap.emplace(42, "answer");
366
367 EXPECT_EQ(node->data.first, 42);
368 EXPECT_EQ(node->data.second, "answer");
369}
370
371// =============================================================================
372// Get Min Tests
373// =============================================================================
374
375TEST_F(FibonacciHeapTest, GetMinOnEmptyHeapThrows)
376{
377 EXPECT_THROW(heap.get_min(), std::underflow_error);
378}
379
380TEST_F(FibonacciHeapTest, GetMinNodeOnEmptyHeap)
381{
382 EXPECT_EQ(heap.get_min_node(), nullptr);
383}
384
385TEST_F(FibonacciHeapTest, GetMinAfterInserts)
386{
387 heap.insert(50);
388 EXPECT_EQ(heap.get_min(), 50);
389
390 heap.insert(30);
391 EXPECT_EQ(heap.get_min(), 30);
392
393 heap.insert(40);
394 EXPECT_EQ(heap.get_min(), 30);
395
396 heap.insert(10);
397 EXPECT_EQ(heap.get_min(), 10);
398
399 heap.insert(20);
400 EXPECT_EQ(heap.get_min(), 10);
401}
402
403// =============================================================================
404// Extract Min Tests
405// =============================================================================
406
407TEST_F(FibonacciHeapTest, ExtractMinOnEmptyHeapThrows)
408{
409 EXPECT_THROW(heap.extract_min(), std::underflow_error);
410}
411
412TEST_F(FibonacciHeapTest, ExtractMinSingleElement)
413{
414 heap.insert(42);
415 int val = heap.extract_min();
416
417 EXPECT_EQ(val, 42);
418 EXPECT_TRUE(heap.is_empty());
419}
420
421TEST_F(FibonacciHeapTest, ExtractMinMultipleElements)
422{
423 heap.insert(30);
424 heap.insert(10);
425 heap.insert(20);
426
427 EXPECT_EQ(heap.extract_min(), 10);
428 EXPECT_EQ(heap.extract_min(), 20);
429 EXPECT_EQ(heap.extract_min(), 30);
430 EXPECT_TRUE(heap.is_empty());
431}
432
433TEST_F(FibonacciHeapTest, ExtractMinMaintainsSortedOrder)
434{
435 std::vector<int> input = {50, 20, 80, 10, 90, 30, 70, 40, 60, 100};
436 for (int v : input)
437 heap.insert(v);
438
439 std::vector<int> extracted;
440 while (!heap.is_empty())
441 extracted.push_back(heap.extract_min());
442
443 std::vector<int> expected = input;
444 std::sort(expected.begin(), expected.end());
445
446 EXPECT_EQ(extracted, expected);
447}
448
449TEST_F(FibonacciHeapTest, ExtractMinWithDuplicates)
450{
451 std::vector<int> input = {5, 3, 5, 1, 3, 5, 1, 3};
452 for (int v : input)
453 heap.insert(v);
454
455 std::vector<int> extracted;
456 while (!heap.is_empty())
457 extracted.push_back(heap.extract_min());
458
459 std::sort(input.begin(), input.end());
460 EXPECT_EQ(extracted, input);
461}
462
463// =============================================================================
464// Decrease Key Tests
465// =============================================================================
466
467TEST_F(FibonacciHeapWithDataTest, DecreaseKeyToNewMinimum)
468{
469 // nodes[9] has value 10 (the current minimum)
470 // nodes[0] has value 100
471 heap.decrease_key(nodes[0], 5);
472
473 EXPECT_EQ(heap.get_min(), 5);
474 EXPECT_EQ(nodes[0]->data, 5);
475}
476
477TEST_F(FibonacciHeapWithDataTest, DecreaseKeyNotAffectingMinimum)
478{
479 // nodes[1] has value 90
480 heap.decrease_key(nodes[1], 50);
481
482 EXPECT_EQ(heap.get_min(), 10); // Still 10
483 EXPECT_EQ(nodes[1]->data, 50);
484}
485
486TEST_F(FibonacciHeapWithDataTest, DecreaseKeyToSameValue)
487{
488 // Decreasing to same value should work
489 heap.decrease_key(nodes[0], 100);
490 EXPECT_EQ(nodes[0]->data, 100);
491}
492
493TEST_F(FibonacciHeapTest, DecreaseKeyWithInvalidIncreaseThrows)
494{
495 auto node = heap.insert(50);
496 EXPECT_THROW(heap.decrease_key(node, 100), std::domain_error);
497}
498
499TEST_F(FibonacciHeapTest, DecreaseKeyWithNullptrThrows)
500{
501 EXPECT_THROW(heap.decrease_key(nullptr, 10), std::invalid_argument);
502}
503
504TEST_F(FibonacciHeapTest, DecreaseKeyTriggersCut)
505{
506 // Build a heap that will have internal structure
507 for (int i = 1; i <= 20; ++i)
508 heap.insert(i);
509
510 // Extract some to build tree structure
511 for (int i = 0; i < 5; ++i)
512 heap.extract_min();
513
514 // Now decrease a key that should trigger cuts
515 auto node = heap.insert(100);
516 heap.decrease_key(node, 1); // Should become new minimum
517
518 EXPECT_EQ(heap.get_min(), 1);
519}
520
521TEST_F(FibonacciHeapTest, DecreaseKeyTriggersCascadingCuts)
522{
523 // Insert elements and extract to create tree structure
524 std::vector<Fibonacci_Heap<int>::Node *> nodes;
525 for (int i = 1; i <= 100; ++i)
526 nodes.push_back(heap.insert(i * 10));
527
528 // Extract min multiple times to consolidate
529 for (int i = 0; i < 20; ++i)
530 heap.extract_min();
531
532 // Find remaining nodes and decrease their keys
533 // This should trigger cascading cuts
534 for (size_t i = 50; i < 60 && i < nodes.size(); ++i)
535 {
536 if (nodes[i]->data > 5)
537 heap.decrease_key(nodes[i], static_cast<int>(i));
538 }
539
540 // Verify heap property is maintained
541 std::vector<int> extracted;
542 while (!heap.is_empty())
543 extracted.push_back(heap.extract_min());
544
545 for (size_t i = 1; i < extracted.size(); ++i)
546 EXPECT_LE(extracted[i - 1], extracted[i]);
547}
548
549TEST_F(FibonacciHeapTest, DecreaseKeyMoveSemantics)
550{
551 Fibonacci_Heap<std::string> string_heap;
552 auto node = string_heap.insert("zzzzz");
553
554 std::string new_val = "aaaaa";
555 string_heap.decrease_key(node, std::move(new_val));
556
557 EXPECT_EQ(node->data, "aaaaa");
558}
559
560// =============================================================================
561// Update Key Tests
562// =============================================================================
563
564TEST_F(FibonacciHeapTest, UpdateKeyDecrease)
565{
566 auto node = heap.insert(50);
567 auto result = heap.update_key(node, 30);
568
569 EXPECT_EQ(result, node);
570 EXPECT_EQ(node->data, 30);
571}
572
573TEST_F(FibonacciHeapTest, UpdateKeyIncrease)
574{
575 heap.insert(30);
576 auto node = heap.insert(50);
577 heap.insert(70);
578
579 auto result = heap.update_key(node, 80);
580
581 // The result should contain the new value and heap should be consistent
582 // Note: The returned pointer may or may not be the same as node due to
583 // memory allocator reuse, so we don't check pointer equality
584 EXPECT_EQ(result->data, 80);
585 EXPECT_EQ(heap.size(), 3u);
586
587 // Verify heap order is maintained: 30, 70, 80
588 EXPECT_EQ(heap.extract_min(), 30);
589 EXPECT_EQ(heap.extract_min(), 70);
590 EXPECT_EQ(heap.extract_min(), 80);
591}
592
593TEST_F(FibonacciHeapTest, UpdateKeySameValue)
594{
595 auto node = heap.insert(50);
596 auto result = heap.update_key(node, 50);
597
598 EXPECT_EQ(result, node);
599 EXPECT_EQ(node->data, 50);
600}
601
602TEST_F(FibonacciHeapTest, UpdateKeyNullptrThrows)
603{
604 EXPECT_THROW(heap.update_key(nullptr, 10), std::invalid_argument);
605}
606
607// =============================================================================
608// Delete Node Tests
609// =============================================================================
610
611TEST_F(FibonacciHeapTest, DeleteNodeSingleElement)
612{
613 auto node = heap.insert(42);
614 heap.delete_node(node);
615
616 EXPECT_TRUE(heap.is_empty());
617}
618
619TEST_F(FibonacciHeapTest, DeleteNodeMinimum)
620{
621 heap.insert(30);
622 auto min_node = heap.insert(10);
623 heap.insert(20);
624
625 heap.delete_node(min_node);
626
627 EXPECT_EQ(heap.size(), 2u);
628 EXPECT_EQ(heap.get_min(), 20);
629}
630
631TEST_F(FibonacciHeapTest, DeleteNodeNonMinimum)
632{
633 heap.insert(10);
634 auto middle = heap.insert(20);
635 heap.insert(30);
636
637 heap.delete_node(middle);
638
639 EXPECT_EQ(heap.size(), 2u);
640 EXPECT_EQ(heap.get_min(), 10);
641 EXPECT_EQ(heap.extract_min(), 10);
642 EXPECT_EQ(heap.extract_min(), 30);
643}
644
645TEST_F(FibonacciHeapTest, DeleteNodeNullptrThrows)
646{
647 EXPECT_THROW(heap.delete_node(nullptr), std::invalid_argument);
648}
649
650TEST_F(FibonacciHeapTest, DeleteNodeFromDeepTree)
651{
652 // Create a complex tree structure
653 std::vector<Fibonacci_Heap<int>::Node *> nodes;
654 for (int i = 1; i <= 50; ++i)
655 nodes.push_back(heap.insert(i));
656
657 // Extract to consolidate
658 for (int i = 0; i < 10; ++i)
659 heap.extract_min();
660
661 // Delete some internal nodes
662 heap.delete_node(nodes[30]);
663 heap.delete_node(nodes[40]);
664 heap.delete_node(nodes[25]);
665
666 // Verify remaining elements
667 std::vector<int> extracted;
668 while (!heap.is_empty())
669 extracted.push_back(heap.extract_min());
670
671 // Should have 50 - 10 (extracted) - 3 (deleted) = 37 elements
672 EXPECT_EQ(extracted.size(), 37u);
673
674 // Should be sorted
675 for (size_t i = 1; i < extracted.size(); ++i)
676 EXPECT_LE(extracted[i - 1], extracted[i]);
677}
678
679// Test for bug: deleting a solitary root with children must consolidate
680// to find the true minimum among the children
681TEST_F(FibonacciHeapTest, DeleteSolitaryRootWithChildren)
682{
683 // Insert values: 10 will become root after extract, with children
684 (void)heap.insert(10);
685 (void)heap.insert(5);
686 (void)heap.insert(20);
687 (void)heap.insert(15);
688 (void)heap.insert(3);
689
690 // Extract minimum (3) - this triggers consolidation
691 // After this, the tree structure will have some nodes as children
692 EXPECT_EQ(heap.extract_min(), 3);
693
694 // Now extract 5 - more consolidation
695 EXPECT_EQ(heap.extract_min(), 5);
696
697 // At this point we have 10, 15, 20 remaining
698 // The structure may have 10 as root with children
699
700 // Insert a new minimum so we can control the structure
701 (void)heap.insert(1);
702
703 // Extract 1 to consolidate: 10, 15, 20 remain, possibly with 10 as root
704 EXPECT_EQ(heap.extract_min(), 1);
705
706 // Now delete the current minimum (should be 10)
707 // This tests deleting a node that may be alone with children
708 auto min_node = heap.get_min_node();
709 heap.delete_node(min_node);
710
711 // After deletion, heap should correctly identify the new minimum
712 EXPECT_EQ(heap.size(), 2u);
713
714 // The new minimum should be correctly found (not just any child)
715 int new_min = heap.get_min();
716 EXPECT_TRUE(new_min == 15 || new_min == 20);
717
718 // Verify we can extract both remaining elements in order
719 int first = heap.extract_min();
720 int second = heap.extract_min();
721 EXPECT_LT(first, second);
722 EXPECT_TRUE(heap.is_empty());
723}
724
725// More direct test: manually create scenario with solitary root + children
726TEST_F(FibonacciHeapTest, DeleteSolitaryRootWithChildrenDirect)
727{
728 // Create heap with nodes that will form a single tree
729 heap.insert(100); // Will be root
730 heap.insert(50);
731 heap.insert(200);
732 heap.insert(25);
733 heap.insert(10); // Will be minimum
734
735 // Extract to build tree structure
736 EXPECT_EQ(heap.extract_min(), 10);
737 EXPECT_EQ(heap.extract_min(), 25);
738
739 // Now 50 is minimum, 100 and 200 may be children or siblings
740 // Keep extracting until we have a small tree
741 EXPECT_EQ(heap.extract_min(), 50);
742
743 // Only 100 and 200 remain
744 EXPECT_EQ(heap.size(), 2u);
745
746 // Delete the minimum (100)
747 heap.delete_node(heap.get_min_node());
748
749 // Only 200 should remain
750 EXPECT_EQ(heap.size(), 1u);
751 EXPECT_EQ(heap.get_min(), 200);
752 EXPECT_EQ(heap.extract_min(), 200);
753 EXPECT_TRUE(heap.is_empty());
754}
755
756TEST_F(FibonacciHeapTest, DeleteAllNodesOneByOne)
757{
758 std::vector<Fibonacci_Heap<int>::Node *> nodes;
759 for (int i = 1; i <= 20; ++i)
760 nodes.push_back(heap.insert(i));
761
762 // Delete in random order
763 std::vector<size_t> indices(20);
764 std::iota(indices.begin(), indices.end(), 0);
765 std::random_device rd;
766 std::mt19937 g(rd());
767 std::shuffle(indices.begin(), indices.end(), g);
768
769 for (size_t idx : indices)
770 {
771 heap.delete_node(nodes[idx]);
772 }
773
774 EXPECT_TRUE(heap.is_empty());
775}
776
777// =============================================================================
778// Merge Tests
779// =============================================================================
780
781TEST_F(FibonacciHeapTest, MergeEmptyHeaps)
782{
783 Fibonacci_Heap<int> h1, h2;
784 h1.merge(h2);
785
786 EXPECT_TRUE(h1.is_empty());
787 EXPECT_TRUE(h2.is_empty());
788}
789
790TEST_F(FibonacciHeapTest, MergeIntoEmptyHeap)
791{
792 Fibonacci_Heap<int> h1, h2;
793 h2.insert(5);
794 h2.insert(3);
795
796 h1.merge(h2);
797
798 EXPECT_EQ(h1.size(), 2u);
799 EXPECT_EQ(h1.get_min(), 3);
800 EXPECT_TRUE(h2.is_empty());
801}
802
803TEST_F(FibonacciHeapTest, MergeEmptyIntoNonEmpty)
804{
805 Fibonacci_Heap<int> h1, h2;
806 h1.insert(5);
807 h1.insert(3);
808
809 h1.merge(h2);
810
811 EXPECT_EQ(h1.size(), 2u);
812 EXPECT_EQ(h1.get_min(), 3);
813}
814
815TEST_F(FibonacciHeapTest, MergeTwoNonEmptyHeaps)
816{
817 Fibonacci_Heap<int> h1, h2;
818
819 h1.insert(10);
820 h1.insert(5);
821 h1.insert(15);
822
823 h2.insert(3);
824 h2.insert(8);
825 h2.insert(12);
826
827 h1.merge(h2);
828
829 EXPECT_EQ(h1.size(), 6u);
830 EXPECT_EQ(h1.get_min(), 3);
831 EXPECT_TRUE(h2.is_empty());
832
833 // Verify all elements
834 std::vector<int> extracted;
835 while (!h1.is_empty())
836 extracted.push_back(h1.extract_min());
837
838 std::vector<int> expected = {3, 5, 8, 10, 12, 15};
839 EXPECT_EQ(extracted, expected);
840}
841
842TEST_F(FibonacciHeapTest, MergeWithRvalue)
843{
845 h1.insert(10);
846
848 h2.insert(5);
849
850 h1.merge(std::move(h2));
851
852 EXPECT_EQ(h1.size(), 2u);
853 EXPECT_EQ(h1.get_min(), 5);
854}
855
856TEST_F(FibonacciHeapTest, MergeLargeHeaps)
857{
858 Fibonacci_Heap<int> h1, h2;
859
860 for (int i = 0; i < 1000; i += 2)
861 h1.insert(i);
862
863 for (int i = 1; i < 1000; i += 2)
864 h2.insert(i);
865
866 h1.merge(h2);
867
868 EXPECT_EQ(h1.size(), 1000u);
869
870 std::vector<int> extracted;
871 while (!h1.is_empty())
872 extracted.push_back(h1.extract_min());
873
874 for (int i = 0; i < 1000; ++i)
875 EXPECT_EQ(extracted[i], i);
876}
877
878// =============================================================================
879// Swap Tests
880// =============================================================================
881
883{
884 Fibonacci_Heap<int> h1, h2;
885
886 h1.insert(10);
887 h1.insert(5);
888
889 h2.insert(100);
890 h2.insert(50);
891 h2.insert(75);
892
893 h1.swap(h2);
894
895 EXPECT_EQ(h1.size(), 3u);
896 EXPECT_EQ(h1.get_min(), 50);
897
898 EXPECT_EQ(h2.size(), 2u);
899 EXPECT_EQ(h2.get_min(), 5);
900}
901
902TEST_F(FibonacciHeapTest, SwapWithEmptyHeap)
903{
904 Fibonacci_Heap<int> h1, h2;
905 h1.insert(10);
906
907 h1.swap(h2);
908
909 EXPECT_TRUE(h1.is_empty());
910 EXPECT_EQ(h2.size(), 1u);
911 EXPECT_EQ(h2.get_min(), 10);
912}
913
914TEST_F(FibonacciHeapTest, SwapFreeFunction)
915{
916 Fibonacci_Heap<int> h1, h2;
917 h1.insert(5);
918 h2.insert(10);
919
920 Aleph::swap(h1, h2);
921
922 EXPECT_EQ(h1.get_min(), 10);
923 EXPECT_EQ(h2.get_min(), 5);
924}
925
926// =============================================================================
927// Clear Tests
928// =============================================================================
929
930TEST_F(FibonacciHeapTest, ClearEmptyHeap)
931{
932 heap.clear();
933 EXPECT_TRUE(heap.is_empty());
934}
935
936TEST_F(FibonacciHeapTest, ClearNonEmptyHeap)
937{
938 for (int i = 0; i < 100; ++i)
939 heap.insert(i);
940
941 heap.clear();
942
943 EXPECT_TRUE(heap.is_empty());
944 EXPECT_EQ(heap.size(), 0u);
945}
946
948{
949 heap.insert(10);
950 heap.insert(5);
951 heap.clear();
952
953 heap.insert(20);
954 heap.insert(15);
955
956 EXPECT_EQ(heap.size(), 2u);
957 EXPECT_EQ(heap.get_min(), 15);
958}
959
960// =============================================================================
961// Type Alias Tests
962// =============================================================================
963
964TEST(FibonacciHeapTypeAliases, ValueType)
965{
966 static_assert(std::is_same_v<Fibonacci_Heap<int>::value_type, int>);
967 static_assert(std::is_same_v<Fibonacci_Heap<std::string>::value_type, std::string>);
968}
969
970TEST(FibonacciHeapTypeAliases, HandleType)
971{
972 static_assert(std::is_same_v<Fibonacci_Heap<int>::handle_type, Fibonacci_Heap<int>::Node *>);
973}
974
975// =============================================================================
976// Max Heap Tests
977// =============================================================================
978
979TEST(FibonacciMaxHeap, BasicOperations)
980{
982
983 max_heap.insert(10);
984 max_heap.insert(30);
985 max_heap.insert(20);
986
987 EXPECT_EQ(max_heap.get_min(), 30); // "min" is actually max
988 EXPECT_EQ(max_heap.extract_min(), 30);
989 EXPECT_EQ(max_heap.extract_min(), 20);
990 EXPECT_EQ(max_heap.extract_min(), 10);
991}
992
993TEST(FibonacciMaxHeap, DecreaseKey)
994{
996
997 auto n1 = max_heap.insert(10);
998 max_heap.insert(30);
999 max_heap.insert(20);
1000
1001 // In max heap, "decrease" means increase the value
1002 max_heap.decrease_key(n1, 50);
1003
1004 EXPECT_EQ(max_heap.get_min(), 50);
1005}
1006
1007// =============================================================================
1008// Custom Type Tests
1009// =============================================================================
1010
1011struct Point
1012{
1013 double x, y;
1014 double distance() const { return x * x + y * y; }
1015
1016 bool operator<(const Point & other) const
1017 {
1018 return distance() < other.distance();
1019 }
1020};
1021
1022TEST(FibonacciHeapCustomType, PointHeap)
1023{
1024 Fibonacci_Heap<Point> point_heap;
1025
1026 point_heap.insert({3.0, 4.0}); // distance = 25
1027 point_heap.insert({1.0, 1.0}); // distance = 2
1028 point_heap.insert({2.0, 2.0}); // distance = 8
1029
1030 EXPECT_DOUBLE_EQ(point_heap.get_min().distance(), 2.0);
1031 EXPECT_DOUBLE_EQ(point_heap.extract_min().distance(), 2.0);
1032 EXPECT_DOUBLE_EQ(point_heap.extract_min().distance(), 8.0);
1033 EXPECT_DOUBLE_EQ(point_heap.extract_min().distance(), 25.0);
1034}
1035
1036TEST(FibonacciHeapCustomType, PairHeap)
1037{
1038 // Heap of (priority, value) pairs
1040
1041 pair_heap.insert({3, "three"});
1042 pair_heap.insert({1, "one"});
1043 pair_heap.insert({2, "two"});
1044
1045 EXPECT_EQ(pair_heap.extract_min().second, "one");
1046 EXPECT_EQ(pair_heap.extract_min().second, "two");
1047 EXPECT_EQ(pair_heap.extract_min().second, "three");
1048}
1049
1050// =============================================================================
1051// Stress Tests
1052// =============================================================================
1053
1054TEST(FibonacciHeapStress, LargeNumberOfInserts)
1055{
1057 constexpr int N = 100000;
1058
1059 for (int i = N; i >= 1; --i)
1060 (void)heap.insert(i);
1061
1062 EXPECT_EQ(heap.size(), static_cast<size_t>(N));
1063 EXPECT_EQ(heap.get_min(), 1);
1064}
1065
1066TEST(FibonacciHeapStress, LargeNumberOfExtractMin)
1067{
1069 constexpr int N = 10000;
1070
1071 for (int i = N; i >= 1; --i)
1072 (void)heap.insert(i);
1073
1074 for (int i = 1; i <= N; ++i)
1075 EXPECT_EQ(heap.extract_min(), i);
1076
1077 EXPECT_TRUE(heap.is_empty());
1078}
1079
1080TEST(FibonacciHeapStress, InterleavedOperations)
1081{
1083 std::multiset<int> reference; // For verification
1084 std::random_device rd;
1085 std::mt19937 gen(42); // Fixed seed for reproducibility
1086 std::uniform_int_distribution<> dis(1, 10000);
1087
1088 constexpr int N = 10000;
1089
1090 for (int i = 0; i < N; ++i)
1091 {
1092 int op = dis(gen) % 3;
1093
1094 if (op == 0 || reference.empty())
1095 {
1096 // Insert
1097 int val = dis(gen);
1098 (void)heap.insert(val);
1099 reference.insert(val);
1100 }
1101 else if (op == 1)
1102 {
1103 // Extract min
1104 int heap_min = heap.extract_min();
1105 int ref_min = *reference.begin();
1106 reference.erase(reference.begin());
1107 EXPECT_EQ(heap_min, ref_min);
1108 }
1109 else
1110 {
1111 // Get min
1112 EXPECT_EQ(heap.get_min(), *reference.begin());
1113 }
1114 }
1115
1116 // Drain remaining
1117 while (!heap.is_empty())
1118 {
1119 int heap_min = heap.extract_min();
1120 int ref_min = *reference.begin();
1121 reference.erase(reference.begin());
1122 EXPECT_EQ(heap_min, ref_min);
1123 }
1124}
1125
1126TEST(FibonacciHeapStress, ManyDecreaseKeys)
1127{
1129 std::vector<Fibonacci_Heap<int>::Node *> nodes;
1130 constexpr int N = 5000;
1131
1132 for (int i = 0; i < N; ++i)
1133 nodes.push_back(heap.insert(i + N)); // Insert N, N+1, ..., 2N-1
1134
1135 // Extract some to create tree structure
1136 for (int i = 0; i < N / 4; ++i)
1137 heap.extract_min();
1138
1139 // Decrease remaining keys
1140 int counter = 0;
1141 for (size_t i = N / 4; i < N; ++i)
1142 {
1143 if (nodes[i]->data > counter)
1144 {
1145 heap.decrease_key(nodes[i], counter);
1146 counter++;
1147 }
1148 }
1149
1150 // Verify heap property
1151 int prev = heap.extract_min();
1152 while (!heap.is_empty())
1153 {
1154 int curr = heap.extract_min();
1155 EXPECT_LE(prev, curr);
1156 prev = curr;
1157 }
1158}
1159
1160TEST(FibonacciHeapStress, ManyDeleteNodes)
1161{
1163 std::vector<Fibonacci_Heap<int>::Node *> nodes;
1164 constexpr int N = 1000;
1165
1166 for (int i = 0; i < N; ++i)
1167 nodes.push_back(heap.insert(i));
1168
1169 // Delete every other node
1170 for (int i = 0; i < N; i += 2)
1171 heap.delete_node(nodes[i]);
1172
1173 EXPECT_EQ(heap.size(), static_cast<size_t>(N / 2));
1174
1175 // Verify remaining elements are odd numbers
1176 std::vector<int> extracted;
1177 while (!heap.is_empty())
1178 extracted.push_back(heap.extract_min());
1179
1180 EXPECT_EQ(extracted.size(), static_cast<size_t>(N / 2));
1181 for (size_t i = 0; i < extracted.size(); ++i)
1182 EXPECT_EQ(extracted[i], static_cast<int>(2 * i + 1));
1183}
1184
1185TEST(FibonacciHeapStress, ManyMerges)
1186{
1187 std::vector<Fibonacci_Heap<int>> heaps(100);
1188
1189 // Insert into each heap
1190 for (int i = 0; i < 100; ++i)
1191 for (int j = 0; j < 100; ++j)
1192 heaps[i].insert(i * 100 + j);
1193
1194 // Merge all into first
1195 for (int i = 1; i < 100; ++i)
1196 heaps[0].merge(heaps[i]);
1197
1198 EXPECT_EQ(heaps[0].size(), 10000u);
1199
1200 // Verify sorted order
1201 int prev = heaps[0].extract_min();
1202 while (!heaps[0].is_empty())
1203 {
1204 int curr = heaps[0].extract_min();
1205 EXPECT_LE(prev, curr);
1206 prev = curr;
1207 }
1208}
1209
1210// =============================================================================
1211// Edge Case Tests
1212// =============================================================================
1213
1214TEST(FibonacciHeapEdgeCases, NegativeNumbers)
1215{
1217
1218 heap.insert(-10);
1219 heap.insert(-5);
1220 heap.insert(-20);
1221 heap.insert(0);
1222 heap.insert(10);
1223
1224 EXPECT_EQ(heap.extract_min(), -20);
1225 EXPECT_EQ(heap.extract_min(), -10);
1226 EXPECT_EQ(heap.extract_min(), -5);
1227 EXPECT_EQ(heap.extract_min(), 0);
1228 EXPECT_EQ(heap.extract_min(), 10);
1229}
1230
1231TEST(FibonacciHeapEdgeCases, IntMinMax)
1232{
1234
1235 heap.insert(std::numeric_limits<int>::max());
1236 heap.insert(0);
1237 heap.insert(std::numeric_limits<int>::min());
1238
1239 EXPECT_EQ(heap.extract_min(), std::numeric_limits<int>::min());
1240 EXPECT_EQ(heap.extract_min(), 0);
1241 EXPECT_EQ(heap.extract_min(), std::numeric_limits<int>::max());
1242}
1243
1244TEST(FibonacciHeapEdgeCases, SingleElementOperations)
1245{
1247 auto node = heap.insert(42);
1248
1249 // Decrease key on single element
1250 heap.decrease_key(node, 10);
1251 EXPECT_EQ(heap.get_min(), 10);
1252
1253 // Delete single element
1254 heap.delete_node(node);
1255 EXPECT_TRUE(heap.is_empty());
1256}
1257
1258TEST(FibonacciHeapEdgeCases, AlternatingMinMax)
1259{
1261
1262 // Insert alternating min and max values
1263 for (int i = 0; i < 100; ++i)
1264 {
1265 if (i % 2 == 0)
1266 heap.insert(std::numeric_limits<int>::min() + i / 2);
1267 else
1268 heap.insert(std::numeric_limits<int>::max() - i / 2);
1269 }
1270
1271 // Should extract in sorted order
1272 int prev = heap.extract_min();
1273 while (!heap.is_empty())
1274 {
1275 int curr = heap.extract_min();
1276 EXPECT_LE(prev, curr);
1277 prev = curr;
1278 }
1279}
1280
1281// =============================================================================
1282// Heap Property Verification Tests
1283// =============================================================================
1284
1285// Helper to verify heap property
1286template <typename T, typename Compare>
1288{
1289 if (heap.is_empty())
1290 return true;
1291
1292 std::vector<T> extracted;
1293 while (!heap.is_empty())
1294 extracted.push_back(heap.extract_min());
1295
1296 // Verify sorted (for min-heap)
1297 for (size_t i = 1; i < extracted.size(); ++i)
1298 {
1299 if (extracted[i] < extracted[i - 1])
1300 return false;
1301 }
1302
1303 return true;
1304}
1305
1306TEST(FibonacciHeapProperty, RandomInsertions)
1307{
1309 std::random_device rd;
1310 std::mt19937 gen(42);
1311 std::uniform_int_distribution<> dis(-10000, 10000);
1312
1313 for (int i = 0; i < 1000; ++i)
1314 heap.insert(dis(gen));
1315
1316 EXPECT_TRUE(verify_heap_property(heap));
1317}
1318
1319TEST(FibonacciHeapProperty, AfterDecreaseKeys)
1320{
1322 std::vector<Fibonacci_Heap<int>::Node *> nodes;
1323
1324 for (int i = 0; i < 100; ++i)
1325 nodes.push_back(heap.insert(i + 100));
1326
1327 // Extract to build structure
1328 for (int i = 0; i < 20; ++i)
1329 heap.extract_min();
1330
1331 // Decrease some keys
1332 for (size_t i = 30; i < 50; ++i)
1333 heap.decrease_key(nodes[i], static_cast<int>(i - 30));
1334
1335 EXPECT_TRUE(verify_heap_property(heap));
1336}
1337
1338TEST(FibonacciHeapProperty, AfterMerge)
1339{
1340 Fibonacci_Heap<int> h1, h2;
1341 std::random_device rd;
1342 std::mt19937 gen(42);
1343 std::uniform_int_distribution<> dis(1, 1000);
1344
1345 for (int i = 0; i < 500; ++i)
1346 {
1347 h1.insert(dis(gen));
1348 h2.insert(dis(gen));
1349 }
1350
1351 h1.merge(h2);
1352
1353 EXPECT_TRUE(verify_heap_property(h1));
1354}
1355
1356// =============================================================================
1357// Memory and Performance Tests
1358// =============================================================================
1359
1360TEST(FibonacciHeapMemory, DestructorFreesMemory)
1361{
1362 // This test mainly checks for memory leaks (run with valgrind/asan)
1363 for (int trial = 0; trial < 10; ++trial)
1364 {
1366 for (int i = 0; i < 1000; ++i)
1367 heap.insert(i);
1368 // Destructor should free all nodes
1369 }
1370}
1371
1372TEST(FibonacciHeapMemory, ClearFreesMemory)
1373{
1374 // Run with valgrind/asan to check for leaks
1376 for (int i = 0; i < 1000; ++i)
1377 heap.insert(i);
1378
1379 heap.clear();
1380
1381 for (int i = 0; i < 1000; ++i)
1382 heap.insert(i + 1000);
1383}
1384
1385namespace
1386{
1387 // Counts the values alive, to check that every node is deleted once
1388 struct Counted
1389 {
1390 static inline long alive = 0;
1391 int key;
1392
1393 Counted(int k) : key(k) { ++alive; }
1394 Counted(const Counted & other) : key(other.key) { ++alive; }
1395 Counted & operator = (const Counted & other) = default;
1396 ~Counted() { --alive; }
1397
1398 bool operator < (const Counted & other) const noexcept
1399 {
1400 return key < other.key;
1401 }
1402 };
1403
1404 using CountedHeap = Fibonacci_Heap<Counted>;
1405
1406 // Fills heap with trees of several children and levels: inserts, extracts
1407 // to link the roots and decreases keys to cut nodes. Returns the nodes
1408 // that are still in the heap.
1409 std::vector<CountedHeap::Node *> fill_with_bushy_trees(CountedHeap & heap)
1410 {
1411 std::mt19937 gen(141);
1412 std::vector<CountedHeap::Node *> nodes;
1413 for (int i = 0; i < 2000; ++i)
1414 nodes.push_back(heap.insert(Counted(int(gen() % 1000000))));
1415
1416 auto extract = [&heap, &nodes]
1417 {
1418 nodes.erase(std::find(nodes.begin(), nodes.end(), heap.get_min_node()));
1419 (void) heap.extract_min();
1420 };
1421 for (int i = 0; i < 100; ++i)
1422 extract();
1423 for (int i = 0; i < 300; ++i)
1424 {
1425 auto *p = nodes[gen() % nodes.size()];
1426 heap.decrease_key(p, Counted(p->data.key - int(gen() % 1000)));
1427 }
1428 for (int i = 0; i < 20; ++i)
1429 extract();
1430
1431 return nodes;
1432 }
1433
1434 // The largest degree and the largest depth of the given nodes
1435 std::pair<size_t, size_t>
1436 degree_and_depth(const std::vector<CountedHeap::Node *> & nodes)
1437 {
1438 size_t degree = 0, depth = 0;
1439 for (auto *p : nodes)
1440 {
1441 degree = std::max(degree, p->degree);
1442 size_t d = 0;
1443 for (auto *q = p; q->parent != nullptr; q = q->parent)
1444 ++d;
1445 depth = std::max(depth, d);
1446 }
1447 return {degree, depth};
1448 }
1449}
1450
1451// clear() and the destructor delete each node once, also in trees of several
1452// children and levels
1453TEST(FibonacciHeapMemory, ClearDeletesEveryNodeOfBushyTrees)
1454{
1455 ASSERT_EQ(Counted::alive, 0);
1456 {
1457 CountedHeap heap;
1458 const auto nodes = fill_with_bushy_trees(heap);
1459 const auto [degree, depth] = degree_and_depth(nodes);
1460 ASSERT_GE(degree, 3u);
1461 ASSERT_GE(depth, 3u);
1462 ASSERT_EQ(Counted::alive, long(heap.size()));
1463
1464 heap.clear();
1465 EXPECT_TRUE(heap.is_empty());
1466 EXPECT_EQ(Counted::alive, 0);
1467
1468 (void) fill_with_bushy_trees(heap);
1469 }
1470 EXPECT_EQ(Counted::alive, 0); // deleted by the destructor
1471}
1472
1473namespace
1474{
1475 // The calls of a comparison, and the one that throws (0 for none)
1476 struct Comparisons
1477 {
1478 long calls = 0;
1479 long fail_at = 0;
1480 };
1481
1482 // Orders Counted by key and counts its calls in count, which the copies
1483 // that the heaps keep share
1484 struct Failing_Counted_Less
1485 {
1486 Comparisons *count = nullptr;
1487
1488 bool operator()(const Counted & a, const Counted & b) const
1489 {
1490 if (count != nullptr and ++count->calls == count->fail_at)
1491 throw std::runtime_error("comparison failed");
1492 return a.key < b.key;
1493 }
1494 };
1495
1497
1498 // Extracts the elements of heap with a comparison that does not throw,
1499 // and returns their keys in the order in which they come out
1500 std::vector<int> drain(Failing_Heap & heap, Comparisons & count)
1501 {
1502 count.fail_at = 0;
1503 std::vector<int> keys;
1504 while (not heap.is_empty())
1505 keys.push_back(heap.extract_min().key);
1506 return keys;
1507 }
1508
1509 // Calls each operation that compares keys, with a comparison that counts
1510 // its calls in count, and returns the keys in the order in which they
1511 // come out. If the comparison throws, each heap must hold as many
1512 // elements as its size() says.
1513 std::vector<int> use_heaps(Comparisons & count)
1514 {
1515 Failing_Heap heap(Failing_Counted_Less{&count});
1516 Failing_Heap other(Failing_Counted_Less{&count});
1517 try
1518 {
1519 std::vector<Failing_Heap::Node *> nodes;
1520 for (int key : {50, 30, 70, 10, 90, 20, 80, 40, 60, 0})
1521 nodes.push_back(heap.insert(Counted(key)));
1522 const Counted copied(35);
1523 nodes.push_back(heap.insert(copied));
1524 nodes.push_back(heap.emplace(45));
1525 (void) heap.extract_min(); // 0, nodes[9]
1526 heap.decrease_key(nodes[4], Counted(5)); // 90
1527 heap.decrease_key(nodes[6], copied); // 80
1528 nodes[2] = heap.update_key(nodes[2], Counted(95)); // 70
1529 heap.delete_node(nodes[7]); // 40
1530 (void) other.insert(Counted(15));
1531 (void) other.insert(Counted(25));
1532 heap.merge(other);
1533
1534 std::vector<int> keys;
1535 while (not heap.is_empty())
1536 keys.push_back(heap.extract_min().key);
1537 return keys;
1538 }
1539 catch (...)
1540 {
1541 const size_t size = heap.size();
1542 const size_t other_size = other.size();
1543 EXPECT_EQ(drain(heap, count).size(), size);
1544 EXPECT_EQ(drain(other, count).size(), other_size);
1545 throw;
1546 }
1547 }
1548}
1549
1550// If the comparison threw, extract_min() and delete_node() lost the node
1551// that they had taken out, which size() still counted, and they could leave
1552// min_node on a node that was not a root or some roots out of the root
1553// list; insert() left in the heap a node that size() did not count, and
1554// merge() left the nodes of both heaps in each one
1555TEST(FibonacciHeapComparison, WhatTheComparisonThrowsLeavesEveryNodeCounted)
1556{
1557 const long alive = Counted::alive;
1558 Comparisons count;
1559 EXPECT_EQ(use_heaps(count),
1560 (std::vector<int>{5, 10, 15, 20, 25, 30, 35, 35, 45, 50, 60, 95}));
1561 EXPECT_EQ(Counted::alive, alive);
1562
1563 for (long k = 1; k <= count.calls; ++k)
1564 {
1565 Comparisons failing;
1566 failing.fail_at = k;
1567 EXPECT_THROW(use_heaps(failing), std::runtime_error) << "call " << k;
1568 EXPECT_EQ(Counted::alive, alive) << "call " << k;
1569 }
1570}
1571
1572// insert(), emplace() and merge() compare the keys before they change the
1573// heaps, so that if the comparison throws the heaps are as they were
1574TEST(FibonacciHeapComparison, InsertAndMergeLeaveTheHeapsAsTheyWere)
1575{
1576 const long alive = Counted::alive;
1577 {
1578 Comparisons count;
1579 Failing_Heap heap(Failing_Counted_Less{&count});
1580 Failing_Heap other(Failing_Counted_Less{&count});
1581 for (int key : {4, 2, 6})
1582 (void) heap.insert(Counted(key));
1583 (void) heap.extract_min(); // 4 and 6 in one tree
1584 for (int key : {5, 1})
1585 (void) other.insert(Counted(key));
1586
1587 const Counted three(3);
1588 count.fail_at = count.calls + 1;
1589 EXPECT_THROW((void) heap.insert(three), std::runtime_error);
1590 count.fail_at = count.calls + 1;
1591 EXPECT_THROW((void) heap.insert(Counted(3)), std::runtime_error);
1592 count.fail_at = count.calls + 1;
1593 EXPECT_THROW((void) heap.emplace(3), std::runtime_error);
1594 count.fail_at = count.calls + 1;
1595 EXPECT_THROW(heap.merge(other), std::runtime_error);
1596
1597 EXPECT_EQ(heap.size(), 2u);
1598 EXPECT_EQ(other.size(), 2u);
1599 EXPECT_EQ(drain(heap, count), (std::vector<int>{4, 6}));
1600 EXPECT_EQ(drain(other, count), (std::vector<int>{1, 5}));
1601 }
1602 EXPECT_EQ(Counted::alive, alive);
1603}
1604
1605// If the comparison throws, extract_min() and delete_node() leave their
1606// node in the heap, which gives all its elements in order afterwards. They
1607// took the node out and destroyed it, and the heap could be left with a
1608// minimum that was not the least element
1609TEST(FibonacciHeapComparison, ExtractAndDeleteLeaveTheirNodeInIfTheComparisonThrows)
1610{
1611 const std::vector<int> keys = {8, 3, 5, 1, 9, 2, 7, 4, 6, 0};
1612 const long alive = Counted::alive;
1613 for (size_t i = 0; i <= keys.size(); ++i) // keys.size(): extract_min()
1614 {
1615 if (i < keys.size() and keys[i] == 0)
1616 continue; // extracted before
1617 for (long k = 1; ; ++k)
1618 {
1619 Comparisons count;
1620 Failing_Heap heap(Failing_Counted_Less{&count});
1621 std::vector<Failing_Heap::Node *> nodes;
1622 for (int key : keys)
1623 nodes.push_back(heap.insert(Counted(key)));
1624 (void) heap.extract_min(); // 0, so that the others are in trees
1625
1626 const std::vector<int> all = {1, 2, 3, 4, 5, 6, 7, 8, 9};
1627 std::vector<int> rest = all;
1628 const int out = i < keys.size() ? keys[i] : 1;
1629 rest.erase(std::find(rest.begin(), rest.end(), out));
1630
1631 count.fail_at = count.calls + k;
1632 bool thrown = false;
1633 try
1634 {
1635 if (i < keys.size())
1636 heap.delete_node(nodes[i]);
1637 else
1638 (void) heap.extract_min();
1639 }
1640 catch (const std::runtime_error &)
1641 {
1642 thrown = true;
1643 }
1644 const std::vector<int> & expected = thrown ? all : rest;
1645 EXPECT_EQ(heap.size(), expected.size()) << "node " << i << ", call " << k;
1646 EXPECT_EQ(drain(heap, count), expected) << "node " << i << ", call " << k; // in order
1647 if (not thrown)
1648 break;
1649 }
1650 }
1651 EXPECT_EQ(Counted::alive, alive);
1652}
1653
1654namespace
1655{
1656 // A key with an identity apart from it; a move takes the identity of its
1657 // source away
1658 struct Tracked
1659 {
1660 static constexpr int gone = -1;
1661
1662 int key = 0;
1663 int id = 0;
1664
1665 Tracked(const int k, const int i) noexcept : key(k), id(i) {}
1666 Tracked(const Tracked &) = default;
1667 Tracked & operator=(const Tracked &) = default;
1668 Tracked(Tracked && o) noexcept : key(o.key), id(std::exchange(o.id, gone)) {}
1669 Tracked & operator=(Tracked && o) noexcept
1670 {
1671 key = o.key;
1672 id = std::exchange(o.id, gone);
1673 return *this;
1674 }
1675 bool operator==(const Tracked &) const = default;
1676 };
1677
1678 void PrintTo(const Tracked & x, std::ostream *os) { *os << x.key << '#' << x.id; }
1679
1680 // Orders Tracked by key and counts its calls in count, which the copies
1681 // that the heaps keep share
1682 struct Failing_Tracked_Less
1683 {
1684 Comparisons *count = nullptr;
1685
1686 bool operator()(const Tracked & a, const Tracked & b) const
1687 {
1688 if (count != nullptr and ++count->calls == count->fail_at)
1689 throw std::runtime_error("comparison failed");
1690 return a.key < b.key;
1691 }
1692 };
1693
1695
1696 // The nodes of a heap, and what is wrong in its trees: the lists of roots
1697 // and of children are circular and doubly linked, each node has its
1698 // parent and as many children as its degree says, no key is less than
1699 // that of its parent, the nodes are as many as size() says, and none has
1700 // a key less than that of the minimum
1701 std::string tree_errors(const Tracked_Heap & heap, std::vector<Tracked_Heap::Node *> & nodes)
1702 {
1703 using Node = Tracked_Heap::Node;
1704 std::ostringstream err;
1705 nodes.clear();
1706 Node *min = heap.get_min_node();
1707 if (min == nullptr)
1708 {
1709 if (heap.size() != 0)
1710 err << "no minimum in a heap of " << heap.size() << "; ";
1711 return err.str();
1712 }
1713 std::vector<std::pair<Node *, Node *>> lists{{min, nullptr}}; // a node of each, and their parent
1714 while (not lists.empty())
1715 {
1716 const auto [first, parent] = lists.back();
1717 lists.pop_back();
1718 size_t count = 0;
1719 Node *p = first;
1720 do
1721 {
1722 if (++count > heap.size())
1723 {
1724 err << "a list does not close; ";
1725 return err.str();
1726 }
1727 if (nodes.size() >= heap.size())
1728 { // a node is reached again: its children would be walked for ever
1729 err << "more nodes than the " << heap.size() << " of the heap; ";
1730 return err.str();
1731 }
1732 nodes.push_back(p);
1733 if (p->parent != parent)
1734 err << "the parent of " << p->data.id << "; ";
1735 if (p->right->left != p or p->left->right != p)
1736 err << "the links of " << p->data.id << "; ";
1737 if (parent != nullptr and p->data.key < parent->data.key)
1738 err << p->data.id << " is less than its parent; ";
1739 if (p->child != nullptr)
1740 lists.emplace_back(p->child, p);
1741 else if (p->degree != 0)
1742 err << "the degree of " << p->data.id << ", without children; ";
1743 p = p->right;
1744 }
1745 while (p != first);
1746 if (parent != nullptr and parent->degree != count)
1747 err << "the degree of " << parent->data.id << "; ";
1748 }
1749 if (nodes.size() != heap.size())
1750 err << nodes.size() << " nodes in a heap of " << heap.size() << "; ";
1751 std::vector<Node *> sorted = nodes;
1752 std::sort(sorted.begin(), sorted.end());
1753 if (std::adjacent_find(sorted.begin(), sorted.end()) != sorted.end())
1754 err << "a node is twice in the heap; ";
1755 for (Node *p : nodes)
1756 if (p->data.key < min->data.key)
1757 err << p->data.id << " is less than the minimum; ";
1758 return err.str();
1759 }
1760
1761 // Fills heap with trees of several children and levels, some of them with
1762 // marked nodes: inserts, extracts to link the roots, decreases keys to
1763 // cut nodes and inserts again, so that there are many roots. Many keys
1764 // are equal
1765 void fill_with_trees(Tracked_Heap & heap, const unsigned seed)
1766 {
1767 std::mt19937 gen(seed);
1768 std::vector<Tracked_Heap::Node *> nodes;
1769 for (int i = 0; i < 70; ++i)
1770 nodes.push_back(heap.insert(Tracked(int(gen() % 40), i + 1)));
1771 auto extract = [&heap, &nodes]
1772 {
1773 nodes.erase(std::find(nodes.begin(), nodes.end(), heap.get_min_node()));
1774 (void) heap.extract_min();
1775 };
1776 for (int i = 0; i < 6; ++i)
1777 extract();
1778 for (int i = 0; i < 14; ++i)
1779 {
1780 auto *p = nodes[gen() % nodes.size()];
1781 heap.decrease_key(p, Tracked(p->data.key - int(gen() % 30), p->data.id));
1782 }
1783 for (int i = 0; i < 3; ++i)
1784 extract();
1785 for (int i = 0; i < 12; ++i) // roots for the next consolidation to link
1786 (void) heap.insert(Tracked(int(gen() % 40), 100 + i));
1787 }
1788}
1789
1790// If the comparison throws, in whichever of its calls, extract_min(),
1791// delete_node(), decrease_key() and update_key() leave in the heap the
1792// elements that it had, each in its node and with its key, and the same
1793// node as the minimum; the trees are well formed, and the key of a
1794// decrease_key() by move is not moved from. extract_min() and delete_node()
1795// destroyed their node, update_key() could destroy it without putting the
1796// new key in, decrease_key() could leave the new key in a node under a
1797// parent of a greater key, and all of them could leave as the minimum a
1798// node that was not the least
1799TEST(FibonacciHeapComparison, EveryFailedCallLeavesTheElementsAndTheMinimum)
1800{
1801 size_t failed = 0, marked = 0, deep = 0;
1802 for (int op = 0; op < 6; ++op)
1803 for (unsigned seed = 1; seed <= 8; ++seed)
1804 for (long k = 1; ; ++k)
1805 {
1806 SCOPED_TRACE(testing::Message() << "op " << op << ", seed " << seed << ", call " << k);
1807 Comparisons count;
1808 Tracked_Heap heap(Failing_Tracked_Less{&count});
1809 fill_with_trees(heap, seed);
1810
1811 std::vector<Tracked_Heap::Node *> before;
1812 ASSERT_EQ(tree_errors(heap, before), "");
1813 std::map<Tracked_Heap::Node *, Tracked> keys;
1814 for (auto *p : before)
1815 {
1816 keys.emplace(p, p->data);
1817 marked += p->mark ? 1 : 0;
1818 deep += p->parent != nullptr and p->parent->parent != nullptr ? 1 : 0;
1819 }
1820 Tracked_Heap::Node *min = heap.get_min_node();
1821
1822 std::mt19937 gen(seed*31 + unsigned(op));
1823 Tracked_Heap::Node *x = before[gen() % before.size()];
1824 const Tracked less_key(x->data.key - 1 - int(gen() % 30), 1000);
1825 const Tracked more_key(x->data.key + 1 + int(gen() % 30), 1000);
1826 Tracked moved = less_key;
1827
1828 count.fail_at = count.calls + k;
1829 bool thrown = false;
1830 try
1831 {
1832 switch (op)
1833 {
1834 case 0: (void) heap.extract_min(); break;
1835 case 1: heap.delete_node(x); break;
1836 case 2: heap.decrease_key(x, less_key); break;
1837 case 3: heap.decrease_key(x, std::move(moved)); break;
1838 case 4: ASSERT_EQ(heap.update_key(x, less_key), x); break;
1839 default: ASSERT_EQ(heap.update_key(x, more_key), x);
1840 }
1841 }
1842 catch (const std::runtime_error &)
1843 {
1844 thrown = true;
1845 }
1846 count.fail_at = 0;
1847
1848 std::vector<Tracked_Heap::Node *> after;
1849 ASSERT_EQ(tree_errors(heap, after), "");
1850 if (thrown)
1851 {
1852 ++failed;
1853 EXPECT_EQ(heap.size(), before.size());
1854 EXPECT_EQ(heap.get_min_node(), min);
1855 std::map<Tracked_Heap::Node *, Tracked> now;
1856 for (auto *p : after)
1857 now.emplace(p, p->data);
1858 EXPECT_EQ(now, keys);
1859 EXPECT_EQ(moved, less_key);
1860 }
1861 else if (op >= 2)
1862 {
1863 EXPECT_EQ(x->data, op == 5 ? more_key : less_key);
1864 }
1865
1866 std::vector<int> out;
1867 while (not heap.is_empty())
1868 out.push_back(heap.extract_min().key);
1869 EXPECT_TRUE(std::is_sorted(out.begin(), out.end()));
1870 EXPECT_EQ(out.size(), before.size() - (not thrown and op < 2 ? 1 : 0));
1871 if (not thrown)
1872 break;
1873 }
1874 EXPECT_GT(failed, 300u);
1875 EXPECT_GT(marked, 0u); // the heaps had marked nodes
1876 EXPECT_GT(deep, 0u); // and nodes at the third level
1877}
1878
1879// When the comparison throws, a consolidation may have left the node that
1880// was the minimum under another one of an equivalent key, and that one
1881// under a third. The minimum is cut from it and is a root again, and the
1882// node that lost it is marked, as one that loses a child by decrease_key()
1883// is: the loss of another child cuts it too. It was left unmarked, so it
1884// could lose two children and stay under its parent
1885TEST(FibonacciHeapComparison, TheNodeThatLosesTheMinimumIsMarked)
1886{
1887 size_t marked = 0, cut = 0;
1888 for (size_t victim = 0; victim < 10; ++victim)
1889 for (long k = 1; ; ++k)
1890 {
1891 SCOPED_TRACE(testing::Message() << "node " << victim + 1 << ", call " << k);
1892 Comparisons count;
1893 Tracked_Heap heap(Failing_Tracked_Less{&count});
1894 std::vector<Tracked_Heap::Node *> handles;
1895 for (int id = 1; id <= 10; ++id)
1896 handles.push_back(heap.insert(Tracked(5, id))); // equivalent keys
1897 Tracked_Heap::Node *min = heap.get_min_node();
1898
1899 count.fail_at = count.calls + k;
1900 bool thrown = false;
1901 try
1902 {
1903 heap.delete_node(handles[victim]);
1904 }
1905 catch (const std::runtime_error &)
1906 {
1907 thrown = true;
1908 }
1909 count.fail_at = 0;
1910 if (not thrown)
1911 break;
1912
1913 std::vector<Tracked_Heap::Node *> nodes;
1914 ASSERT_EQ(tree_errors(heap, nodes), "");
1915 ASSERT_EQ(heap.get_min_node(), min);
1916 // nothing had been cut before, so a marked node is one that lost
1917 // the minimum, and it is not a root
1918 Tracked_Heap::Node *loser = nullptr;
1919 for (auto *p : nodes)
1920 if (p->mark)
1921 {
1922 EXPECT_EQ(loser, nullptr);
1923 EXPECT_NE(p->parent, nullptr);
1924 loser = p;
1925 }
1926 if (loser == nullptr)
1927 continue;
1928 ++marked;
1929 if (loser->child == nullptr)
1930 continue;
1931 // the loss of another child takes it out of its parent
1932 Tracked_Heap::Node *child = loser->child;
1933 heap.decrease_key(child, Tracked(4, child->data.id));
1934 EXPECT_EQ(child->parent, nullptr);
1935 EXPECT_EQ(loser->parent, nullptr);
1936 EXPECT_FALSE(loser->mark);
1937 ASSERT_EQ(tree_errors(heap, nodes), "");
1938 ++cut;
1939 }
1940 EXPECT_GT(marked, 0u);
1941 EXPECT_GT(cut, 0u);
1942}
1943
1944namespace
1945{
1946 // A key whose copies throw when they are told to: its copy constructor
1947 // before it writes anything, and its copy assignment once it has written
1948 struct Brittle
1949 {
1950 static inline bool copy_throws = false;
1951 static inline bool assignment_throws = false;
1952
1953 int key = 0;
1954 int id = 0;
1955
1956 Brittle(const int k, const int i) noexcept : key(k), id(i) {}
1957
1958 Brittle(const Brittle & other) : key(other.key), id(other.id)
1959 {
1960 if (copy_throws)
1961 throw std::runtime_error("copy");
1962 }
1963
1964 Brittle(Brittle &&) noexcept = default;
1965
1966 Brittle & operator=(const Brittle & other)
1967 {
1968 key = other.key;
1969 id = other.id;
1970 if (assignment_throws)
1971 throw std::runtime_error("assignment");
1972 return *this;
1973 }
1974
1975 Brittle & operator=(Brittle &&) noexcept = default;
1976
1977 bool operator==(const Brittle &) const = default;
1978 };
1979
1980 void PrintTo(const Brittle & x, std::ostream *os) { *os << x.key << '#' << x.id; }
1981
1982 struct Brittle_Less
1983 {
1984 bool operator()(const Brittle & a, const Brittle & b) const noexcept { return a.key < b.key; }
1985 };
1986}
1987
1988// update_key() with a greater key assigned the key to the node once the
1989// node was out of its tree. An assignment that threw after writing left a
1990// heap whose minimum was the node of before, whatever its key was by then.
1991// Now the key is copied before the heap changes and moved into the node at
1992// the end: a copy that throws changes nothing
1993TEST(FibonacciHeapComparison, UpdateKeyCopiesTheKeyBeforeItChangesTheHeap)
1994{
1996 auto *one = heap.insert(Brittle(1, 1));
1997 auto *five = heap.insert(Brittle(5, 2));
1998 auto *seven = heap.insert(Brittle(7, 3));
1999 (void) heap.insert(Brittle(0, 4));
2000 EXPECT_EQ(heap.extract_min(), Brittle(0, 4)); // one and five are roots now
2001 ASSERT_EQ(heap.get_min_node(), one);
2002 ASSERT_EQ(five->parent, nullptr);
2003 ASSERT_EQ(seven->parent, five); // which update_key() cuts from its tree
2004 const Brittle nine(9, 5);
2005
2006 Brittle::copy_throws = true;
2007 EXPECT_THROW((void) heap.update_key(one, nine), std::runtime_error);
2008 EXPECT_THROW((void) heap.update_key(five, nine), std::runtime_error);
2009 EXPECT_THROW((void) heap.update_key(seven, nine), std::runtime_error);
2010 Brittle::copy_throws = false;
2011 EXPECT_EQ(heap.size(), 3u);
2012 EXPECT_EQ(heap.get_min_node(), one);
2013 EXPECT_EQ(one->data, Brittle(1, 1));
2014 EXPECT_EQ(five->data, Brittle(5, 2));
2015 EXPECT_EQ(seven->data, Brittle(7, 3));
2016 EXPECT_EQ(seven->parent, five);
2017 EXPECT_EQ(five->degree, 1u);
2018
2019 // the copy assignment, which throws after it writes, is not what puts
2020 // the key in the node
2021 Brittle::assignment_throws = true;
2022 ASSERT_EQ(heap.update_key(one, nine), one);
2023 Brittle::assignment_throws = false;
2024 EXPECT_EQ(one->data, nine);
2025 EXPECT_EQ(heap.size(), 3u);
2026 EXPECT_EQ(heap.get_min_node(), five);
2027 EXPECT_EQ(heap.extract_min(), Brittle(5, 2));
2028 EXPECT_EQ(heap.extract_min(), Brittle(7, 3));
2029 EXPECT_EQ(heap.extract_min(), nine);
2030 EXPECT_TRUE(heap.is_empty());
2031}
2032
2033namespace
2034{
2035 // A key that is copied, and assigned from a const reference only: its
2036 // move assignment is deleted, and so is the one from a reference that is
2037 // not const
2038 struct Copied_Only
2039 {
2040 int key = 0;
2041
2042 explicit Copied_Only(const int k) noexcept : key(k) {}
2043 Copied_Only(const Copied_Only &) = default;
2044 Copied_Only & operator=(const Copied_Only &) = default;
2045 Copied_Only & operator=(Copied_Only &) = delete;
2046 Copied_Only & operator=(Copied_Only &&) = delete;
2047
2048 bool operator<(const Copied_Only & other) const noexcept { return key < other.key; }
2049 };
2050}
2051
2052// update_key() with a greater key deleted the node and inserted a copy of
2053// the key: it took a key whose move assignment is deleted, as
2054// decrease_key() does, which assigns it from a const reference. Moving the
2055// key into the node stopped compiling with such a key, which is copied
2056// into it now, from a const reference too
2057TEST(FibonacciHeapComparison, UpdateKeyTakesAKeyWithNoMoveAssignment)
2058{
2059 static_assert(not std::is_move_assignable_v<Copied_Only>);
2060 static_assert(std::is_copy_assignable_v<Copied_Only>);
2062 const Copied_Only zero(0), one(1), three(3), five(5), seven(7), nine(9);
2063 auto *n1 = heap.insert(one);
2064 auto *n5 = heap.insert(five);
2065 auto *n7 = heap.insert(seven);
2066 (void) heap.insert(zero);
2067 EXPECT_EQ(heap.extract_min().key, 0);
2068 ASSERT_EQ(heap.get_min_node(), n1);
2069 ASSERT_EQ(n7->parent, n5);
2070
2071 ASSERT_EQ(heap.update_key(n7, nine), n7); // a child
2072 EXPECT_EQ(n7->data.key, 9);
2073 EXPECT_EQ(n7->parent, nullptr);
2074 ASSERT_EQ(heap.update_key(n1, seven), n1); // the minimum
2075 EXPECT_EQ(n1->data.key, 7);
2076 EXPECT_EQ(heap.get_min_node(), n5);
2077 ASSERT_EQ(heap.update_key(n7, three), n7); // decreases
2078 EXPECT_EQ(heap.get_min_node(), n7);
2079 EXPECT_EQ(heap.size(), 3u);
2080 EXPECT_EQ(heap.extract_min().key, 3);
2081 EXPECT_EQ(heap.extract_min().key, 5);
2082 EXPECT_EQ(heap.extract_min().key, 7);
2083 EXPECT_TRUE(heap.is_empty());
2084}
2085
2086namespace
2087{
2088 // What a comparison returns: it converts to bool implicitly by a function
2089 // that throws when it is told to, and in a condition by another one
2090 struct Wary_Bool
2091 {
2092 static inline bool armed = false;
2093
2094 bool value;
2095
2096 operator bool() const &
2097 {
2098 if (armed)
2099 throw std::runtime_error("implicit conversion");
2100 return value;
2101 }
2102
2103 explicit operator bool() && noexcept { return value; }
2104 };
2105
2106 struct Wary_Less
2107 {
2108 Wary_Bool operator()(const int a, const int b) const noexcept { return Wary_Bool{a < b}; }
2109 };
2110}
2111
2112// decrease_key() and update_key() compare before they change the heap, and
2113// kept each result in a bool, by its implicit conversion, where they made
2114// that of a condition before. With a result whose implicit conversion
2115// throws, decrease_key() stopped decreasing. They convert the results now
2116// as a condition does
2117TEST(FibonacciHeapComparison, TheResultOfAComparisonIsConvertedAsInACondition)
2118{
2120 auto *five = heap.insert(5);
2121 auto *seven = heap.insert(7);
2122 auto *nine = heap.insert(9);
2123 (void) heap.insert(1);
2124 EXPECT_EQ(heap.extract_min(), 1);
2125 const int six = 6;
2126
2127 Wary_Bool::armed = true;
2128 EXPECT_NO_THROW(heap.decrease_key(nine, 3)); // the key is moved
2129 EXPECT_NO_THROW(heap.decrease_key(seven, six)); // and copied
2130 EXPECT_NO_THROW((void) heap.update_key(five, 8));
2131 Wary_Bool::armed = false;
2132 EXPECT_EQ(heap.size(), 3u);
2133 EXPECT_EQ(heap.get_min_node(), nine);
2134 EXPECT_EQ(heap.extract_min(), 3);
2135 EXPECT_EQ(heap.extract_min(), 6);
2136 EXPECT_EQ(heap.extract_min(), 8);
2137 EXPECT_TRUE(heap.is_empty());
2138}
2139
2140// update_key() with a greater key deleted the node and inserted another one.
2141// Now it keeps the node, so the handle is the same and no node is allocated
2142TEST(FibonacciHeapComparison, UpdateKeyKeepsTheNodeWhenTheKeyIncreases)
2143{
2144 Comparisons count;
2145 Tracked_Heap heap(Failing_Tracked_Less{&count});
2146 fill_with_trees(heap, 5);
2147 std::vector<Tracked_Heap::Node *> nodes;
2148 ASSERT_EQ(tree_errors(heap, nodes), "");
2149 const size_t size = heap.size();
2150 int id = 2000;
2151 for (auto *p : nodes)
2152 {
2153 const Tracked key(p->data.key + 7, ++id);
2154 ASSERT_EQ(heap.update_key(p, key), p);
2155 EXPECT_EQ(p->data, key);
2156 std::vector<Tracked_Heap::Node *> now;
2157 ASSERT_EQ(tree_errors(heap, now), "");
2158 ASSERT_EQ(heap.size(), size);
2159 }
2160 // the minimum alone, in a heap of one node
2161 Tracked_Heap one(Failing_Tracked_Less{&count});
2162 auto *p = one.insert(Tracked(3, 1));
2163 EXPECT_EQ(one.update_key(p, Tracked(9, 2)), p);
2164 EXPECT_EQ(one.get_min(), Tracked(9, 2));
2165 EXPECT_EQ(one.size(), 1u);
2166}
2167
2168// With several roots of the least key, a consolidation links the node that
2169// was the minimum under another of them. If the comparison throws after
2170// that, in delete_node() or in update_key() of another node, that node is
2171// the minimum again, and a root
2172TEST(FibonacciHeapComparison, AMinimumThatWasLinkedIsTheMinimumAgain)
2173{
2174 size_t failed = 0;
2175 for (int op = 0; op < 2; ++op)
2176 for (size_t which = 1; which < 12; ++which) // the consolidation starts after the node that leaves
2177 for (long k = 1; ; ++k)
2178 {
2179 SCOPED_TRACE(testing::Message() << "op " << op << ", node " << which << ", call " << k);
2180 Comparisons count;
2181 Tracked_Heap heap(Failing_Tracked_Less{&count});
2182 std::vector<Tracked_Heap::Node *> nodes;
2183 for (int i = 0; i < 12; ++i) // eight roots with the least key
2184 nodes.push_back(heap.insert(Tracked(i < 8 ? 5 : 5 + i, i + 1)));
2185 Tracked_Heap::Node *min = heap.get_min_node();
2186 Tracked_Heap::Node *x = nodes[which];
2187 ASSERT_NE(x, min);
2188
2189 count.fail_at = count.calls + k;
2190 bool thrown = false;
2191 try
2192 {
2193 if (op == 0)
2194 heap.delete_node(x);
2195 else
2196 (void) heap.update_key(x, Tracked(99, 50));
2197 }
2198 catch (const std::runtime_error &)
2199 {
2200 thrown = true;
2201 }
2202 count.fail_at = 0;
2203
2204 std::vector<Tracked_Heap::Node *> after;
2205 EXPECT_EQ(tree_errors(heap, after), "");
2206 if (not thrown)
2207 break;
2208 ++failed;
2209 EXPECT_EQ(heap.get_min_node(), min);
2210 EXPECT_EQ(min->parent, nullptr);
2211 EXPECT_EQ(heap.size(), 12u);
2212 }
2213 EXPECT_GT(failed, 100u);
2214}
2215
2216// A key that increases and is still the least one leaves its node as the
2217// minimum; if another key is less than it now, the node of that one is
2218TEST(FibonacciHeapComparison, UpdateKeyOfTheMinimumToAGreaterKey)
2219{
2220 Comparisons count;
2221 Tracked_Heap heap(Failing_Tracked_Less{&count});
2222 std::vector<Tracked_Heap::Node *> nodes;
2223 for (int i = 0; i < 9; ++i)
2224 nodes.push_back(heap.insert(Tracked(10*i, i + 1))); // 0, 10, ..., 80
2225 EXPECT_EQ(heap.extract_min().key, 0); // the others, in trees
2226 std::vector<Tracked_Heap::Node *> now;
2227
2228 Tracked_Heap::Node *p = heap.get_min_node();
2229 ASSERT_EQ(p, nodes[1]);
2230 ASSERT_EQ(heap.update_key(p, Tracked(15, 100)), p); // still less than 20
2231 EXPECT_EQ(heap.get_min_node(), p);
2232 EXPECT_EQ(tree_errors(heap, now), "");
2233
2234 EXPECT_EQ(heap.update_key(p, Tracked(25, 101)), p); // 20 is the least now
2235 EXPECT_EQ(heap.get_min_node(), nodes[2]);
2236 EXPECT_EQ(tree_errors(heap, now), "");
2237
2238 std::vector<int> out;
2239 while (not heap.is_empty())
2240 out.push_back(heap.extract_min().key);
2241 EXPECT_EQ(out, (std::vector<int>{20, 25, 30, 40, 50, 60, 70, 80}));
2242}
2243
2244// Performance test (disabled by default due to time)
2245TEST(FibonacciHeapPerformance, DISABLED_TimingComparison)
2246{
2247 constexpr int N = 1000000;
2248
2249 auto start = std::chrono::high_resolution_clock::now();
2250
2252 for (int i = N; i >= 1; --i)
2253 (void)heap.insert(i);
2254
2255 auto after_insert = std::chrono::high_resolution_clock::now();
2256
2257 while (!heap.is_empty())
2258 heap.extract_min();
2259
2260 auto after_extract = std::chrono::high_resolution_clock::now();
2261
2262 auto insert_time = std::chrono::duration_cast<std::chrono::milliseconds>(
2263 after_insert - start).count();
2264 auto extract_time = std::chrono::duration_cast<std::chrono::milliseconds>(
2265 after_extract - after_insert).count();
2266
2267 std::cout << "Insert " << N << " elements: " << insert_time << " ms\n";
2268 std::cout << "Extract " << N << " elements: " << extract_time << " ms\n";
2269}
2270
2271// =============================================================================
2272// Dijkstra-like Usage Pattern Test
2273// =============================================================================
2274
2275TEST(FibonacciHeapUsagePattern, DijkstraSimulation)
2276{
2277 // Simulate Dijkstra's algorithm usage pattern
2278 struct DistNode
2279 {
2280 int vertex;
2281 int distance;
2282
2283 bool operator<(const DistNode & other) const
2284 {
2285 return distance < other.distance;
2286 }
2287 };
2288
2290 std::vector<Fibonacci_Heap<DistNode>::Node *> handles(100, nullptr);
2291
2292 // Initialize all vertices with infinite distance except source
2293 for (int v = 0; v < 100; ++v)
2294 {
2295 int dist = (v == 0) ? 0 : std::numeric_limits<int>::max();
2296 handles[v] = pq.insert({v, dist});
2297 }
2298
2299 // Simulate relaxation
2300 std::random_device rd;
2301 std::mt19937 gen(42);
2302 std::uniform_int_distribution<> dist_gen(1, 100);
2303
2304 while (!pq.is_empty())
2305 {
2306 DistNode u = pq.extract_min();
2307
2308 // Mark as processed BEFORE accessing other handles
2309 // (the extracted node's handle is now invalid)
2310 handles[u.vertex] = nullptr;
2311
2312 // Simulate relaxing neighbors
2313 for (int i = 0; i < 3; ++i)
2314 {
2315 int v = dist_gen(gen) % 100;
2316 // Only access handles that haven't been extracted yet
2317 if (handles[v] != nullptr && handles[v]->data.distance > u.distance + 10)
2318 {
2319 // Decrease key to simulate edge relaxation
2320 pq.decrease_key(handles[v], {v, u.distance + 10});
2321 }
2322 }
2323 }
2324}
2325
2326// =============================================================================
2327// Comparator Tests
2328// =============================================================================
2329
2330TEST(FibonacciHeapComparator, KeyComp)
2331{
2333 auto cmp = heap.key_comp();
2334
2335 EXPECT_TRUE(cmp(1, 2));
2336 EXPECT_FALSE(cmp(2, 1));
2337 EXPECT_FALSE(cmp(1, 1));
2338}
2339
2340TEST(FibonacciHeapComparator, CustomLambdaComparator)
2341{
2342 auto cmp = [](int a, int b) { return a > b; }; // Max heap
2343 Fibonacci_Heap<int, decltype(cmp)> heap(cmp);
2344
2345 (void)heap.insert(10);
2346 (void)heap.insert(30);
2347 (void)heap.insert(20);
2348
2349 EXPECT_EQ(heap.extract_min(), 30);
2350 EXPECT_EQ(heap.extract_min(), 20);
2351 EXPECT_EQ(heap.extract_min(), 10);
2352}
2353
2354// =============================================================================
2355// Additional Edge Case Tests
2356// =============================================================================
2357
2358TEST(FibonacciHeapEdgeCases, DecreaseKeyOnRootNode)
2359{
2361 auto node = heap.insert(50);
2362 heap.insert(60);
2363 heap.insert(70);
2364
2365 // Decrease the minimum (root) node - should just update data
2366 heap.decrease_key(node, 10);
2367
2368 EXPECT_EQ(heap.get_min(), 10);
2369 EXPECT_EQ(heap.extract_min(), 10);
2370 EXPECT_EQ(heap.extract_min(), 60);
2371 EXPECT_EQ(heap.extract_min(), 70);
2372}
2373
2374TEST(FibonacciHeapEdgeCases, DecreaseKeyChildBecomesSmallerThanParent)
2375{
2377
2378 // Insert values that will create parent-child relationships after consolidate
2379 for (int i = 1; i <= 10; ++i)
2380 heap.insert(i * 10);
2381
2382 // Extract to force consolidation
2383 heap.extract_min(); // Remove 10
2384 heap.extract_min(); // Remove 20
2385
2386 // Insert a large value and then decrease it
2387 auto node = heap.insert(1000);
2388 heap.decrease_key(node, 5); // Now smaller than any remaining
2389
2390 EXPECT_EQ(heap.get_min(), 5);
2391
2392 // Verify heap property is maintained
2393 int prev = heap.extract_min();
2394 while (!heap.is_empty())
2395 {
2396 int curr = heap.extract_min();
2397 EXPECT_LE(prev, curr);
2398 prev = curr;
2399 }
2400}
2401
2402TEST(FibonacciHeapEdgeCases, DeleteNodeWithMultipleChildren)
2403{
2405 std::vector<Fibonacci_Heap<int>::Node *> nodes;
2406
2407 // Insert 15 elements to create trees with multiple children
2408 for (int i = 0; i < 15; ++i)
2409 nodes.push_back(heap.insert(i + 1));
2410
2411 // Extract several times to build tree structure with children
2412 for (int i = 0; i < 4; ++i)
2413 heap.extract_min();
2414
2415 // Delete a node that likely has children (after consolidation)
2416 // Node with value 8 should still be in the heap
2417 heap.delete_node(nodes[7]); // Delete node with original value 8
2418
2419 // Verify heap property and correct count
2420 EXPECT_EQ(heap.size(), 10u); // 15 - 4 extracted - 1 deleted
2421
2422 int prev = heap.extract_min();
2423 while (!heap.is_empty())
2424 {
2425 int curr = heap.extract_min();
2426 EXPECT_LE(prev, curr);
2427 prev = curr;
2428 }
2429}
2430
2431TEST(FibonacciHeapEdgeCases, MergeSelfNoOp)
2432{
2434 heap.insert(10);
2435 heap.insert(20);
2436
2437 heap.merge(heap); // Self-merge should be no-op
2438
2439 EXPECT_EQ(heap.size(), 2u);
2440 EXPECT_EQ(heap.get_min(), 10);
2441}
2442
2443TEST(FibonacciHeapEdgeCases, UpdateKeyToSameValueOnChild)
2444{
2446
2447 // Create structure with parent-child relationships
2448 for (int i = 1; i <= 10; ++i)
2449 heap.insert(i * 10);
2450
2451 // Extract to consolidate
2452 heap.extract_min();
2453
2454 // Insert and update to same value
2455 auto node = heap.insert(500);
2456 auto result = heap.update_key(node, 500);
2457
2458 EXPECT_EQ(result, node);
2459 EXPECT_EQ(result->data, 500);
2460}
2461
2462TEST(FibonacciHeapEdgeCases, ConsecutiveDecreaseKeys)
2463{
2465
2466 auto node = heap.insert(100);
2467 heap.insert(200);
2468 heap.insert(300);
2469
2470 // Multiple consecutive decrease keys on same node
2471 heap.decrease_key(node, 90);
2472 EXPECT_EQ(heap.get_min(), 90);
2473
2474 heap.decrease_key(node, 50);
2475 EXPECT_EQ(heap.get_min(), 50);
2476
2477 heap.decrease_key(node, 10);
2478 EXPECT_EQ(heap.get_min(), 10);
2479
2480 // Verify extraction order
2481 EXPECT_EQ(heap.extract_min(), 10);
2482 EXPECT_EQ(heap.extract_min(), 200);
2483 EXPECT_EQ(heap.extract_min(), 300);
2484}
2485
2486TEST(FibonacciHeapEdgeCases, EmplaceWithSingleArg)
2487{
2489
2490 // emplace with single arg should work (goes through insert path)
2491 auto node = heap.emplace(42);
2492
2493 EXPECT_EQ(node->data, 42);
2494 EXPECT_EQ(heap.get_min(), 42);
2495}
2496
2497TEST(FibonacciHeapEdgeCases, LargeDegreeTrees)
2498{
2500
2501 // Insert enough elements to create high-degree trees
2502 // Fibonacci heap can have trees of degree up to log_phi(n)
2503 constexpr int N = 10000;
2504 for (int i = N; i >= 1; --i)
2505 heap.insert(i);
2506
2507 // Extract half to create complex tree structure
2508 for (int i = 0; i < N / 2; ++i)
2509 {
2510 int val = heap.extract_min();
2511 EXPECT_EQ(val, i + 1);
2512 }
2513
2514 // Verify remaining half
2515 for (int i = N / 2 + 1; i <= N; ++i)
2516 {
2517 int val = heap.extract_min();
2518 EXPECT_EQ(val, i);
2519 }
2520
2521 EXPECT_TRUE(heap.is_empty());
2522}
2523
2524TEST(FibonacciHeapEdgeCases, SwapEmptyHeaps)
2525{
2526 Fibonacci_Heap<int> h1, h2;
2527
2528 h1.swap(h2);
2529
2530 EXPECT_TRUE(h1.is_empty());
2531 EXPECT_TRUE(h2.is_empty());
2532}
2533
2534TEST(FibonacciHeapEdgeCases, MoveAssignToSelf)
2535{
2537 heap.insert(1);
2538 heap.insert(2);
2539 heap.insert(3);
2540
2541#pragma GCC diagnostic push
2542#pragma GCC diagnostic ignored "-Wself-move"
2543 heap = std::move(heap);
2544#pragma GCC diagnostic pop
2545
2546 // After self-move, the heap should still be valid (either empty or same)
2547 // This is implementation-defined, but should not crash
2548}
2549
2550TEST(FibonacciHeapEdgeCases, DeleteLastTwoNodes)
2551{
2553 auto n1 = heap.insert(10);
2554 auto n2 = heap.insert(20);
2555
2556 heap.delete_node(n1);
2557 EXPECT_EQ(heap.size(), 1u);
2558 EXPECT_EQ(heap.get_min(), 20);
2559
2560 heap.delete_node(n2);
2561 EXPECT_TRUE(heap.is_empty());
2562}
2563
2564// =============================================================================
2565// Regression Tests
2566// =============================================================================
2567
2568// Test that delete_node properly handles the case where the deleted node
2569// is alone in the root list but has children
2570TEST(FibonacciHeapRegression, DeleteAloneRootWithChildren)
2571{
2573
2574 // Build a specific structure
2575 heap.insert(1);
2576 heap.insert(2);
2577 heap.insert(3);
2578 heap.insert(4);
2579
2580 // Extract to consolidate into a single tree
2581 EXPECT_EQ(heap.extract_min(), 1);
2582 EXPECT_EQ(heap.extract_min(), 2);
2583
2584 // Now we have 3 and 4, likely in a parent-child relationship
2585 // Delete the root (3)
2586 auto root = heap.get_min_node();
2587 heap.delete_node(root);
2588
2589 // Should have only 4 left
2590 EXPECT_EQ(heap.size(), 1u);
2591 EXPECT_EQ(heap.get_min(), 4);
2592}
2593
2594// Test cascading cuts trigger properly
2595TEST(FibonacciHeapRegression, CascadingCutsChain)
2596{
2598 std::vector<Fibonacci_Heap<int>::Node *> nodes;
2599
2600 // Create a deep tree by inserting many elements
2601 for (int i = 1; i <= 100; ++i)
2602 nodes.push_back(heap.insert(i * 100));
2603
2604 // Extract several to build tree structure
2605 for (int i = 0; i < 30; ++i)
2606 heap.extract_min();
2607
2608 // Now decrease keys to trigger cascading cuts
2609 // Decrease non-extracted nodes in sequence
2610 int key = 1;
2611 for (size_t i = 50; i < 70; ++i)
2612 {
2613 if (nodes[i]->data > key)
2614 {
2615 heap.decrease_key(nodes[i], key);
2616 ++key;
2617 }
2618 }
2619
2620 // Verify heap property is maintained
2621 int prev = heap.extract_min();
2622 while (!heap.is_empty())
2623 {
2624 int curr = heap.extract_min();
2625 EXPECT_LE(prev, curr);
2626 prev = curr;
2627 }
2628}
2629
2630namespace
2631{
2632 // Runs f, which must not throw, in a thread with a stack of 256 KiB, which
2633 // a recursion as deep as the trees of these tests are high overflows.
2634 // Without POSIX threads, it runs f in this thread.
2635 template <class F>
2636 void run_with_small_stack(F f)
2637 {
2638# if defined(__unix__) || defined(__APPLE__)
2639 pthread_attr_t attr;
2640 ASSERT_EQ(pthread_attr_init(&attr), 0);
2641 ASSERT_EQ(pthread_attr_setstacksize(&attr, 256 * 1024), 0);
2642 auto start = [](void *arg) -> void *
2643 {
2644 (*static_cast<F *>(arg))();
2645 return nullptr;
2646 };
2647 pthread_t thread;
2648 const int created = pthread_create(&thread, &attr, start, &f);
2649 pthread_attr_destroy(&attr);
2650 ASSERT_EQ(created, 0);
2651 ASSERT_EQ(pthread_join(thread, nullptr), 0);
2652# else
2653 f();
2654# endif
2655 }
2656
2657 // Puts in heap, which must be empty, a single tree that is a chain of n
2658 // nodes (CLRS, exercise 19.4-1). Each round inserts a < b < c below the
2659 // root and extracts a, so that b takes c and the chain as children; then
2660 // it cuts c with decrease_key() and extracts it, so that b ends on top of
2661 // the chain.
2662 void build_chain(Fibonacci_Heap<long> & heap, long n)
2663 {
2664 long key = 4 * n;
2665 (void) heap.insert(key);
2666 for (long i = 1; i < n; ++i)
2667 {
2668 const long b = key - 2;
2669 (void) heap.insert(key - 3);
2670 (void) heap.insert(b);
2671 auto *c = heap.insert(key - 1);
2672 (void) heap.extract_min();
2673 heap.decrease_key(c, b - 1);
2674 (void) heap.extract_min();
2675 key = b;
2676 }
2677 }
2678
2679 // The number of nodes from the root down by child
2680 size_t height_of_chain(const Fibonacci_Heap<long> & heap)
2681 {
2682 size_t height = 0;
2683 for (auto *p = heap.get_min_node(); p != nullptr; p = p->child)
2684 ++height;
2685 return height;
2686 }
2687}
2688
2689// clear() deleted the children of each node recursively, so a tree as high
2690// as the heap is large overflowed the stack
2691TEST(FibonacciHeapRegression, ClearsATreeAsHighAsTheHeap)
2692{
2693 constexpr long n = 50000;
2695 build_chain(heap, n);
2696 ASSERT_EQ(heap.size(), size_t(n));
2697 ASSERT_EQ(heap.get_min_node()->right, heap.get_min_node()); // one tree
2698 ASSERT_EQ(height_of_chain(heap), size_t(n));
2699
2700 run_with_small_stack([&heap] { heap.clear(); });
2701 EXPECT_TRUE(heap.is_empty());
2702 EXPECT_EQ(heap.size(), 0u);
2703
2704 (void) heap.insert(7);
2705 EXPECT_EQ(heap.get_min(), 7);
2706}
2707
2708// The destructor deletes the nodes as clear() does
2709TEST(FibonacciHeapRegression, DestroysATreeAsHighAsTheHeap)
2710{
2711 constexpr long n = 50000;
2712 auto heap = std::make_unique<Fibonacci_Heap<long>>();
2713 build_chain(*heap, n);
2714 ASSERT_EQ(height_of_chain(*heap), size_t(n));
2715
2716 run_with_small_stack([&heap] { heap.reset(); });
2717 EXPECT_EQ(heap, nullptr);
2718}
2719
2720int main(int argc, char **argv)
2721{
2722 ::testing::InitGoogleTest(&argc, argv);
2723 return RUN_ALL_TESTS();
2724}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
void PrintTo(const mpq_class &q, std::ostream *os)
WeightedDigraph::Node Node
int main()
long double h
Definition btreepic.C:154
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Implementation of a Fibonacci Heap priority queue.
const T & get_min() const
Returns the minimum element without removing it.
Node * get_min_node() const noexcept
Returns a pointer to the minimum node.
Compare key_comp() const
Returns the comparison functor.
void clear() noexcept(std::is_nothrow_destructible_v< T >)
Removes all elements from the heap.
Node * insert(const T &val)
Inserts a new element (copy).
void merge(Fibonacci_Heap &other)
Merges another heap into this one.
void swap(Fibonacci_Heap &other) noexcept(std::is_nothrow_swappable_v< Compare >)
Swaps contents with another heap.
Node * emplace(Args &&... args)
Constructs and inserts an element in-place.
size_t size() const noexcept
Returns the number of elements in the heap.
T extract_min()
Extracts and returns the minimum element.
Compare & get_compare() noexcept
Returns the comparison functor that orders the heap.
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).
void decrease_key(Node *x, const T &k)
Decreases the key of a node.
bool is_empty() const noexcept
Checks if the heap is empty.
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Represents a point with rectangular coordinates in a 2D plane.
Definition point.H:221
Minimal std::expected-style result type for C++20.
Fibonacci_Heap< int > heap
std::vector< Fibonacci_Heap< int >::Node * > nodes
#define TEST(name)
#define N
Definition fib.C:294
bool verify_heap_property(Fibonacci_Heap< T, Compare > &heap)
TEST_F(FibonacciHeapTest, InsertSingleElement)
__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
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
static mpfr_t y
Definition mpfr_mul_d.c:3
size_t degree(const GT &g, typename GT::Node *p, SA &sa)
Degree of a node as an Eulerian walk counts it.
Definition eulerian.H:129
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
and
Check uniqueness with explicit hash + equality functors.
Itor3 merge(Itor1 source1Beg, Itor1 source1End, Itor2 source2Beg, Itor2 source2End, Itor3 destBeg)
Merge two sorted ranges.
Definition ahAlgo.H:1410
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
bool run_with_small_stack(F &&f, size_t kb=256)
Runs f in a thread whose stack has kb KiB, and returns false if the thread could not run; without POS...
STL namespace.
Represents a node in the Fibonacci Heap.
Node * right
Right sibling in circular list.
Counted(int v=0)
bool operator<(const Point &other) const
double distance() const
static long counter
Definition test-splice.C:40
int keys[]
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Fibonacci Heap implementation.