Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
test_kruskal.cc
Go to the documentation of this file.
1
13#include <gtest/gtest.h>
14
15#include <limits>
16#include <optional>
17#include <random>
18#include <set>
19#include <stdexcept>
20#include <vector>
21
22#include <Kruskal.H>
23#include <tpl_graph.H>
24#include <tpl_sgraph.H>
25#include <tpl_agraph.H>
26
27using namespace Aleph;
28
29// Graph types for tests
31using Node = GT::Node;
32using Arc = GT::Arc;
33
34// Array-based graph type
37using AArc = AGT::Arc;
38
39namespace {
40
41// Helper to count painted arcs
42template <class G>
43size_t count_painted_arcs(const G &g)
44{
45 size_t n = 0;
46 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
47 if (IS_ARC_VISITED(it.get_current_arc_ne(), Aleph::Spanning_Tree))
48 ++n;
49 return n;
50}
51
52// Helper to compute total weight of tree
53template <class G>
54int tree_total_weight(const G &tree)
55{
56 int total = 0;
57 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
58 total += it.get_current_arc_ne()->get_info();
59 return total;
60}
61
62// Helper to compute total weight of painted arcs
63template <class G>
64int painted_total_weight(const G &g)
65{
66 int total = 0;
67 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
68 {
69 auto arc = it.get_current_arc_ne();
71 total += arc->get_info();
72 }
73 return total;
74}
75
76// Custom distance accessor for testing
77template <class G>
78struct Scaled_Dist
79{
80 using Distance_Type = int;
81 static const Distance_Type Zero_Distance = 0;
82 static const Distance_Type Max_Distance = std::numeric_limits<int>::max();
83
84 int factor = 1;
85 Scaled_Dist() = default;
86 explicit Scaled_Dist(int f) : factor(f) {}
87
88 int operator()(typename G::Arc *a) const noexcept
89 {
90 return a->get_info() * factor;
91 }
92};
93
94// Custom arc filter that only accepts arcs with weight <= threshold
95template <class G>
96struct Weight_Filter
97{
98 int threshold;
99
100 Weight_Filter(int t = std::numeric_limits<int>::max()) : threshold(t) {}
101
102 bool operator()(typename G::Arc *a) const noexcept
103 {
104 return a->get_info() <= threshold;
105 }
106};
107
108// Check if tree is connected (for undirected graphs)
109template <class G>
110bool is_tree_connected(const G &tree)
111{
112 if (tree.get_num_nodes() == 0)
113 return true;
114 if (tree.get_num_nodes() == 1)
115 return true;
116
117 // A tree with V nodes should have V-1 arcs
118 if (tree.get_num_arcs() != tree.get_num_nodes() - 1)
119 return false;
120
121 // BFS to check connectivity
122 tree.reset_nodes();
123 auto first = tree.get_first_node();
124 NODE_BITS(first).set_bit(Aleph::Spanning_Tree, true);
125
127 queue.append(first);
128 size_t visited = 1;
129
130 while (not queue.is_empty())
131 {
132 auto curr = queue.remove_first();
133 for (Node_Arc_Iterator<G> it(curr); it.has_curr(); it.next_ne())
134 {
135 auto tgt = it.get_tgt_node_ne();
137 {
138 NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
139 queue.append(tgt);
140 ++visited;
141 }
142 }
143 }
144
145 return visited == tree.get_num_nodes();
146}
147
148} // namespace
149
150// ========== TEST 1: Simple Connected Graph ==========
151TEST(KruskalTest, SimpleConnectedGraph) {
152
153 GT g;
154 Node* n0 = g.insert_node(0);
155 Node* n1 = g.insert_node(1);
156 Node* n2 = g.insert_node(2);
157 Node* n3 = g.insert_node(3);
158
159 g.insert_arc(n0, n1, 1);
160 g.insert_arc(n0, n2, 4);
161 g.insert_arc(n1, n2, 2);
162 g.insert_arc(n1, n3, 5);
163 g.insert_arc(n2, n3, 3);
164
166 GT tree;
167 kruskal(g, tree);
168
169 // Tree should have same number of nodes as g
170 ASSERT_EQ(tree.get_num_nodes(), g.get_num_nodes());
171
172 // Tree should have n-1 arcs (spanning tree)
173 ASSERT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
174
175 // MST weight: edges (0,1)=1 + (1,2)=2 + (2,3)=3 = 6
176 ASSERT_EQ(tree_total_weight(tree), 6);
177}
178
179// ========== TEST 2: Single Node Graph ==========
180TEST(KruskalTest, SingleNodeGraph) {
181
182 GT g;
183 g.insert_node(0);
184
186 GT tree;
187 kruskal(g, tree);
188
189 ASSERT_EQ(tree.get_num_nodes(), 1u);
190 ASSERT_EQ(tree.get_num_arcs(), 0u);
191}
192
193// ========== TEST 3: Two Nodes One Arc ==========
194TEST(KruskalTest, TwoNodesOneArc) {
195
196 GT g;
197 Node* n0 = g.insert_node(0);
198 Node* n1 = g.insert_node(1);
199 g.insert_arc(n0, n1, 5);
200
202 GT tree;
203 kruskal(g, tree);
204
205 ASSERT_EQ(tree.get_num_nodes(), 2u);
206 ASSERT_EQ(tree.get_num_arcs(), 1u);
207 ASSERT_EQ(tree_total_weight(tree), 5);
208}
209
210// ========== TEST 4: Linear Chain ==========
211TEST(KruskalTest, LinearChain) {
212
213 GT g;
214 const int num_nodes = 5;
215 std::vector<Node*> nodes;
216
217 for (int i = 0; i < num_nodes; ++i)
218 nodes.push_back(g.insert_node(i));
219
220 // Chain: 0--1--2--3--4 with weights 1,2,3,4
221 for (int i = 0; i < num_nodes - 1; ++i)
222 g.insert_arc(nodes[i], nodes[i+1], i + 1);
223
225 GT tree;
226 kruskal(g, tree);
227
228 // Tree is the chain itself
229 ASSERT_EQ(tree.get_num_nodes(), static_cast<size_t>(num_nodes));
230 ASSERT_EQ(tree.get_num_arcs(), static_cast<size_t>(num_nodes - 1));
231 // Total weight: 1+2+3+4 = 10
232 ASSERT_EQ(tree_total_weight(tree), 10);
233}
234
235// ========== TEST 5: Complete Graph K4 ==========
236TEST(KruskalTest, CompleteGraphK4) {
237
238 GT g;
239 Node* n0 = g.insert_node(0);
240 Node* n1 = g.insert_node(1);
241 Node* n2 = g.insert_node(2);
242 Node* n3 = g.insert_node(3);
243
244 // K4 with distinct weights
245 g.insert_arc(n0, n1, 1); // min
246 g.insert_arc(n0, n2, 2); // 2nd min
247 g.insert_arc(n0, n3, 10);
248 g.insert_arc(n1, n2, 5);
249 g.insert_arc(n1, n3, 3); // 3rd min
250 g.insert_arc(n2, n3, 7);
251
253 GT tree;
254 kruskal(g, tree);
255
256 ASSERT_EQ(tree.get_num_nodes(), 4u);
257 ASSERT_EQ(tree.get_num_arcs(), 3u);
258 // MST: (0,1)=1 + (0,2)=2 + (1,3)=3 = 6
259 ASSERT_EQ(tree_total_weight(tree), 6);
260}
261
262// ========== TEST 6: Star Graph ==========
263TEST(KruskalTest, StarGraph) {
264
265 GT g;
266 Node* center = g.insert_node(0);
267 const int num_leaves = 5;
268 std::vector<Node*> leaves;
269
270 for (int i = 1; i <= num_leaves; ++i)
271 {
272 auto leaf = g.insert_node(i);
273 leaves.push_back(leaf);
274 g.insert_arc(center, leaf, i);
275 }
276
278 GT tree;
279 kruskal(g, tree);
280
281 // Star tree: center connects to all leaves
282 ASSERT_EQ(tree.get_num_nodes(), static_cast<size_t>(num_leaves + 1));
283 ASSERT_EQ(tree.get_num_arcs(), static_cast<size_t>(num_leaves));
284 // Total weight: 1+2+3+4+5 = 15
285 ASSERT_EQ(tree_total_weight(tree), 15);
286}
287
288// ========== TEST 7: Grid Graph 3x3 ==========
289TEST(KruskalTest, GridGraph3x3) {
290
291 GT g;
292 std::vector<std::vector<Node*>> grid(3, std::vector<Node*>(3));
293
294 // Create 3x3 grid
295 int id = 0;
296 for (int i = 0; i < 3; ++i)
297 for (int j = 0; j < 3; ++j)
298 grid[i][j] = g.insert_node(id++);
299
300 // Add horizontal edges (weight = row + 1)
301 for (int i = 0; i < 3; ++i)
302 for (int j = 0; j < 2; ++j)
303 g.insert_arc(grid[i][j], grid[i][j+1], i + 1);
304
305 // Add vertical edges (weight = column + 5)
306 for (int i = 0; i < 2; ++i)
307 for (int j = 0; j < 3; ++j)
308 g.insert_arc(grid[i][j], grid[i+1][j], j + 5);
309
311 GT tree;
312 kruskal(g, tree);
313
314 // 9 nodes, should have 8 arcs
315 ASSERT_EQ(tree.get_num_nodes(), 9u);
316 ASSERT_EQ(tree.get_num_arcs(), 8u);
317 ASSERT_TRUE(is_tree_connected(tree));
318}
319
320// ========== TEST 8: Diamond Graph ==========
321TEST(KruskalTest, DiamondGraph) {
322
323 GT g;
324 Node* n0 = g.insert_node(0);
325 Node* n1 = g.insert_node(1);
326 Node* n2 = g.insert_node(2);
327 Node* n3 = g.insert_node(3);
328
329 // Diamond shape with two paths
330 g.insert_arc(n0, n1, 1);
331 g.insert_arc(n0, n2, 2);
332 g.insert_arc(n1, n3, 3);
333 g.insert_arc(n2, n3, 1);
334
336 GT tree;
337 kruskal(g, tree);
338
339 ASSERT_EQ(tree.get_num_nodes(), 4u);
340 ASSERT_EQ(tree.get_num_arcs(), 3u);
341 // MST: (0,1)=1 + (2,3)=1 + (0,2)=2 = 4
342 ASSERT_EQ(tree_total_weight(tree), 4);
343}
344
345// ========== TEST 9: All Equal Weights ==========
346TEST(KruskalTest, AllEqualWeights) {
347
348 GT g;
349 Node* n0 = g.insert_node(0);
350 Node* n1 = g.insert_node(1);
351 Node* n2 = g.insert_node(2);
352 Node* n3 = g.insert_node(3);
353
354 // All edges have weight 5
355 g.insert_arc(n0, n1, 5);
356 g.insert_arc(n0, n2, 5);
357 g.insert_arc(n0, n3, 5);
358 g.insert_arc(n1, n2, 5);
359 g.insert_arc(n1, n3, 5);
360 g.insert_arc(n2, n3, 5);
361
363 GT tree;
364 kruskal(g, tree);
365
366 // Any spanning tree is valid
367 ASSERT_EQ(tree.get_num_nodes(), 4u);
368 ASSERT_EQ(tree.get_num_arcs(), 3u);
369 // Total weight: 3 * 5 = 15
370 ASSERT_EQ(tree_total_weight(tree), 15);
371}
372
373// ========== TEST 10: Unique Weights ==========
374TEST(KruskalTest, UniqueWeights) {
375
376 GT g;
377 Node* n0 = g.insert_node(0);
378 Node* n1 = g.insert_node(1);
379 Node* n2 = g.insert_node(2);
380 Node* n3 = g.insert_node(3);
381
382 // All edges have unique weights
383 g.insert_arc(n0, n1, 1);
384 g.insert_arc(n0, n2, 3);
385 g.insert_arc(n0, n3, 5);
386 g.insert_arc(n1, n2, 2);
387 g.insert_arc(n1, n3, 6);
388 g.insert_arc(n2, n3, 4);
389
391 GT tree;
392 kruskal(g, tree);
393
394 // Deterministic MST: (0,1)=1 + (1,2)=2 + (2,3)=4 = 7
395 ASSERT_EQ(tree_total_weight(tree), 7);
396}
397
398// ========== TEST 11: Zero Weight Edges ==========
399TEST(KruskalTest, ZeroWeightEdges) {
400
401 GT g;
402 Node* n0 = g.insert_node(0);
403 Node* n1 = g.insert_node(1);
404 Node* n2 = g.insert_node(2);
405
406 g.insert_arc(n0, n1, 0);
407 g.insert_arc(n1, n2, 0);
408
410 GT tree;
411 kruskal(g, tree);
412
413 ASSERT_EQ(tree.get_num_nodes(), 3u);
414 ASSERT_EQ(tree.get_num_arcs(), 2u);
415 ASSERT_EQ(tree_total_weight(tree), 0);
416}
417
418// ========== TEST 12: Large Weights ==========
419TEST(KruskalTest, LargeWeights) {
420
421 GT g;
422 Node* n0 = g.insert_node(0);
423 Node* n1 = g.insert_node(1);
424 Node* n2 = g.insert_node(2);
425
426 g.insert_arc(n0, n1, 1000000);
427 g.insert_arc(n1, n2, 2000000);
428 g.insert_arc(n0, n2, 1500000);
429
431 GT tree;
432 kruskal(g, tree);
433
434 ASSERT_EQ(tree.get_num_arcs(), 2u);
435 // MST: (0,1)=1000000 + (0,2)=1500000 = 2500000
436 ASSERT_EQ(tree_total_weight(tree), 2500000);
437}
438
439// ========== TEST 13: Parallel Edges ==========
440TEST(KruskalTest, ParallelEdges) {
441
442 GT g;
443 Node* n0 = g.insert_node(0);
444 Node* n1 = g.insert_node(1);
445
446 // Multiple edges between same nodes
447 g.insert_arc(n0, n1, 10);
448 g.insert_arc(n0, n1, 5); // minimum
449 g.insert_arc(n0, n1, 8);
450
452 GT tree;
453 kruskal(g, tree);
454
455 ASSERT_EQ(tree.get_num_nodes(), 2u);
456 ASSERT_EQ(tree.get_num_arcs(), 1u);
457 // Should pick the minimum weight edge
458 ASSERT_EQ(tree_total_weight(tree), 5);
459}
460
461// ========== TEST 14: Self Loop ==========
462TEST(KruskalTest, SelfLoop) {
463
464 GT g;
465 Node* n0 = g.insert_node(0);
466 Node* n1 = g.insert_node(1);
467
468 g.insert_arc(n0, n0, 1); // Self-loop
469 g.insert_arc(n0, n1, 2);
470
472 GT tree;
473 kruskal(g, tree);
474
475 ASSERT_EQ(tree.get_num_nodes(), 2u);
476 // Self-loops should be ignored (would create cycle)
477 ASSERT_EQ(tree.get_num_arcs(), 1u);
478 ASSERT_EQ(tree_total_weight(tree), 2);
479}
480
481// ========== TEST 15: Cycle Graph ==========
482TEST(KruskalTest, CycleGraph) {
483
484 GT g;
485 const int num_nodes = 5;
486 std::vector<Node*> nodes;
487
488 for (int i = 0; i < num_nodes; ++i)
489 nodes.push_back(g.insert_node(i));
490
491 // Create cycle: 0--1--2--3--4--0
492 for (int i = 0; i < num_nodes; ++i)
493 g.insert_arc(nodes[i], nodes[(i+1) % num_nodes], i + 1);
494
496 GT tree;
497 kruskal(g, tree);
498
499 // Should remove one edge to break the cycle
500 ASSERT_EQ(tree.get_num_nodes(), static_cast<size_t>(num_nodes));
501 ASSERT_EQ(tree.get_num_arcs(), static_cast<size_t>(num_nodes - 1));
502 // MST: picks 4 smallest edges = 1+2+3+4 = 10
503 ASSERT_EQ(tree_total_weight(tree), 10);
504}
505
506// ========== TEST 16: Paint Mode ==========
507TEST(KruskalTest, PaintMode) {
508
509 GT g;
510 Node* n0 = g.insert_node(0);
511 Node* n1 = g.insert_node(1);
512 Node* n2 = g.insert_node(2);
513 Node* n3 = g.insert_node(3);
514
515 g.insert_arc(n0, n1, 1);
516 g.insert_arc(n0, n2, 4);
517 g.insert_arc(n1, n2, 2);
518 g.insert_arc(n1, n3, 5);
519 g.insert_arc(n2, n3, 3);
520
522 kruskal(g); // Paint mode
523
524 // Verify spanning tree arcs are painted
525 ASSERT_EQ(count_painted_arcs(g), g.get_num_nodes() - 1);
526 // MST weight: 1+2+3 = 6
527 ASSERT_EQ(painted_total_weight(g), 6);
528}
529
530// ========== TEST 17: Tree Building Mode ==========
531TEST(KruskalTest, TreeBuildingMode) {
532
533 GT g;
534 Node* n0 = g.insert_node(0);
535 Node* n1 = g.insert_node(1);
536 Node* n2 = g.insert_node(2);
537
538 g.insert_arc(n0, n1, 1);
539 g.insert_arc(n1, n2, 2);
540 g.insert_arc(n0, n2, 5);
541
543 GT tree;
544 kruskal(g, tree);
545
546 ASSERT_EQ(tree.get_num_nodes(), 3u);
547 ASSERT_EQ(tree.get_num_arcs(), 2u);
548 ASSERT_TRUE(is_tree_connected(tree));
549}
550
551// ========== TEST 18: Tree Has V-1 Arcs ==========
552TEST(KruskalTest, TreeHasCorrectArcCount) {
553
554 GT g;
555 const int num_nodes = 10;
556 std::vector<Node*> nodes;
557
558 for (int i = 0; i < num_nodes; ++i)
559 nodes.push_back(g.insert_node(i));
560
561 // Create a complete graph
562 int weight = 1;
563 for (int i = 0; i < num_nodes; ++i)
564 for (int j = i + 1; j < num_nodes; ++j)
565 g.insert_arc(nodes[i], nodes[j], weight++);
566
568 GT tree;
569 kruskal(g, tree);
570
571 ASSERT_EQ(tree.get_num_nodes(), static_cast<size_t>(num_nodes));
572 ASSERT_EQ(tree.get_num_arcs(), static_cast<size_t>(num_nodes - 1));
573}
574
575// ========== TEST 19: All Nodes in Tree ==========
576TEST(KruskalTest, AllNodesInTree) {
577
578 GT g;
579 Node* n0 = g.insert_node(0);
580 Node* n1 = g.insert_node(1);
581 Node* n2 = g.insert_node(2);
582 Node* n3 = g.insert_node(3);
583
584 g.insert_arc(n0, n1, 1);
585 g.insert_arc(n1, n2, 2);
586 g.insert_arc(n2, n3, 3);
587
589 GT tree;
590 kruskal(g, tree);
591
592 // Verify all node info values are present
593 std::set<int> node_infos;
594 for (typename GT::Node_Iterator it(tree); it.has_curr(); it.next_ne())
595 node_infos.insert(it.get_curr()->get_info());
596
597 ASSERT_TRUE(node_infos.count(0));
598 ASSERT_TRUE(node_infos.count(1));
599 ASSERT_TRUE(node_infos.count(2));
600 ASSERT_TRUE(node_infos.count(3));
601}
602
603// ========== TEST 20: Tree is Connected ==========
604TEST(KruskalTest, TreeIsConnected) {
605
606 GT g;
607 const int num_nodes = 8;
608 std::vector<Node*> nodes;
609
610 for (int i = 0; i < num_nodes; ++i)
611 nodes.push_back(g.insert_node(i));
612
613 // Create random-ish connected graph
614 std::mt19937 rng(12345);
615 for (int i = 0; i < num_nodes - 1; ++i)
616 g.insert_arc(nodes[i], nodes[i+1], rng() % 10 + 1);
617
618 // Add some cross edges
619 g.insert_arc(nodes[0], nodes[4], rng() % 10 + 1);
620 g.insert_arc(nodes[2], nodes[6], rng() % 10 + 1);
621
623 GT tree;
624 kruskal(g, tree);
625
626 ASSERT_TRUE(is_tree_connected(tree));
627}
628
629// ========== TEST 21: Bit Flags Correctly Set ==========
630TEST(KruskalTest, BitFlagsCorrectlySet) {
631
632 GT g;
633 Node* n0 = g.insert_node(0);
634 Node* n1 = g.insert_node(1);
635 Node* n2 = g.insert_node(2);
636
637 Arc* a01 = g.insert_arc(n0, n1, 1);
638 Arc* a12 = g.insert_arc(n1, n2, 2);
639 Arc* a02 = g.insert_arc(n0, n2, 10); // Should not be in MST
640
642 kruskal(g);
643
644 ASSERT_TRUE(IS_ARC_VISITED(a01, Aleph::Spanning_Tree));
645 ASSERT_TRUE(IS_ARC_VISITED(a12, Aleph::Spanning_Tree));
646 ASSERT_FALSE(IS_ARC_VISITED(a02, Aleph::Spanning_Tree));
647}
648
649// ========== TEST 22: Node Mapping Correct ==========
650TEST(KruskalTest, NodeMappingCorrect) {
651
652 GT g;
653 Node* n0 = g.insert_node(100);
654 Node* n1 = g.insert_node(200);
655 Node* n2 = g.insert_node(300);
656
657 g.insert_arc(n0, n1, 1);
658 g.insert_arc(n1, n2, 2);
659
661 GT tree;
662 kruskal(g, tree);
663
664 // Check that tree nodes have same info as original nodes
665 std::set<int> tree_infos;
666 for (typename GT::Node_Iterator it(tree); it.has_curr(); it.next_ne())
667 tree_infos.insert(it.get_curr()->get_info());
668
669 ASSERT_TRUE(tree_infos.count(100));
670 ASSERT_TRUE(tree_infos.count(200));
671 ASSERT_TRUE(tree_infos.count(300));
672}
673
674// ========== TEST 23: Arc Mapping Correct ==========
675TEST(KruskalTest, ArcMappingCorrect) {
676
677 GT g;
678 Node* n0 = g.insert_node(0);
679 Node* n1 = g.insert_node(1);
680 Node* n2 = g.insert_node(2);
681
682 g.insert_arc(n0, n1, 5);
683 g.insert_arc(n1, n2, 7);
684
686 GT tree;
687 kruskal(g, tree);
688
689 // Check that tree arcs have same weights as original arcs
690 std::set<int> tree_weights;
691 for (typename GT::Arc_Iterator it(tree); it.has_curr(); it.next_ne())
692 tree_weights.insert(it.get_curr()->get_info());
693
694 ASSERT_TRUE(tree_weights.count(5));
695 ASSERT_TRUE(tree_weights.count(7));
696}
697
698// ========== TEST 24: Digraph Rejection ==========
699TEST(KruskalTest, DigraphRejection) {
700
702
703 DGT dg;
704 auto n0 = dg.insert_node(0);
705 auto n1 = dg.insert_node(1);
706 dg.insert_arc(n0, n1, 1);
707
709 EXPECT_THROW(kruskal(dg), std::domain_error);
710}
711
712// ========== TEST 27: Empty Graph ==========
713TEST(KruskalTest, EmptyGraph) {
714
715 GT g; // Empty graph
716
718 GT tree;
719 kruskal(g, tree);
720
721 ASSERT_EQ(tree.get_num_nodes(), 0u);
722 ASSERT_EQ(tree.get_num_arcs(), 0u);
723}
724
725// ========== TEST 28: Custom Distance Functor ==========
726TEST(KruskalTest, CustomDistanceFunctor) {
727
728 GT g;
729 Node* n0 = g.insert_node(0);
730 Node* n1 = g.insert_node(1);
731 Node* n2 = g.insert_node(2);
732
733 g.insert_arc(n0, n1, 2); // scaled = 4
734 g.insert_arc(n1, n2, 3); // scaled = 6
735 g.insert_arc(n0, n2, 4); // scaled = 8
736
737 Scaled_Dist<GT> dist(2);
739 GT tree;
740 kruskal(g, tree);
741
742 // MST should still pick (0,1) and (1,2)
743 ASSERT_EQ(tree.get_num_arcs(), 2u);
744 // Original weights: 2 + 3 = 5
745 ASSERT_EQ(tree_total_weight(tree), 5);
746}
747
748// ========== TEST 29: Array Graph Type ==========
749TEST(KruskalTest, ArrayGraphType) {
750
751 AGT g;
752 ANode* n0 = g.insert_node(0);
753 ANode* n1 = g.insert_node(1);
754 ANode* n2 = g.insert_node(2);
755
756 g.insert_arc(n0, n1, 1);
757 g.insert_arc(n1, n2, 2);
758 g.insert_arc(n0, n2, 5);
759
761 AGT tree;
762 kruskal(g, tree);
763
764 ASSERT_EQ(tree.get_num_nodes(), 3u);
765 ASSERT_EQ(tree.get_num_arcs(), 2u);
766 ASSERT_EQ(tree_total_weight(tree), 3);
767}
768
769// ========== TEST 30: Multiple Calls on Same Instance ==========
770TEST(KruskalTest, MultipleCallsSameInstance) {
771
772 GT g1;
773 Node* n0 = g1.insert_node(0);
774 Node* n1 = g1.insert_node(1);
775 g1.insert_arc(n0, n1, 5);
776
777 GT g2;
778 Node* m0 = g2.insert_node(0);
779 Node* m1 = g2.insert_node(1);
780 Node* m2 = g2.insert_node(2);
781 g2.insert_arc(m0, m1, 1);
782 g2.insert_arc(m1, m2, 2);
783
785
786 GT tree1;
787 kruskal(g1, tree1);
788 ASSERT_EQ(tree1.get_num_arcs(), 1u);
789
790 GT tree2;
791 kruskal(g2, tree2);
792 ASSERT_EQ(tree2.get_num_arcs(), 2u);
793}
794
795// ========== TEST 31: Large Connected Graph ==========
796TEST(KruskalTest, LargeConnectedGraph) {
797
798 GT g;
799 const int num_nodes = 100;
800 std::vector<Node*> nodes;
801
802 for (int i = 0; i < num_nodes; ++i)
803 nodes.push_back(g.insert_node(i));
804
805 // Create a chain to ensure connectivity
806 for (int i = 0; i < num_nodes - 1; ++i)
807 g.insert_arc(nodes[i], nodes[i+1], i + 1);
808
809 // Add random edges
810 std::mt19937 rng(99999);
811 std::uniform_int_distribution<int> ndist(0, num_nodes - 1);
812 std::uniform_int_distribution<int> wdist(1, 1000);
813
814 for (int e = 0; e < num_nodes * 3; ++e)
815 {
816 int u = ndist(rng);
817 int v = ndist(rng);
818 if (u != v)
819 g.insert_arc(nodes[u], nodes[v], wdist(rng));
820 }
821
823 GT tree;
824 kruskal(g, tree);
825
826 ASSERT_EQ(tree.get_num_nodes(), static_cast<size_t>(num_nodes));
827 ASSERT_EQ(tree.get_num_arcs(), static_cast<size_t>(num_nodes - 1));
828 ASSERT_TRUE(is_tree_connected(tree));
829}
830
831// ========== TEST 32: Paint Then Build Tree ==========
832TEST(KruskalTest, PaintThenBuildTree) {
833
834 GT g;
835 Node* n0 = g.insert_node(0);
836 Node* n1 = g.insert_node(1);
837 Node* n2 = g.insert_node(2);
838
839 g.insert_arc(n0, n1, 1);
840 g.insert_arc(n1, n2, 2);
841 g.insert_arc(n0, n2, 5);
842
844
845 // First paint
846 kruskal(g);
847 int painted_weight = painted_total_weight(g);
848
849 // Then build tree
850 GT tree;
851 kruskal(g, tree);
852 int tree_weight = tree_total_weight(tree);
853
854 // Both should have same weight
855 ASSERT_EQ(painted_weight, tree_weight);
856}
857
858// ========== TEST 33: Disconnected Graph Creates Forest ==========
859TEST(KruskalTest, DisconnectedGraphCreatesForest) {
860
861 GT g;
862 // Component 1
863 Node* n0 = g.insert_node(0);
864 Node* n1 = g.insert_node(1);
865 g.insert_arc(n0, n1, 1);
866
867 // Component 2 (disconnected)
868 Node* n2 = g.insert_node(2);
869 Node* n3 = g.insert_node(3);
870 g.insert_arc(n2, n3, 2);
871
873 GT tree;
874 kruskal(g, tree);
875
876 // Should create a forest with 2 trees
877 ASSERT_EQ(tree.get_num_nodes(), 4u);
878 ASSERT_EQ(tree.get_num_arcs(), 2u); // Two separate edges
879}
880
881// ========== TEST 34: Verify Minimum Weight Property ==========
882TEST(KruskalTest, VerifyMinimumWeightProperty) {
883
884 GT g;
885 Node* n0 = g.insert_node(0);
886 Node* n1 = g.insert_node(1);
887 Node* n2 = g.insert_node(2);
888 Node* n3 = g.insert_node(3);
889
890 // Create graph with known MST
891 g.insert_arc(n0, n1, 1); // in MST
892 g.insert_arc(n0, n2, 3); // in MST
893 g.insert_arc(n0, n3, 10); // not in MST
894 g.insert_arc(n1, n2, 5); // not in MST
895 g.insert_arc(n1, n3, 4); // in MST
896 g.insert_arc(n2, n3, 6); // not in MST
897
899 GT tree;
900 kruskal(g, tree);
901
902 // MST weight should be: 1 + 3 + 4 = 8
903 ASSERT_EQ(tree_total_weight(tree), 8);
904
905 // Verify this is minimum by checking against all spanning tree possibilities
906 // (For this simple graph, we can verify manually)
907 ASSERT_LT(tree_total_weight(tree), 1 + 3 + 6); // alt tree
908 ASSERT_LT(tree_total_weight(tree), 1 + 5 + 4); // alt tree
909 ASSERT_LT(tree_total_weight(tree), 1 + 10 + 6); // alt tree
910}
911
912// ========== TEST 35: Repeated Edges Same Nodes ==========
913TEST(KruskalTest, RepeatedEdgesSameNodes) {
914
915 GT g;
916 Node* n0 = g.insert_node(0);
917 Node* n1 = g.insert_node(1);
918 Node* n2 = g.insert_node(2);
919
920 // Multiple edges between pairs
921 g.insert_arc(n0, n1, 10);
922 g.insert_arc(n0, n1, 1); // min
923 g.insert_arc(n1, n2, 8);
924 g.insert_arc(n1, n2, 2); // min
925
927 GT tree;
928 kruskal(g, tree);
929
930 // Should pick minimum edges
931 ASSERT_EQ(tree_total_weight(tree), 3); // 1 + 2
932}
933
934// ========== TEST 36: is_painted() Getter ==========
935TEST(KruskalTest, IsPaintedGetter) {
936
937 GT g;
938 Node* n0 = g.insert_node(0);
939 Node* n1 = g.insert_node(1);
940 Node* n2 = g.insert_node(2);
941
942 g.insert_arc(n0, n1, 1);
943 g.insert_arc(n1, n2, 2);
944
946
947 // Before painting
948 ASSERT_FALSE(kruskal.is_painted());
949
950 // After painting
951 kruskal(g);
952 ASSERT_TRUE(kruskal.is_painted());
953
954 // After painting to tree (should still be true)
955 GT tree;
956 kruskal(g, tree);
957 ASSERT_TRUE(kruskal.is_painted());
958}
959
960// ========== TEST 37: Distance and Filter in Variables ==========
961TEST(KruskalTest, DistanceAndFilterInVariables) {
962
963 GT g;
964 Node* n0 = g.insert_node(0);
965 Node* n1 = g.insert_node(1);
966 Node* n2 = g.insert_node(2);
967 Node* n3 = g.insert_node(3);
968
969 g.insert_arc(n0, n1, 1);
970 g.insert_arc(n1, n2, 2);
971 g.insert_arc(n0, n2, 3);
972 g.insert_arc(n2, n3, 4);
973 g.insert_arc(n1, n3, 9);
974
975 // With a distance in a variable, the constructor was ambiguous
976 Scaled_Dist<GT> reversed(-1); // the heaviest arcs first
977 Weight_Filter<GT> up_to_4(4); // hides the arc of 9
979 kruskal(reversed, up_to_4);
980
981 GT tree;
982 kruskal(g, tree);
983 ASSERT_EQ(tree.get_num_arcs(), 3u);
984 ASSERT_EQ(tree_total_weight(tree), 4 + 3 + 2);
985
986 kruskal(g);
987 ASSERT_EQ(count_painted_arcs(g), 3u);
988 ASSERT_EQ(painted_total_weight(g), 4 + 3 + 2);
989}
990
991// ========== TEST 38: A Copy Keeps Its Own Distance ==========
992TEST(KruskalTest, CopyKeepsItsOwnDistance) {
993
994 GT g;
995 Node* n0 = g.insert_node(0);
996 Node* n1 = g.insert_node(1);
997 Node* n2 = g.insert_node(2);
998 Node* n3 = g.insert_node(3);
999
1000 g.insert_arc(n0, n1, 1);
1001 g.insert_arc(n1, n2, 2);
1002 g.insert_arc(n0, n2, 3);
1003 g.insert_arc(n2, n3, 4);
1004 g.insert_arc(n1, n3, 9);
1005
1006 using Reversed_Kruskal =
1008 std::optional<Reversed_Kruskal> original;
1009 original.emplace(Scaled_Dist<GT>(-1), Weight_Filter<GT>(4));
1010 Reversed_Kruskal copy(*original);
1011
1012 // The copy referred to the distance of the original, and so to the one of
1013 // the object built in its place
1014 original.emplace(Scaled_Dist<GT>(1), Weight_Filter<GT>(4));
1015
1016 GT tree;
1017 copy(g, tree);
1018 ASSERT_EQ(tree.get_num_arcs(), 3u);
1019 ASSERT_EQ(tree_total_weight(tree), 4 + 3 + 2);
1020}
1021
1022// ========== TEST 39: Painted_Min_Spanning_Tree with a Given Distance ==========
1023TEST(KruskalTest, PaintedMinSpanningTreeUsesTheDistanceItWasGiven) {
1024
1025 GT g;
1026 Node* n0 = g.insert_node(0);
1027 Node* n1 = g.insert_node(1);
1028 Node* n2 = g.insert_node(2);
1029 Node* n3 = g.insert_node(3);
1030
1031 g.insert_arc(n0, n1, 1);
1032 g.insert_arc(n1, n2, 2);
1033 g.insert_arc(n0, n2, 3);
1034 g.insert_arc(n2, n3, 4);
1035 g.insert_arc(n1, n3, 9);
1036
1038 kruskal(g); // paints the arcs of 1, 2 and 4
1039
1040 // The weight of an arc plus a constant, with no default constructor
1041 struct Plus_Dist
1042 {
1043 using Distance_Type = int;
1044 int extra;
1045 explicit Plus_Dist(int e) noexcept : extra(e) {}
1046 int operator()(Arc *a) const noexcept { return a->get_info() + extra; }
1047 };
1048
1049 // The filter built its distance with Distance(), so it could take neither
1050 // one with state nor one without a default constructor
1052 Painted_Min_Spanning_Tree<GT, Scaled_Dist<GT>> doubled(Scaled_Dist<GT>(2));
1053 Painted_Min_Spanning_Tree<GT, Plus_Dist> plus_one(Plus_Dist(1));
1054 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
1055 {
1056 auto arc = it.get_current_arc_ne();
1057 const bool painted = IS_ARC_VISITED(arc, Aleph::Spanning_Tree);
1058 ASSERT_EQ(plain(arc), painted);
1059 ASSERT_EQ(doubled(arc), painted);
1060 ASSERT_EQ(plus_one(arc), painted);
1061 }
1062 ASSERT_EQ(plain.dist, 1 + 2 + 4);
1063 ASSERT_EQ(doubled.dist, 2 * (1 + 2 + 4));
1064 ASSERT_EQ(plus_one.dist, (1 + 1) + (2 + 1) + (4 + 1));
1065}
1066
1067// ========== TEST 40: Painted_Min_Spanning_Tree with a Distance That Throws ==========
1068TEST(KruskalTest, PaintedMinSpanningTreeLetsWhatTheDistanceThrowsThrough) {
1069
1070 GT g;
1071 Node* n0 = g.insert_node(0);
1072 Node* n1 = g.insert_node(1);
1073 Node* n2 = g.insert_node(2);
1074
1075 Arc* light = g.insert_arc(n0, n1, 1);
1076 Arc* heavy = g.insert_arc(n1, n2, 2);
1077 Arc* closing = g.insert_arc(n0, n2, 3);
1078
1080 kruskal(g); // paints the arcs of 1 and 2
1081
1082 // The weight of an arc, which it does not give above a limit
1083 struct Limited_Dist
1084 {
1085 using Distance_Type = int;
1086 int limit;
1087 explicit Limited_Dist(int l) noexcept : limit(l) {}
1088 int operator()(Arc *a) const
1089 {
1090 if (a->get_info() > limit)
1091 throw std::domain_error("weight above the limit");
1092 return a->get_info();
1093 }
1094 };
1095
1096 // operator() was noexcept, so what the distance threw ended the program
1098 ASSERT_TRUE(filter(light));
1099 ASSERT_THROW(filter(heavy), std::domain_error);
1100 ASSERT_FALSE(filter(closing)); // not painted: its weight is not asked for
1101 ASSERT_EQ(filter.dist, 1);
1102}
1103
1104namespace {
1105
1106template <class G>
1107struct KruskalOnEveryGraph : public ::testing::Test {};
1108
1109using Graph_Kinds =
1110 ::testing::Types<GT, List_SGraph<Graph_Snode<int>, Graph_Sarc<int>>, AGT>;
1111
1112// A square of heavy arcs, inserted first, with its diagonals and a
1113// parallel arc of weight 1
1114template <class G>
1115std::vector<typename G::Node *> heavy_square(G & g)
1116{
1117 std::vector<typename G::Node *> n;
1118 for (int i = 0; i < 4; ++i)
1119 n.push_back(g.insert_node(i));
1120 g.insert_arc(n[0], n[1], 100);
1121 g.insert_arc(n[1], n[2], 100);
1122 g.insert_arc(n[2], n[3], 100);
1123 g.insert_arc(n[3], n[0], 100);
1124 g.insert_arc(n[0], n[2], 1);
1125 g.insert_arc(n[1], n[3], 1);
1126 g.insert_arc(n[0], n[1], 1);
1127 return n;
1128}
1129
1130} // namespace
1131
1132TYPED_TEST_SUITE(KruskalOnEveryGraph, Graph_Kinds);
1133
1134// Kruskal sorted the arcs of g with sort_arcs(), which does not reorder those
1135// of List_SGraph: they are in a set ordered by address, so the tree took the
1136// arcs in that order, and weighed 300 instead of 3
1137TYPED_TEST(KruskalOnEveryGraph, TakesTheLightestArcs)
1138{
1139 TypeParam g;
1140 heavy_square(g);
1141
1142 TypeParam tree;
1144 EXPECT_EQ(tree.get_num_arcs(), 3u);
1145 EXPECT_EQ(tree_total_weight(tree), 3);
1146 EXPECT_EQ(painted_total_weight(g), 3);
1147}
1148
1149// The arcs of g keep their order, and so a second run gives the same tree:
1150// the sort of the arcs of g did not keep the order of equal arcs, so each
1151// run reordered them and could take others
1152TEST(KruskalTest, LeavesTheArcsOfTheGraphInTheirOrder)
1153{
1154 GT g;
1155 std::mt19937 gen(7);
1156 std::vector<Node *> n;
1157 for (int i = 0; i < 60; ++i)
1158 n.push_back(g.insert_node(i));
1159 for (int i = 1; i < 60; ++i)
1160 g.insert_arc(n[i], n[gen() % i], int(gen() % 4)); // many equal weights
1161 for (int k = 0; k < 400; ++k)
1162 g.insert_arc(n[gen() % 60], n[gen() % 60], int(gen() % 4));
1163
1164 std::vector<Arc *> order;
1165 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
1166 order.push_back(it.get_current_arc_ne());
1167
1168 auto tree_arcs = [&g, &order]
1169 {
1170 GT tree;
1172 std::vector<Arc *> arcs, now;
1173 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
1174 {
1175 now.push_back(it.get_current_arc_ne());
1176 if (IS_ARC_VISITED(now.back(), Aleph::Spanning_Tree))
1177 arcs.push_back(now.back());
1178 }
1179 EXPECT_EQ(now, order);
1180 return arcs;
1181 };
1182
1183 const auto first = tree_arcs();
1184 EXPECT_EQ(first.size(), 59u);
1185 EXPECT_EQ(tree_arcs(), first);
1186}
1187
1188// Kruskal sorts the arcs stably, so that of two equal arcs it tries first
1189// the one that comes first in g: its tree is that of a greedy pass over the
1190// arcs of g in their order, sorted stably by weight
1191TEST(KruskalTest, TakesEqualArcsInTheOrderOfTheGraph)
1192{
1193 GT g;
1194 std::mt19937 gen(11);
1195 std::vector<Node *> n;
1196 for (int i = 0; i < 200; ++i)
1197 n.push_back(g.insert_node(i));
1198 for (int k = 0; k < 2000; ++k)
1199 g.insert_arc(n[gen() % 200], n[gen() % 200], int(gen() % 3)); // many equal weights
1200
1201 // The arcs by weight, those of each weight in the order of g
1202 std::vector<Arc *> sorted;
1203 for (int w = 0; w < 3; ++w)
1204 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
1205 if (it.get_current_arc_ne()->get_info() == w)
1206 sorted.push_back(it.get_current_arc_ne());
1207
1208 // The greedy pass, with the blocks of the nodes in a union-find
1209 std::vector<int> parent(200);
1210 for (int i = 0; i < 200; ++i)
1211 parent[i] = i;
1212 auto find = [&parent](int x)
1213 {
1214 while (parent[x] != x)
1215 x = parent[x] = parent[parent[x]];
1216 return x;
1217 };
1218 std::set<Arc *> expected;
1219 for (auto a : sorted)
1220 {
1221 const int s = find(g.get_src_node(a)->get_info());
1222 const int t = find(g.get_tgt_node(a)->get_info());
1223 if (s == t)
1224 continue;
1225 parent[s] = t;
1226 expected.insert(a);
1227 }
1228 ASSERT_EQ(expected.size(), 199u);
1229
1231 std::set<Arc *> painted;
1232 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
1233 if (IS_ARC_VISITED(it.get_current_arc_ne(), Aleph::Spanning_Tree))
1234 painted.insert(it.get_current_arc_ne());
1235 EXPECT_EQ(painted, expected);
1236}
1237
1238// The tree mapped its nodes to those of g with map_nodes(), which chains a
1239// cookie left by an earlier run: after a run whose tree was destroyed, the
1240// nodes of the new tree mapped to freed nodes
1241TEST(KruskalTest, MapsANewTreeAfterTheOldOneIsGone)
1242{
1243 GT g;
1244 std::vector<Node *> n;
1245 for (int i = 0; i < 3; ++i)
1246 n.push_back(g.insert_node(i));
1247 g.insert_arc(n[0], n[1], 1);
1248 g.insert_arc(n[1], n[2], 2);
1249 g.insert_arc(n[0], n[2], 3);
1250
1252 {
1253 GT old_tree;
1254 kruskal(g, old_tree);
1255 }
1256
1257 GT tree;
1258 kruskal(g, tree);
1259 for (auto p : n)
1260 {
1261 auto tp = mapped_node<GT>(p);
1262 ASSERT_NE(tp, nullptr);
1263 EXPECT_EQ(mapped_node<GT>(tp), p);
1264 EXPECT_EQ(tp->get_info(), p->get_info());
1265 }
1266 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
1267 {
1268 auto ta = it.get_current_arc_ne();
1269 auto ga = mapped_arc<GT>(ta);
1270 ASSERT_NE(ga, nullptr);
1271 EXPECT_EQ(mapped_arc<GT>(ga), ta);
1272 EXPECT_EQ(ga->get_info(), ta->get_info());
1273 }
1274}
1275
1276// ========== GoogleTest main ==========
1277int main(int argc, char **argv)
1278{
1279 ::testing::InitGoogleTest(&argc, argv);
1280 return RUN_ALL_TESTS();
1281}
Kruskal's minimum spanning tree algorithm.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int main()
long double w
Definition btreepic.C:153
int num_nodes
Definition btreepic.C:410
virtual Node * insert_node(Node *p)
Inserts the node p, made with new, which the graph takes.
Definition tpl_agraph.H:494
__Graph_Node Node
Definition tpl_agraph.H:286
Arc * insert_arc(Node *src, Node *tgt, void *a)
Definition tpl_agraph.H:565
__Graph_Arc Arc
Definition tpl_agraph.H:287
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
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
bool is_painted() const noexcept
Returns true if the spanning tree has been painted on the graph.
Definition Kruskal.H:134
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
Minimal std::expected-style result type for C++20.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
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
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
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#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.
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
Itor find(const Itor &beg, const Itor &end, const T &value)
Find the first element equal to a value.
Definition ahAlgo.H:230
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Filter of painter arcs with that are set the Spanning_Tree control bit.
Definition tpl_graph.H:5047
Distance::Distance_Type dist
Accumulative distance from the first seen arc until the last seen.
Definition tpl_graph.H:5049
bool operator()(typename GT::Arc *a) const
Definition karger.cc:553
static int * k
AGT::Node ANode
TYPED_TEST_SUITE(KruskalOnEveryGraph, Graph_Kinds)
TYPED_TEST(KruskalOnEveryGraph, TakesTheLightestArcs)
Array-based graph implementation.
Generic graph and digraph implementations.
Simple graph implementation with adjacency lists.
DynList< int > l