Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
prim_test.cc
Go to the documentation of this file.
1
13#include <gtest/gtest.h>
14
15#include <functional>
16#include <limits>
17#include <new>
18#include <random>
19#include <set>
20#include <stdexcept>
21#include <vector>
22
23#include <Prim.H>
24#include <Kruskal.H> // For comparison tests
25#include <tpl_graph.H>
26#include <tpl_graph_utils.H>
27#include <tpl_sgraph.H>
28
29using namespace Aleph;
30
31// Graph types for tests
33using Node = GT::Node;
34using Arc = GT::Arc;
35
36namespace {
37
38// Helper to compute total weight of tree
39template <class G>
40int tree_total_weight(const G &tree)
41{
42 int total = 0;
43 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
44 total += it.get_current_arc_ne()->get_info();
45 return total;
46}
47
48// Check if tree is connected (for undirected graphs)
49template <class G>
50bool is_tree_connected(const G &tree)
51{
52 if (tree.get_num_nodes() == 0)
53 return true;
54 if (tree.get_num_nodes() == 1)
55 return true;
56
57 // A tree with V nodes should have V-1 arcs
58 if (tree.get_num_arcs() != tree.get_num_nodes() - 1)
59 return false;
60
61 // BFS to check connectivity
62 tree.reset_nodes();
63 auto first = tree.get_first_node();
64 NODE_BITS(first).set_bit(Aleph::Spanning_Tree, true);
65
67 queue.append(first);
68 size_t visited = 1;
69
70 while (not queue.is_empty())
71 {
72 auto curr = queue.remove_first();
73 for (Node_Arc_Iterator<G> it(curr); it.has_curr(); it.next_ne())
74 {
75 auto tgt = it.get_tgt_node_ne();
77 {
78 NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
79 queue.append(tgt);
80 ++visited;
81 }
82 }
83 }
84
85 return visited == tree.get_num_nodes();
86}
87
88} // namespace
89
90// =============================================================================
91// Basic Functionality Tests
92// =============================================================================
93
94TEST(PrimBasic, EmptyGraph)
95{
96 GT g;
97 GT tree;
98
100
101 // Prim throws exception when graph has no nodes
102 EXPECT_THROW(prim(g, tree), std::exception);
103}
104
105TEST(PrimBasic, SingleNode)
106{
107 GT g;
108 g.insert_node(1);
109
110 GT tree;
112 prim(g, tree);
113
114 EXPECT_EQ(tree.get_num_nodes(), 1u);
115 EXPECT_EQ(tree.get_num_arcs(), 0u);
116}
117
118TEST(PrimBasic, TwoNodesOneArc)
119{
120 GT g;
121 auto n1 = g.insert_node(1);
122 auto n2 = g.insert_node(2);
123 g.insert_arc(n1, n2, 10);
124
125 GT tree;
127 prim(g, tree);
128
129 EXPECT_EQ(tree.get_num_nodes(), 2u);
130 EXPECT_EQ(tree.get_num_arcs(), 1u);
131 EXPECT_EQ(tree_total_weight(tree), 10);
132}
133
134TEST(PrimBasic, TriangleGraph)
135{
136 GT g;
137 auto n1 = g.insert_node(1);
138 auto n2 = g.insert_node(2);
139 auto n3 = g.insert_node(3);
140
141 // Triangle with weights 1, 2, 3
142 g.insert_arc(n1, n2, 1);
143 g.insert_arc(n2, n3, 2);
144 g.insert_arc(n1, n3, 3);
145
146 GT tree;
148 prim(g, tree);
149
150 EXPECT_EQ(tree.get_num_nodes(), 3u);
151 EXPECT_EQ(tree.get_num_arcs(), 2u);
152 EXPECT_EQ(tree_total_weight(tree), 3); // MST uses edges 1 and 2
153 EXPECT_TRUE(is_tree_connected(tree));
154}
155
156TEST(PrimBasic, SquareGraph)
157{
158 GT g;
159 auto n1 = g.insert_node(1);
160 auto n2 = g.insert_node(2);
161 auto n3 = g.insert_node(3);
162 auto n4 = g.insert_node(4);
163
164 // Square: 1-2-3-4-1 with diagonal 1-3
165 g.insert_arc(n1, n2, 1);
166 g.insert_arc(n2, n3, 2);
167 g.insert_arc(n3, n4, 3);
168 g.insert_arc(n4, n1, 4);
169 g.insert_arc(n1, n3, 5); // diagonal
170
171 GT tree;
173 prim(g, tree);
174
175 EXPECT_EQ(tree.get_num_nodes(), 4u);
176 EXPECT_EQ(tree.get_num_arcs(), 3u);
177 EXPECT_EQ(tree_total_weight(tree), 6); // MST uses edges 1, 2, 3
178 EXPECT_TRUE(is_tree_connected(tree));
179}
180
181// =============================================================================
182// Comparison with Kruskal Tests
183// =============================================================================
184
185TEST(PrimVsKruskal, SameWeightOnSimpleGraph)
186{
187 GT g;
188 auto n1 = g.insert_node(1);
189 auto n2 = g.insert_node(2);
190 auto n3 = g.insert_node(3);
191 auto n4 = g.insert_node(4);
192 auto n5 = g.insert_node(5);
193
194 g.insert_arc(n1, n2, 1);
195 g.insert_arc(n1, n3, 3);
196 g.insert_arc(n2, n3, 2);
197 g.insert_arc(n2, n4, 4);
198 g.insert_arc(n3, n4, 5);
199 g.insert_arc(n3, n5, 6);
200 g.insert_arc(n4, n5, 7);
201
202 GT prim_tree, kruskal_tree;
203
205 prim(g, prim_tree);
206
208 kruskal(g, kruskal_tree);
209
210 EXPECT_EQ(tree_total_weight(prim_tree), tree_total_weight(kruskal_tree));
211 EXPECT_TRUE(is_tree_connected(prim_tree));
212 EXPECT_TRUE(is_tree_connected(kruskal_tree));
213}
214
215TEST(PrimVsKruskal, RandomGraph)
216{
217 std::mt19937 rng(42); // Fixed seed for reproducibility
218 std::uniform_int_distribution<int> weight_dist(1, 100);
219
220 const int N = 20;
221 GT g;
222 std::vector<Node *> nodes;
223
224 for (int i = 0; i < N; ++i)
225 nodes.push_back(g.insert_node(i));
226
227 // Create a connected graph
228 for (int i = 1; i < N; ++i)
229 g.insert_arc(nodes[i-1], nodes[i], weight_dist(rng));
230
231 // Add some random edges
232 for (int i = 0; i < N * 2; ++i)
233 {
234 int a = rng() % N;
235 int b = rng() % N;
236 if (a != b)
237 g.insert_arc(nodes[a], nodes[b], weight_dist(rng));
238 }
239
240 GT prim_tree, kruskal_tree;
241
243 prim(g, prim_tree);
244
246 kruskal(g, kruskal_tree);
247
248 EXPECT_EQ(tree_total_weight(prim_tree), tree_total_weight(kruskal_tree));
249}
250
251// =============================================================================
252// Edge Cases Tests
253// =============================================================================
254
255TEST(PrimEdgeCases, AllEqualWeights)
256{
257 GT g;
258 auto n1 = g.insert_node(1);
259 auto n2 = g.insert_node(2);
260 auto n3 = g.insert_node(3);
261 auto n4 = g.insert_node(4);
262
263 // Complete graph with all equal weights
264 g.insert_arc(n1, n2, 1);
265 g.insert_arc(n1, n3, 1);
266 g.insert_arc(n1, n4, 1);
267 g.insert_arc(n2, n3, 1);
268 g.insert_arc(n2, n4, 1);
269 g.insert_arc(n3, n4, 1);
270
271 GT tree;
273 prim(g, tree);
274
275 EXPECT_EQ(tree.get_num_nodes(), 4u);
276 EXPECT_EQ(tree.get_num_arcs(), 3u);
277 EXPECT_EQ(tree_total_weight(tree), 3);
278 EXPECT_TRUE(is_tree_connected(tree));
279}
280
281TEST(PrimEdgeCases, LinearGraph)
282{
283 GT g;
284 auto n1 = g.insert_node(1);
285 auto n2 = g.insert_node(2);
286 auto n3 = g.insert_node(3);
287 auto n4 = g.insert_node(4);
288 auto n5 = g.insert_node(5);
289
290 // Linear chain: 1-2-3-4-5
291 g.insert_arc(n1, n2, 1);
292 g.insert_arc(n2, n3, 2);
293 g.insert_arc(n3, n4, 3);
294 g.insert_arc(n4, n5, 4);
295
296 GT tree;
298 prim(g, tree);
299
300 EXPECT_EQ(tree.get_num_nodes(), 5u);
301 EXPECT_EQ(tree.get_num_arcs(), 4u);
302 EXPECT_EQ(tree_total_weight(tree), 10); // 1+2+3+4
303 EXPECT_TRUE(is_tree_connected(tree));
304}
305
306TEST(PrimEdgeCases, StarGraph)
307{
308 GT g;
309 auto center = g.insert_node(0);
310
311 // Star graph with center connected to all others
312 for (int i = 1; i <= 5; ++i)
313 {
314 auto leaf = g.insert_node(i);
315 g.insert_arc(center, leaf, i);
316 }
317
318 GT tree;
320 prim(g, tree);
321
322 EXPECT_EQ(tree.get_num_nodes(), 6u);
323 EXPECT_EQ(tree.get_num_arcs(), 5u);
324 EXPECT_EQ(tree_total_weight(tree), 15); // 1+2+3+4+5
325 EXPECT_TRUE(is_tree_connected(tree));
326}
327
328// =============================================================================
329// Stress Tests
330// =============================================================================
331
332TEST(PrimStress, LargeGraph)
333{
334 std::mt19937 rng(12345);
335 std::uniform_int_distribution<int> weight_dist(1, 1000);
336
337 const int N = 100;
338 GT g;
339 std::vector<Node *> nodes;
340
341 for (int i = 0; i < N; ++i)
342 nodes.push_back(g.insert_node(i));
343
344 // Create a connected graph (chain)
345 for (int i = 1; i < N; ++i)
346 g.insert_arc(nodes[i-1], nodes[i], weight_dist(rng));
347
348 // Add random edges to make it denser
349 for (int i = 0; i < N * 3; ++i)
350 {
351 int a = rng() % N;
352 int b = rng() % N;
353 if (a != b)
354 g.insert_arc(nodes[a], nodes[b], weight_dist(rng));
355 }
356
357 GT prim_tree, kruskal_tree;
358
360 prim(g, prim_tree);
361
363 kruskal(g, kruskal_tree);
364
365 EXPECT_EQ(prim_tree.get_num_nodes(), static_cast<size_t>(N));
366 EXPECT_EQ(prim_tree.get_num_arcs(), static_cast<size_t>(N - 1));
367 EXPECT_TRUE(is_tree_connected(prim_tree));
368
369 // Both algorithms should produce trees with the same total weight
370 EXPECT_EQ(tree_total_weight(prim_tree), tree_total_weight(kruskal_tree));
371}
372
373TEST(PrimStress, DenseGraph)
374{
375 std::mt19937 rng(54321);
376 std::uniform_int_distribution<int> weight_dist(1, 100);
377
378 const int N = 30;
379 GT g;
380 std::vector<Node *> nodes;
381
382 for (int i = 0; i < N; ++i)
383 nodes.push_back(g.insert_node(i));
384
385 // Create almost complete graph
386 for (int i = 0; i < N; ++i)
387 for (int j = i + 1; j < N; ++j)
388 g.insert_arc(nodes[i], nodes[j], weight_dist(rng));
389
390 GT prim_tree, kruskal_tree;
391
393 prim(g, prim_tree);
394
396 kruskal(g, kruskal_tree);
397
398 EXPECT_EQ(prim_tree.get_num_nodes(), static_cast<size_t>(N));
399 EXPECT_EQ(prim_tree.get_num_arcs(), static_cast<size_t>(N - 1));
400 EXPECT_TRUE(is_tree_connected(prim_tree));
401
402 // Both algorithms should produce trees with the same total weight
403 EXPECT_EQ(tree_total_weight(prim_tree), tree_total_weight(kruskal_tree));
404}
405
406// =============================================================================
407// Node Mapping Tests
408// =============================================================================
409
410TEST(PrimMapping, NodesAreMapped)
411{
412 GT g;
413 auto n1 = g.insert_node(1);
414 auto n2 = g.insert_node(2);
415 auto n3 = g.insert_node(3);
416
417 g.insert_arc(n1, n2, 1);
418 g.insert_arc(n2, n3, 2);
419
420 GT tree;
422 prim(g, tree);
423
424 // Verify that each node in g maps to a node in tree
425 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
426 {
427 auto gnode = it.get_curr();
428 auto tnode = mapped_node<GT>(gnode);
429 EXPECT_NE(tnode, nullptr);
430 EXPECT_EQ(gnode->get_info(), tnode->get_info());
431 }
432}
433
434// =============================================================================
435// Textbook Example
436// =============================================================================
437
438TEST(PrimTextbook, ClassicExample)
439{
440 // Classic MST example from textbooks
441 // Graph with nodes A(0), B(1), C(2), D(3), E(4), F(5)
442 GT g;
443 auto a = g.insert_node(0);
444 auto b = g.insert_node(1);
445 auto c = g.insert_node(2);
446 auto d = g.insert_node(3);
447 auto e = g.insert_node(4);
448 auto f = g.insert_node(5);
449
450 g.insert_arc(a, b, 6);
451 g.insert_arc(a, c, 1);
452 g.insert_arc(a, d, 5);
453 g.insert_arc(b, c, 2);
454 g.insert_arc(b, e, 5);
455 g.insert_arc(c, d, 2);
456 g.insert_arc(c, e, 6);
457 g.insert_arc(c, f, 4);
458 g.insert_arc(d, f, 4);
459 g.insert_arc(e, f, 3);
460
461 GT tree;
463 prim(g, tree);
464
465 EXPECT_EQ(tree.get_num_nodes(), 6u);
466 EXPECT_EQ(tree.get_num_arcs(), 5u);
467 // MST weight: 1 + 2 + 2 + 3 + 4 = 12 (or could be 1+2+2+4+3=12)
468 EXPECT_EQ(tree_total_weight(tree), 12);
469 EXPECT_TRUE(is_tree_connected(tree));
470}
471
472// =============================================================================
473// Distance Tests
474// =============================================================================
475
476namespace {
477
478// The weight of an arc, or 100 minus it when `reversed` is set: a
479// default-constructed instance orders the arcs the other way.
480struct Reversible_Distance
481{
482 using Distance_Type = int;
483
484 bool reversed = false;
485
486 int operator()(Arc *a) const
487 {
488 return reversed ? 100 - a->get_info() : a->get_info();
489 }
490};
491
492// The weight of an arc times a factor, with no default constructor.
494{
495 using Distance_Type = int;
496
497 int factor;
498
499 explicit Factor_Only_Distance(int f) noexcept : factor(f) {}
500
501 int operator()(Arc *a) const { return factor * a->get_info(); }
502};
503
504// Total of the arcs of tree, measured with d
505template <class Distance>
506int tree_distance(const GT &tree, const Distance &d)
507{
508 int total = 0;
509 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
510 total += d(it.get_current_arc_ne());
511 return total;
512}
513
514// Total of the arcs of g that Prim painted, measured with d
515template <class Distance>
516int painted_distance(const GT &g, const Distance &d)
517{
518 int total = 0;
519 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
520 if (IS_ARC_VISITED(it.get_current_arc_ne(), Aleph::Spanning_Tree))
521 total += d(it.get_current_arc_ne());
522 return total;
523}
524
525} // namespace
526
527// The heap ordered the arcs with a default-constructed distance; only the
528// choice between two arcs that reach the same node used the given one. With
529// the reversed weights (99, 98 and 95), the tree took 99 and 95.
530TEST(PrimDistance, UsesTheDistanceItWasGiven)
531{
532 GT g;
533 auto n0 = g.insert_node(0);
534 auto n1 = g.insert_node(1);
535 auto n2 = g.insert_node(2);
536 g.insert_arc(n0, n1, 1);
537 g.insert_arc(n1, n2, 2);
538 g.insert_arc(n0, n2, 5);
539
540 const Reversible_Distance reversed{true};
542
543 GT tree;
544 prim(g, n0, tree);
545 EXPECT_EQ(tree_distance(tree, reversed), 98 + 95);
546
547 prim(g, n0);
548 EXPECT_EQ(painted_distance(g, reversed), 98 + 95);
549}
550
551// The same on random graphs, against Kruskal, which uses the given distance
552TEST(PrimDistance, MatchesKruskalWithTheGivenDistance)
553{
554 std::mt19937 rng(7);
555 std::uniform_int_distribution<int> weight_dist(1, 99);
556 const Reversible_Distance reversed{true};
557
558 for (int iter = 0; iter < 20; ++iter)
559 {
560 const int N = 15;
561 GT g;
562 std::vector<Node *> nodes;
563 for (int i = 0; i < N; ++i)
564 nodes.push_back(g.insert_node(i));
565 for (int i = 1; i < N; ++i)
566 g.insert_arc(nodes[i - 1], nodes[i], weight_dist(rng));
567 for (int i = 0; i < 2 * N; ++i)
568 {
569 const int a = rng() % N;
570 const int b = rng() % N;
571 if (a != b)
572 g.insert_arc(nodes[a], nodes[b], weight_dist(rng));
573 }
574
575 GT prim_tree, kruskal_tree;
577 prim(g, prim_tree);
579 kruskal(Reversible_Distance{true});
580 kruskal(g, kruskal_tree);
581
582 EXPECT_EQ(tree_distance(prim_tree, reversed),
583 tree_distance(kruskal_tree, reversed)) << "graph " << iter;
584
585 prim(g);
586 EXPECT_EQ(painted_distance(g, reversed),
587 tree_distance(kruskal_tree, reversed)) << "graph " << iter;
588 }
589}
590
591// Building that default comparator required a default constructor.
592TEST(PrimDistance, TakesADistanceWithoutADefaultConstructor)
593{
594 GT g;
595 auto n0 = g.insert_node(0);
596 auto n1 = g.insert_node(1);
597 auto n2 = g.insert_node(2);
598 g.insert_arc(n0, n1, 1);
599 g.insert_arc(n1, n2, 2);
600 g.insert_arc(n0, n2, 5);
601
602 const Factor_Only_Distance twice(2);
604
605 GT tree;
606 prim(g, tree);
607 EXPECT_EQ(tree_distance(tree, twice), 2 * (1 + 2));
608
609 prim(g);
610 EXPECT_EQ(painted_distance(g, twice), 2 * (1 + 2));
611}
612
613// =============================================================================
614// Painting Tests
615// =============================================================================
616
617namespace {
618
619size_t painted_arcs(const GT &g)
620{
621 size_t count = 0;
622 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
623 if (IS_ARC_VISITED(it.get_current_arc_ne(), Aleph::Spanning_Tree))
624 ++count;
625 return count;
626}
627
628} // namespace
629
630// The heap of the painting kept its nodes in a member that the nodes do not
631// have, so painting did not compile.
632TEST(PrimPainting, PaintsTheArcsOfTheTree)
633{
634 GT g;
635 auto a = g.insert_node(0);
636 auto b = g.insert_node(1);
637 auto c = g.insert_node(2);
638 auto d = g.insert_node(3);
639 auto e = g.insert_node(4);
640 auto f = g.insert_node(5);
641 g.insert_arc(a, b, 6);
642 g.insert_arc(a, c, 1);
643 g.insert_arc(a, d, 5);
644 g.insert_arc(b, c, 2);
645 g.insert_arc(b, e, 5);
646 g.insert_arc(c, d, 2);
647 g.insert_arc(c, e, 6);
648 g.insert_arc(c, f, 4);
649 g.insert_arc(d, f, 4);
650 g.insert_arc(e, f, 3);
651
653 prim(g, a);
654 EXPECT_EQ(painted_arcs(g), 5u);
655 EXPECT_EQ(painted_distance(g, Dft_Dist<GT>()), 12);
656
657 prim(g);
658 EXPECT_EQ(painted_arcs(g), 5u);
659 EXPECT_EQ(painted_distance(g, Dft_Dist<GT>()), 12);
660}
661
662// The painting put the loops of the first node in the heap. A light one
663// came out first and was painted, since the painting marks each arc it
664// takes from the heap before seeing whether it closes a cycle.
665TEST(PrimPainting, LeavesOutALoopOnTheFirstNode)
666{
667 GT g;
668 auto n0 = g.insert_node(0);
669 auto n1 = g.insert_node(1);
670 auto n2 = g.insert_node(2);
671 auto loop = g.insert_arc(n0, n0, 1);
672 g.insert_arc(n0, n1, 2);
673 g.insert_arc(n1, n2, 3);
674
676 prim(g, n0);
677 EXPECT_FALSE(IS_ARC_VISITED(loop, Aleph::Spanning_Tree));
678 EXPECT_EQ(painted_arcs(g), 2u);
679 EXPECT_EQ(painted_distance(g, Dft_Dist<GT>()), 2 + 3);
680
681 GT tree;
682 prim(g, n0, tree);
683 EXPECT_EQ(tree_total_weight(tree), 2 + 3);
684}
685
686// A heavy one never came out, and the cookie of the first node kept its heap
687// node after the heap freed it.
688TEST(PrimPainting, LeavesTheCookiesNullWithALoopOnTheFirstNode)
689{
690 GT g;
691 auto n0 = g.insert_node(0);
692 auto n1 = g.insert_node(1);
693 auto n2 = g.insert_node(2);
694 g.insert_arc(n0, n0, 100);
695 g.insert_arc(n0, n1, 2);
696 g.insert_arc(n1, n2, 3);
697
699 prim(g, n0);
700 EXPECT_EQ(painted_arcs(g), 2u);
701 EXPECT_EQ(NODE_COOKIE(n0), nullptr);
702 EXPECT_EQ(NODE_COOKIE(n1), nullptr);
703 EXPECT_EQ(NODE_COOKIE(n2), nullptr);
704}
705
706namespace {
707
708// The weight of an arc; tells in *read whether it read that of watched
709struct Watching_Distance
710{
711 using Distance_Type = int;
712
713 Arc *watched = nullptr;
714 bool *read = nullptr;
715
716 int operator()(Arc *a) const
717 {
718 if (a == watched)
719 *read = true;
720 return a->get_info();
721 }
722};
723
724} // namespace
725
726// The version that builds the tree put the loops of the first node in the
727// heap, and it marked in g the one that came out, as if it were in the tree
728TEST(PrimMapping, LeavesOutALoopOnTheFirstNode)
729{
730 GT g;
731 auto n0 = g.insert_node(0);
732 auto n1 = g.insert_node(1);
733 auto n2 = g.insert_node(2);
734 auto loop = g.insert_arc(n0, n0, 0);
735 g.insert_arc(n0, n1, 1);
736 g.insert_arc(n1, n2, 2);
737 g.insert_arc(n0, n2, 3);
738
739 bool read = false;
741 prim(Watching_Distance{loop, &read});
742 GT tree;
743 prim(g, n0, tree);
744 EXPECT_EQ(tree.get_num_arcs(), 2u);
745 EXPECT_EQ(tree_total_weight(tree), 1 + 2);
746 EXPECT_FALSE(IS_ARC_VISITED(loop, Aleph::Spanning_Tree));
747 EXPECT_EQ(painted_arcs(g), 2u); // the arcs of the tree, as when painting
748 EXPECT_FALSE(read); // the loop did not enter the heap
749
750 prim(g, n0);
751 EXPECT_FALSE(IS_ARC_VISITED(loop, Aleph::Spanning_Tree));
752 EXPECT_EQ(painted_arcs(g), 2u);
753 EXPECT_FALSE(read);
754}
755
756// =============================================================================
757// Exception Tests
758// =============================================================================
759
760namespace {
761
762// Counts the calls of a distance and makes one of them throw.
763struct Distance_Failure
764{
765 long calls = 0;
766 long fail_at = 0; // number of the call that throws; 0 for none
767
768 void count()
769 {
770 if (++calls == fail_at)
771 throw std::runtime_error("arc weight not available");
772 }
773};
774
775// The weight of an arc, counting the calls in failure
776struct Failing_Distance
777{
778 using Distance_Type = int;
779
780 Distance_Failure *failure = nullptr;
781
782 int operator()(Arc *a) const
783 {
784 if (failure != nullptr)
785 failure->count();
786 return a->get_info();
787 }
788};
789
790} // namespace
791
792// The heap called the distance in functions that were noexcept, so a
793// distance that threw there ended the program. When painting, the cookies
794// of the arcs left in the heap pointed to the heap nodes freed with it.
795TEST(PrimExceptions, DistanceThatThrowsLeavesTheGraphReusable)
796{
797 std::mt19937 rng(11);
798 std::uniform_int_distribution<int> weight_dist(1, 50);
799 const int N = 12;
800 GT g;
801 std::vector<Node *> nodes;
802 for (int i = 0; i < N; ++i)
803 nodes.push_back(g.insert_node(i));
804 for (int i = 1; i < N; ++i)
805 g.insert_arc(nodes[i - 1], nodes[i], weight_dist(rng));
806 for (int i = 0; i < 2 * N; ++i)
807 {
808 const int a = rng() % N;
809 const int b = rng() % N;
810 if (a != b)
811 g.insert_arc(nodes[a], nodes[b], weight_dist(rng));
812 }
813
814 GT expected;
816 kruskal(g, expected);
817 const int weight = tree_total_weight(expected);
818
819 Distance_Failure failure;
821
822 const std::vector<std::function<void()>> methods = {
823 [&] {
824 GT tree;
825 prim(g, tree);
826 EXPECT_EQ(tree_total_weight(tree), weight);
827 },
828 [&] {
829 prim(g);
830 EXPECT_EQ(painted_distance(g, Dft_Dist<GT>()), weight);
831 }
832 };
833
834 for (size_t m = 0; m < methods.size(); ++m)
835 {
836 failure = Distance_Failure();
837 methods[m]();
838 const long calls = failure.calls;
839 ASSERT_GT(calls, 0) << "method " << m;
840
841 for (long k = 1; k <= calls; ++k)
842 {
843 failure.calls = 0;
844 failure.fail_at = k;
845 EXPECT_THROW(methods[m](), std::runtime_error)
846 << "method " << m << ", call " << k;
847
848 if (m == 1)
849 {
850 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
851 {
852 EXPECT_EQ(NODE_COOKIE(it.get_curr()), nullptr)
853 << "call " << k;
854 }
855 }
856
857 failure.fail_at = 0;
858 methods[m]();
859 }
860 }
861}
862
863namespace {
864
865// Counts the nodes created with an info; the creation number fail_at throws
866int fragile_creations = 0;
867int fragile_fail_at = 0; // 0 for none
868
869struct Fragile_Node : public Graph_Node<int>
870{
871 using Graph_Node<int>::Graph_Node;
872
873 Fragile_Node(const int & info) : Graph_Node<int>(info)
874 {
875 if (fragile_fail_at != 0 and ++fragile_creations == fragile_fail_at)
876 throw std::bad_alloc();
877 }
878};
879
880using Fragile_Graph = List_Graph<Fragile_Node, Graph_Arc<int>>;
881
882} // namespace
883
884// The Prim_Info of the nodes were created before the guard that frees them,
885// so a node of the tree that could not be created leaked those before it.
886TEST(PrimExceptions, ANodeOfTheTreeThatCannotBeCreatedLeaksNothing)
887{
888 Fragile_Graph g;
889 std::vector<Fragile_Node *> nodes;
890 for (int i = 0; i < 5; ++i)
891 nodes.push_back(g.insert_node(i));
892 for (int i = 1; i < 5; ++i)
893 g.insert_arc(nodes[i - 1], nodes[i], i);
894 g.insert_arc(nodes[0], nodes[4], 10);
895
897 for (int k = 1; k <= 5; ++k) // the first, the ones between and the last
898 {
899 // the cookies hold the mapping of the previous run, and Prim leaves
900 // those of the nodes it does not reach as they are
901 for (auto p : nodes)
902 NODE_COOKIE(p) = nullptr;
903
904 fragile_creations = 0;
905 fragile_fail_at = k;
906 Fragile_Graph tree;
907 EXPECT_THROW(prim(g, nodes[0], tree), std::bad_alloc) << "node " << k;
908 fragile_fail_at = 0;
909
910 for (auto p : nodes)
911 {
912 EXPECT_EQ(NODE_COOKIE(p), nullptr) << "node " << k;
913 }
914
915 Fragile_Graph again; // the graph can be used again
916 prim(g, nodes[0], again);
917 EXPECT_EQ(tree_total_weight(again), 1 + 2 + 3 + 4) << "node " << k;
918 }
919}
920
921// =============================================================================
922// Mapping Tests
923// =============================================================================
924
925namespace {
926
927template <class G>
928struct PrimMappingTest : public ::testing::Test {};
929
930using Representations =
931 ::testing::Types<List_Graph<Graph_Node<int>, Graph_Arc<int>>,
934
935} // namespace
936
937TYPED_TEST_SUITE(PrimMappingTest, Representations);
938
939// Unmapping a node gave its node in the tree the cookie that the node still
940// had, its Prim_Info, freed right after: the tree mapped back to freed
941// memory. The data of the nodes repeat, so that only identity counts.
942TYPED_TEST(PrimMappingTest, NodesAndArcsMapBothWays)
943{
944 using G = TypeParam;
945 std::mt19937 rng(5);
946 std::uniform_int_distribution<int> weight_dist(1, 30);
947 const int N = 12;
948 G g;
949 std::vector<typename G::Node *> nodes;
950 for (int i = 0; i < N; ++i)
951 nodes.push_back(g.insert_node(i % 3));
952 for (int i = 1; i < N; ++i)
953 g.insert_arc(nodes[i - 1], nodes[i], weight_dist(rng));
954 for (int i = 0; i < 2 * N; ++i)
955 {
956 const int a = rng() % N;
957 const int b = rng() % N;
958 if (a != b)
959 g.insert_arc(nodes[a], nodes[b], weight_dist(rng));
960 }
961
962 G tree;
964 prim(g, nodes[0], tree);
965 ASSERT_EQ(tree.get_num_nodes(), g.get_num_nodes());
966 ASSERT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
967
968 std::set<typename G::Node *> tree_nodes;
969 for (auto it = tree.get_node_it(); it.has_curr(); it.next_ne())
970 tree_nodes.insert(it.get_curr());
971 std::set<typename G::Arc *> graph_arcs;
972 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
973 graph_arcs.insert(it.get_curr());
974
975 for (auto p : nodes)
976 {
977 auto t = mapped_node<G>(p);
978 ASSERT_TRUE(tree_nodes.contains(t));
979 EXPECT_EQ(mapped_node<G>(t), p);
980 EXPECT_EQ(t->get_info(), p->get_info());
981 }
982
983 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
984 {
985 auto ta = it.get_curr();
986 auto a = mapped_arc<G>(ta);
987 ASSERT_TRUE(graph_arcs.contains(a));
988 EXPECT_EQ(mapped_arc<G>(a), ta);
989 auto s = mapped_node<G>(tree.get_src_node(ta));
990 auto t = mapped_node<G>(tree.get_tgt_node(ta));
991 EXPECT_TRUE((g.get_src_node(a) == s and g.get_tgt_node(a) == t) or
992 (g.get_src_node(a) == t and g.get_tgt_node(a) == s));
993 }
994}
Kruskal's minimum spanning tree algorithm.
Prim's algorithm for minimum spanning trees.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
Default distance accessor for arc weights.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T remove_first()
See remove().
Definition htlist.H:1473
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Arc for graphs implemented with simple adjacency lists.
Definition tpl_sgraph.H:197
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Computes the minimum spanning tree of a graph using Kruskal's algorithm.
Definition Kruskal.H:94
Node * get_first_node() const
Return any node in the graph.
Definition tpl_graph.H:590
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Graph_Arc< int > Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Graph class implemented with singly-linked adjacency lists.
Definition tpl_sgraph.H:274
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Computes the minimum spanning tree of a graph using Prim's algorithm.
Definition Prim.H:223
Minimal std::expected-style result type for C++20.
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
auto get_arc_it() const noexcept
Obtains an iterator to the arc of graph.
Definition graph-dry.H:3144
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
static mt19937 rng
#define N
Definition fib.C:294
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define NODE_COOKIE(p)
Return the node cookie
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
#define NODE_BITS(p)
Get the control bits of a node.
@ Spanning_Tree
Definition aleph-graph.H:79
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Spec reversed(const Spec &s)
The spec with each arc reversed; the arcs keep their numbers.
TYPED_TEST(PrimMappingTest, NodesAndArcsMapBothWays)
Definition prim_test.cc:942
TYPED_TEST_SUITE(PrimMappingTest, Representations)
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Node belonging to a graph implemented with a double linked adjacency list.
Definition tpl_graph.H:126
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Distance accessor.
int operator()(IntGraph::Arc *a) const
Call_Failure * failure
int operator()(IntGraph::Arc *a) const
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.
Simple graph implementation with adjacency lists.