Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
test_bellman_ford.cc
Go to the documentation of this file.
1
13#include <gtest/gtest.h>
14
15#include <limits>
16#include <stdexcept>
17
18#include <Bellman_Ford.H>
19#include <tpl_graph.H>
20
21using namespace Aleph;
22
23// Graph type for tests
25using Node = GT::Node;
26using Arc = GT::Arc;
27
28// ========== TEST 1: Simple Graph without Negative Cycles ==========
29TEST(BellmanFordTest, SimpleGraphNoNegativeCycles) {
30
31 GT g;
32 Node* n0 = g.insert_node(0);
33 Node* n1 = g.insert_node(1);
34 Node* n2 = g.insert_node(2);
35 Node* n3 = g.insert_node(3);
36
37 [[maybe_unused]] Arc* a01 = g.insert_arc(n0, n1, 1);
38 [[maybe_unused]] Arc* a02 = g.insert_arc(n0, n2, 4);
39 [[maybe_unused]] Arc* a12 = g.insert_arc(n1, n2, 2);
40 [[maybe_unused]] Arc* a13 = g.insert_arc(n1, n3, 5);
41 [[maybe_unused]] Arc* a23 = g.insert_arc(n2, n3, 1);
42
43 Bellman_Ford<GT> bf(g);
44
45 // Should not detect any negative cycles
46 bool has_negative_cycle = bf.has_negative_cycle(n0);
47 ASSERT_FALSE(has_negative_cycle);
48}
49
50// ========== TEST 2: Graph with Negative Cycle ==========
51TEST(BellmanFordTest, GraphWithNegativeCycle) {
52
53 GT g;
54 Node* n0 = g.insert_node(0);
55 Node* n1 = g.insert_node(1);
56 Node* n2 = g.insert_node(2);
57
58 [[maybe_unused]] Arc* a01 = g.insert_arc(n0, n1, 1);
59 [[maybe_unused]] Arc* a12 = g.insert_arc(n1, n2, -3);
60 [[maybe_unused]] Arc* a20 = g.insert_arc(n2, n0, 1); // Cycle: 0->1->2->0 with total weight -1
61
62 Bellman_Ford<GT> bf(g);
63
64 // Must detect a negative cycle
65 bool has_negative_cycle = bf.has_negative_cycle(n0);
66 ASSERT_TRUE(has_negative_cycle);
67}
68
69// ========== TEST 3: Minimal Paths Spanning Tree ==========
70TEST(BellmanFordTest, SpanningTreePainting) {
71
72 GT g;
73 Node* n0 = g.insert_node(0);
74 Node* n1 = g.insert_node(1);
75 Node* n2 = g.insert_node(2);
76 Node* n3 = g.insert_node(3);
77
78 [[maybe_unused]] Arc* a01 = g.insert_arc(n0, n1, 1);
79 [[maybe_unused]] Arc* a02 = g.insert_arc(n0, n2, 4);
80 [[maybe_unused]] Arc* a12 = g.insert_arc(n1, n2, 2);
81 [[maybe_unused]] Arc* a13 = g.insert_arc(n1, n3, 5);
82 [[maybe_unused]] Arc* a23 = g.insert_arc(n2, n3, 1);
83
84 Bellman_Ford<GT> bf(g);
85 bool negative_cycle = bf.paint_spanning_tree(n0);
86
87 ASSERT_FALSE(negative_cycle);
88
89 // Verify that the tree arcs are marked
90 int painted_arcs = 0;
91 for (Arc_Iterator<GT> it(g); it.has_curr(); it.next()) {
92 if (IS_ARC_VISITED(it.get_curr(), Aleph::Spanning_Tree)) {
93 painted_arcs++;
94 }
95 }
96
97 // The spanning tree must have n-1 arcs
98 ASSERT_EQ(painted_arcs, 3);
99}
100
101// ========== TEST 4: Faster Version of the Algorithm ==========
102TEST(BellmanFordTest, FasterVersion) {
103
104 GT g;
105 Node* n0 = g.insert_node(0);
106 Node* n1 = g.insert_node(1);
107 Node* n2 = g.insert_node(2);
108 Node* n3 = g.insert_node(3);
109 Node* n4 = g.insert_node(4);
110
111 g.insert_arc(n0, n1, 6);
112 g.insert_arc(n0, n2, 7);
113 g.insert_arc(n1, n2, 8);
114 g.insert_arc(n1, n3, 5);
115 g.insert_arc(n1, n4, -4);
116 g.insert_arc(n2, n3, -3);
117 g.insert_arc(n2, n4, 9);
118 g.insert_arc(n3, n1, -2);
119 g.insert_arc(n4, n0, 2);
120 g.insert_arc(n4, n3, 7);
121
122 Bellman_Ford<GT> bf(g);
123 bool negative_cycle = bf.faster_paint_spanning_tree(n0);
124
125 ASSERT_FALSE(negative_cycle);
126}
127
128// ========== TEST 5: Negative Cycle Detection (full version) ==========
129TEST(BellmanFordTest, NegativeCycleDetectionFull) {
130
131 GT g;
132 Node* n0 = g.insert_node(0);
133 Node* n1 = g.insert_node(1);
134 Node* n2 = g.insert_node(2);
135 Node* n3 = g.insert_node(3);
136
137 g.insert_arc(n0, n1, 1);
138 g.insert_arc(n1, n2, -1);
139 g.insert_arc(n2, n3, -1);
140 g.insert_arc(n3, n1, -1); // Negative cycle: 1->2->3->1 with weight -3
141
142 Bellman_Ford<GT> bf(g);
143 Path<GT> cycle = bf.test_negative_cycle(n0);
144
145 // The resulting cycle must not be empty
146 ASSERT_FALSE(cycle.is_empty());
147}
148
149// ========== TEST 6: Search Negative Cycle with Parameters ==========
150TEST(BellmanFordTest, SearchNegativeCycleWithParams) {
151
152 GT g;
153 Node* n0 = g.insert_node(0);
154 Node* n1 = g.insert_node(1);
155 Node* n2 = g.insert_node(2);
156 Node* n3 = g.insert_node(3);
157
158 g.insert_arc(n0, n1, 1);
159 g.insert_arc(n1, n2, -2);
160 g.insert_arc(n2, n3, -2);
161 g.insert_arc(n3, n1, -1); // Negative cycle
162
163 Bellman_Ford<GT> bf(g);
164 auto result = bf.search_negative_cycle(n0, 0.5, 2);
165
166 Path<GT>& cycle = get<0>(result);
167 size_t iterations = get<1>(result);
168
169 ASSERT_FALSE(cycle.is_empty());
170 ASSERT_GT(iterations, 0u);
171}
172
173// ========== TEST 7: Trivial Graph without Negative Cycles ==========
174TEST(BellmanFordTest, TrivialGraphNoNegativeCycles) {
175
176 GT g;
177 Node* n0 = g.insert_node(0);
178
179 Bellman_Ford<GT> bf(g);
180 bool has_negative_cycle = bf.has_negative_cycle(n0);
181
182 ASSERT_FALSE(has_negative_cycle);
183}
184
185// ========== TEST 8: Graph with Zero Weights ==========
186TEST(BellmanFordTest, GraphWithZeroWeights) {
187
188 GT g;
189 Node* n0 = g.insert_node(0);
190 Node* n1 = g.insert_node(1);
191 Node* n2 = g.insert_node(2);
192
193 g.insert_arc(n0, n1, 0);
194 g.insert_arc(n1, n2, 0);
195 g.insert_arc(n2, n0, 0);
196
197 Bellman_Ford<GT> bf(g);
198 bool has_negative_cycle = bf.has_negative_cycle(n0);
199
200 // A cycle with zero total weight is not negative
201 ASSERT_FALSE(has_negative_cycle);
202}
203
204// ========== TEST 9: Disconnected Graph ==========
205TEST(BellmanFordTest, DisconnectedGraph) {
206
207 GT g;
208 Node* n0 = g.insert_node(0);
209 Node* n1 = g.insert_node(1);
210 Node* n2 = g.insert_node(2);
211 Node* n3 = g.insert_node(3);
212
213 // Component 1
214 g.insert_arc(n0, n1, 1);
215
216 // Component 2 (disconnected)
217 g.insert_arc(n2, n3, 2);
218
219 Bellman_Ford<GT> bf(g);
220 bool has_negative_cycle = bf.has_negative_cycle(n0);
221
222 ASSERT_FALSE(has_negative_cycle);
223}
224
225// ========== TEST 10: Negative Weights without Negative Cycle ==========
226TEST(BellmanFordTest, NegativeWeightsNoCycle) {
227
228 GT g;
229 Node* n0 = g.insert_node(0);
230 Node* n1 = g.insert_node(1);
231 Node* n2 = g.insert_node(2);
232 Node* n3 = g.insert_node(3);
233
234 g.insert_arc(n0, n1, -1);
235 g.insert_arc(n1, n2, -2);
236 g.insert_arc(n2, n3, -3);
237 // There is no cycle
238
239 Bellman_Ford<GT> bf(g);
240 bool has_negative_cycle = bf.has_negative_cycle(n0);
241
242 ASSERT_FALSE(has_negative_cycle);
243}
244
245// ========== TEST 11: Large Graph with Multiple Paths ==========
246TEST(BellmanFordTest, LargeGraphNoNegativeCycle) {
247
248 GT g;
249 constexpr int num_nodes = 100;
250 std::vector<Node*> nodes;
251
252 for (int i = 0; i < num_nodes; ++i) {
253 nodes.push_back(g.insert_node(i));
254 }
255
256 // Create a long chain
257 for (int i = 0; i < num_nodes - 1; ++i) {
258 g.insert_arc(nodes[i], nodes[i+1], 1);
259 }
260
261 // Add some extra arcs
262 for (int i = 0; i < num_nodes - 5; i += 5) {
263 g.insert_arc(nodes[i], nodes[i+5], 2);
264 }
265
266 Bellman_Ford<GT> bf(g);
267 bool has_negative_cycle = bf.has_negative_cycle(nodes[0]);
268
269 ASSERT_FALSE(has_negative_cycle);
270}
271
272// ========== TEST 12: Complex Negative Cycle ==========
273TEST(BellmanFordTest, ComplexNegativeCycle) {
274
275 GT g;
276 Node* n0 = g.insert_node(0);
277 Node* n1 = g.insert_node(1);
278 Node* n2 = g.insert_node(2);
279 Node* n3 = g.insert_node(3);
280 Node* n4 = g.insert_node(4);
281
282 g.insert_arc(n0, n1, 1);
283 g.insert_arc(n1, n2, 3);
284 g.insert_arc(n2, n3, -2);
285 g.insert_arc(n3, n4, -1);
286 g.insert_arc(n4, n2, -3); // Negative cycle: 2->3->4->2 with weight -6
287
288 Bellman_Ford<GT> bf(g);
289 Path<GT> cycle = bf.test_negative_cycle(n0);
290
291 ASSERT_FALSE(cycle.is_empty());
292}
293
294// ========== TEST 13: test_negative_cycle with Output Parameter ==========
295TEST(BellmanFordTest, NegativeCycleWithOutputParameter) {
296
297 GT g;
298 Node* n0 = g.insert_node(0);
299 Node* n1 = g.insert_node(1);
300 Node* n2 = g.insert_node(2);
301
302 g.insert_arc(n0, n1, 1);
303 g.insert_arc(n1, n2, -3);
304 g.insert_arc(n2, n0, 1);
305
306 Bellman_Ford<GT> bf(g);
307 Path<GT> cycle;
308 bool has_cycle = bf.test_negative_cycle(n0, cycle);
309
310 ASSERT_TRUE(has_cycle);
311 ASSERT_FALSE(cycle.is_empty());
312}
313
314// ========== TEST 14: search_negative_cycle without Start Node ==========
315TEST(BellmanFordTest, SearchNegativeCycleNoStartNode) {
316
317 GT g;
318 Node* n0 = g.insert_node(0);
319 Node* n1 = g.insert_node(1);
320 Node* n2 = g.insert_node(2);
321 Node* n3 = g.insert_node(3);
322
323 // Component without negative cycle
324 g.insert_arc(n0, n1, 1);
325
326 // Component with negative cycle
327 g.insert_arc(n1, n2, 1);
328 g.insert_arc(n2, n3, -2);
329 g.insert_arc(n3, n1, -1);
330
331 Bellman_Ford<GT> bf(g);
332 Path<GT> cycle = bf.search_negative_cycle();
333
334 ASSERT_FALSE(cycle.is_empty());
335}
336
337// ========== TEST 15: Bellman_Ford_Negative_Cycle Functor ==========
338TEST(BellmanFordTest, NegativeCycleFunctor) {
339
340 GT g;
341 Node* n0 = g.insert_node(0);
342 Node* n1 = g.insert_node(1);
343 Node* n2 = g.insert_node(2);
344
345 g.insert_arc(n0, n1, 1);
346 g.insert_arc(n1, n2, -3);
347 g.insert_arc(n2, n0, 1);
348
350 Path<GT> cycle;
351 bool has_cycle = detector(g, cycle);
352
353 ASSERT_TRUE(has_cycle);
354 ASSERT_FALSE(cycle.is_empty());
355}
356
357// ========== TEST 16: Graph with Negative Self-loop ==========
358TEST(BellmanFordTest, NegativeSelfLoop) {
359
360 GT g;
361 Node* n0 = g.insert_node(0);
362 Node* n1 = g.insert_node(1);
363
364 g.insert_arc(n0, n1, 1);
365 g.insert_arc(n1, n1, -1); // Negative self-loop
366
367 Bellman_Ford<GT> bf(g);
368 bool has_negative_cycle = bf.has_negative_cycle(n0);
369
370 ASSERT_TRUE(has_negative_cycle);
371}
372
373// ========== TEST 17: All Negative Weights without Cycle ==========
374TEST(BellmanFordTest, AllNegativeWeightsNoCycle) {
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 g.insert_arc(n0, n1, -1);
383 g.insert_arc(n1, n2, -2);
384 g.insert_arc(n2, n3, -3);
385 g.insert_arc(n0, n2, -4);
386
387 Bellman_Ford<GT> bf(g);
388 bool has_negative_cycle = bf.has_negative_cycle(n0);
389
390 ASSERT_FALSE(has_negative_cycle);
391}
392
393// ========== TEST 18: Nullptr Validation ==========
394TEST(BellmanFordTest, NullptrValidation) {
395
396 GT g;
397 Node* n0 = g.insert_node(0);
398 Node* n1 = g.insert_node(1);
399 g.insert_arc(n0, n1, 1);
400
401 Bellman_Ford<GT> bf(g);
402
403 bool caught_exception = false;
404 try {
405 bf.paint_spanning_tree(nullptr);
406 } catch (const std::domain_error&) {
407 caught_exception = true;
408 }
409 ASSERT_TRUE(caught_exception);
410
411 caught_exception = false;
412 try {
413 bf.faster_paint_spanning_tree(nullptr);
414 } catch (const std::domain_error&) {
415 caught_exception = true;
416 }
417 ASSERT_TRUE(caught_exception);
418
419 caught_exception = false;
420 try {
421 bf.has_negative_cycle(nullptr);
422 } catch (const std::domain_error&) {
423 caught_exception = true;
424 }
425 ASSERT_TRUE(caught_exception);
426}
427
428// ========== TEST 19: Completely Empty Graph ==========
429TEST(BellmanFordTest, CompletelyEmptyGraph) {
430
431 GT g;
432 // No nodes inserted
433
434 Bellman_Ford<GT> bf(g);
435
436 // has_negative_cycle() without parameters must work
437 bool has_cycle = bf.has_negative_cycle();
438 ASSERT_FALSE(has_cycle);
439}
440
441// ========== TEST 20: Build Tree from Spanning Tree ==========
442TEST(BellmanFordTest, BuildTreeFromSpanningTree) {
443
444 GT g;
445 Node* n0 = g.insert_node(0);
446 Node* n1 = g.insert_node(1);
447 Node* n2 = g.insert_node(2);
448 Node* n3 = g.insert_node(3);
449
450 g.insert_arc(n0, n1, 1);
451 g.insert_arc(n0, n2, 4);
452 g.insert_arc(n1, n2, 2);
453 g.insert_arc(n1, n3, 5);
454 g.insert_arc(n2, n3, 1);
455
456 Bellman_Ford<GT> bf(g);
457 bf.paint_spanning_tree(n0);
458
459 GT tree;
460 bf.build_tree(tree, false);
461
462 // The tree must have the same number of nodes
463 ASSERT_EQ(tree.get_num_nodes(), g.get_num_nodes());
464
465 // The tree must have n-1 arcs
466 ASSERT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
467}
468
469// ========== TEST 21: Extract Min Spanning Tree ==========
470TEST(BellmanFordTest, ExtractMinSpanningTree) {
471
472 GT g;
473 Node* n0 = g.insert_node(0);
474 Node* n1 = g.insert_node(1);
475 Node* n2 = g.insert_node(2);
476 Node* n3 = g.insert_node(3);
477
478 g.insert_arc(n0, n1, 1);
479 g.insert_arc(n0, n2, 4);
480 g.insert_arc(n1, n2, 2);
481 g.insert_arc(n1, n3, 5);
482 g.insert_arc(n2, n3, 1);
483
484 Bellman_Ford<GT> bf(g);
485 bf.paint_spanning_tree(n0);
486
488
489 // There must be n-1 arcs (some entries may be nullptr)
490 int non_null_arcs = 0;
491 for (size_t i = 0; i < tree_arcs.size(); ++i) {
492 if (tree_arcs(i) != nullptr) {
493 non_null_arcs++;
494 }
495 }
496
497 ASSERT_EQ(non_null_arcs, 3); // n-1 for 4 nodes
498}
499
500// ========== TEST 22: Compute Nodes Weights (Johnson) ==========
501TEST(BellmanFordTest, ComputeNodesWeightsJohnson) {
502
503 GT g;
504 Node* n0 = g.insert_node(0);
505 Node* n1 = g.insert_node(1);
506 Node* n2 = g.insert_node(2);
507
508 g.insert_arc(n0, n1, 1);
509 g.insert_arc(n1, n2, 2);
510 g.insert_arc(n2, n0, 3);
511
512 Bellman_Ford<GT> bf(g);
513
514 auto weights = bf.compute_nodes_weights();
515
516 // There must be one weight for each node
517 ASSERT_EQ(weights.size(), g.get_num_nodes());
518}
519
520// ========== TEST 23: Compute Nodes Weights with Negative Cycle ==========
521TEST(BellmanFordTest, ComputeNodesWeightsWithNegativeCycle) {
522
523 GT g;
524 Node* n0 = g.insert_node(0);
525 Node* n1 = g.insert_node(1);
526 Node* n2 = g.insert_node(2);
527
528 g.insert_arc(n0, n1, 1);
529 g.insert_arc(n1, n2, -3);
530 g.insert_arc(n2, n0, 1); // Negative cycle
531
532 Bellman_Ford<GT> bf(g);
533
534 bool caught_exception = false;
535 try {
537 } catch (const std::domain_error&) {
538 caught_exception = true;
539 }
540
541 ASSERT_TRUE(caught_exception);
542}
543
544// ========== TEST 24: has_negative_cycle Without Start Node ==========
545TEST(BellmanFordTest, HasNegativeCycleNoStartNode) {
546
547 GT g;
548 Node* n0 = g.insert_node(0);
549 Node* n1 = g.insert_node(1);
550 Node* n2 = g.insert_node(2);
551
552 g.insert_arc(n0, n1, 1);
553 g.insert_arc(n1, n2, -3);
554 g.insert_arc(n2, n0, 1); // Negative cycle
555
556 Bellman_Ford<GT> bf(g);
557 bool has_cycle = bf.has_negative_cycle();
558
559 ASSERT_TRUE(has_cycle);
560}
561
562// ========== TEST 25: test_negative_cycle Without Parameters ==========
563TEST(BellmanFordTest, NegativeCycleNoParams) {
564
565 GT g;
566 Node* n0 = g.insert_node(0);
567 Node* n1 = g.insert_node(1);
568 Node* n2 = g.insert_node(2);
569
570 g.insert_arc(n0, n1, 1);
571 g.insert_arc(n1, n2, -3);
572 g.insert_arc(n2, n0, 1);
573
574 Bellman_Ford<GT> bf(g);
575 Path<GT> cycle;
576 const bool has_cycle = bf.test_negative_cycle(cycle);
577
578 ASSERT_TRUE(has_cycle);
579 ASSERT_FALSE(cycle.is_empty());
580}
581
582// ========== TEST 26: get_min_path - CRITICAL MISSING TEST ==========
583TEST(BellmanFordTest, GetMinPath) {
584
585 GT g;
586 Node* n0 = g.insert_node(0);
587 Node* n1 = g.insert_node(1);
588 Node* n2 = g.insert_node(2);
589 Node* n3 = g.insert_node(3);
590
591 g.insert_arc(n0, n1, 1);
592 g.insert_arc(n0, n2, 4);
593 g.insert_arc(n1, n2, 2);
594 g.insert_arc(n1, n3, 5);
595 g.insert_arc(n2, n3, 1);
596
597 Bellman_Ford<GT> bf(g);
598 bf.paint_spanning_tree(n0);
599
600 // Test path to n3 (should be: n0->n1->n2->n3 with cost 4)
601 Path<GT> path(g);
602 int distance = bf.get_min_path(n3, path);
603
604 ASSERT_EQ(distance, 4);
605 ASSERT_FALSE(path.is_empty());
606
607 // Verify path contains correct nodes
608 size_t path_length = 0;
609 for (typename Path<GT>::Iterator it(path); it.has_current_node(); it.next_ne())
610 path_length++;
611
612 ASSERT_EQ(path_length, 4); // n0, n1, n2, n3
613}
614
615// ========== TEST 27: get_min_path to All Nodes ==========
616TEST(BellmanFordTest, GetMinPathToAllNodes) {
617
618 GT g;
619 Node* n0 = g.insert_node(0);
620 Node* n1 = g.insert_node(1);
621 Node* n2 = g.insert_node(2);
622
623 g.insert_arc(n0, n1, 5);
624 g.insert_arc(n0, n2, 10);
625 g.insert_arc(n1, n2, 3);
626
627 Bellman_Ford<GT> bf(g);
628 bf.paint_spanning_tree(n0);
629
630 // Path to n1
631 Path<GT> path1(g);
632 int dist1 = bf.get_min_path(n1, path1);
633 ASSERT_EQ(dist1, 5);
634
635 // Path to n2 (via n1: 5+3=8, better than direct 10)
636 Path<GT> path2(g);
637 int dist2 = bf.get_min_path(n2, path2);
638 ASSERT_EQ(dist2, 8);
639}
640
641// ========== TEST 28: extract_min_spanning_tree Validation ==========
642TEST(BellmanFordTest, ExtractMinSpanningTreeValidation) {
643
644 GT g;
645 Node* n0 = g.insert_node(0);
646 Node* n1 = g.insert_node(1);
647 Node* n2 = g.insert_node(2);
648
649 [[maybe_unused]] Arc* a01 = g.insert_arc(n0, n1, 1);
650 [[maybe_unused]] Arc* a02 = g.insert_arc(n0, n2, 5);
651 [[maybe_unused]] Arc* a12 = g.insert_arc(n1, n2, 2);
652
653 Bellman_Ford<GT> bf(g);
654 bf.paint_spanning_tree(n0);
655
657
658 // Verify arc count (should be n-1 = 2 arcs)
659 size_t valid_arcs = 0;
660 for (size_t i = 0; i < arcs.size(); ++i)
661 if (arcs(i) != nullptr)
662 valid_arcs++;
663
664 ASSERT_EQ(valid_arcs, 2);
665
666 // Verify arcs are actually from the tree (a01 and a12, not a02)
667 bool found_a01 = false;
668 bool found_a12 = false;
669 for (size_t i = 0; i < arcs.size(); ++i) {
670 if (arcs(i) == a01) found_a01 = true;
671 if (arcs(i) == a12) found_a12 = true;
672 }
673
674 ASSERT_TRUE(found_a01);
675 ASSERT_TRUE(found_a12);
676}
677
678// ========== TEST 29: build_tree with with_map=true ==========
679TEST(BellmanFordTest, BuildTreeWithMapping) {
680
681 GT g;
682 Node* n0 = g.insert_node(0);
683 Node* n1 = g.insert_node(1);
684 Node* n2 = g.insert_node(2);
685
686 g.insert_arc(n0, n1, 1);
687 g.insert_arc(n0, n2, 5);
688 g.insert_arc(n1, n2, 2);
689
690 Bellman_Ford<GT> bf(g);
691 bf.paint_spanning_tree(n0);
692
693 GT tree;
694 bf.build_tree(tree, true); // with_map = true
695
696 // Verify tree has same number of nodes
697 ASSERT_EQ(tree.get_num_nodes(), 3);
698
699 // Verify tree has n-1 arcs
700 ASSERT_EQ(tree.get_num_arcs(), 2);
701
702 // Verify nodes have correct info
703 bool found_0 = false, found_1 = false, found_2 = false;
704 for (typename GT::Node_Iterator it(tree); it.has_curr(); it.next()) {
705 auto node = it.get_curr();
706 int info = node->get_info();
707 if (info == 0) found_0 = true;
708 if (info == 1) found_1 = true;
709 if (info == 2) found_2 = true;
710 }
711
712 ASSERT_TRUE(found_0);
713 ASSERT_TRUE(found_1);
714 ASSERT_TRUE(found_2);
715}
716
717// ========== TEST 30: compute_nodes_weights Values Validation ==========
718TEST(BellmanFordTest, ComputeNodesWeightsValues) {
719
720 GT g;
721 Node* n0 = g.insert_node(0);
722 Node* n1 = g.insert_node(1);
723 Node* n2 = g.insert_node(2);
724
725 g.insert_arc(n0, n1, 5);
726 g.insert_arc(n1, n2, 3);
727 g.insert_arc(n0, n2, 10);
728
729 Bellman_Ford<GT> bf(g);
730 auto weights = bf.compute_nodes_weights();
731
732 ASSERT_EQ(weights.size(), 3);
733
734 // All weights should be 0 (Johnson's algorithm uses these to reweight)
735 // The actual values depend on the dummy node distances
736 for (auto it = weights.get_it(); it.has_curr(); it.next()) {
737 auto & pair = it.get_curr();
738 // Weight should be >= 0 after Johnson preprocessing
739 ASSERT_GE(pair.second, std::numeric_limits<int>::min());
740 }
741}
742
743// ========== TEST 31: Bellman_Ford_Negative_Cycle Functor (variant 1) ==========
744TEST(BellmanFordTest, NegativeCycleFunctorVariant1) {
745
746 GT g;
747 Node* n0 = g.insert_node(0);
748 Node* n1 = g.insert_node(1);
749 Node* n2 = g.insert_node(2);
750
751 g.insert_arc(n0, n1, 1);
752 g.insert_arc(n1, n2, -3);
753 g.insert_arc(n2, n0, 1); // Negative cycle
754
755 Path<GT> path(g);
757
758 bool has_cycle = detector(g, path);
759
760 ASSERT_TRUE(has_cycle);
761 ASSERT_FALSE(path.is_empty());
762}
763
764// ========== TEST 32: Bellman_Ford_Negative_Cycle Functor (variant 2 with start node) ==========
765TEST(BellmanFordTest, NegativeCycleFunctorWithStartNode) {
766
767 GT g;
768 Node* n0 = g.insert_node(0);
769 Node* n1 = g.insert_node(1);
770 Node* n2 = g.insert_node(2);
771
772 g.insert_arc(n0, n1, 1);
773 g.insert_arc(n1, n2, -3);
774 g.insert_arc(n2, n0, 1);
775
776 Path<GT> path(g);
778
779 bool has_cycle = detector(g, n0, path);
780
781 ASSERT_TRUE(has_cycle);
782 ASSERT_FALSE(path.is_empty());
783}
784
785// ========== TEST 33: search_negative_cycle with different it_factor ==========
786TEST(BellmanFordTest, SearchNegativeCycleWithDifferentItFactors) {
787
788 GT g;
789 Node* n0 = g.insert_node(0);
790 Node* n1 = g.insert_node(1);
791 Node* n2 = g.insert_node(2);
792
793 g.insert_arc(n0, n1, 1);
794 g.insert_arc(n1, n2, -3);
795 g.insert_arc(n2, n0, 1);
796
797 Bellman_Ford<GT> bf(g);
798
799 // Test with it_factor = 0.1
800 auto [path1, iter1] = bf.search_negative_cycle(n0, 0.1, 1);
801 ASSERT_FALSE(path1.is_empty());
802 ASSERT_GT(iter1, 0u);
803
804 // Test with it_factor = 0.9
805 auto [path2, iter2] = bf.search_negative_cycle(n0, 0.9, 1);
806 ASSERT_FALSE(path2.is_empty());
807 ASSERT_GT(iter2, 0u);
808}
809
810// ========== TEST 34: Empty Graph Edge Case ==========
811TEST(BellmanFordTest, EmptyGraphEdgeCase) {
812
813 GT g;
814 Bellman_Ford<GT> bf(g);
815
816 bool has_cycle = bf.has_negative_cycle();
817 ASSERT_FALSE(has_cycle);
818}
819
820// ========== TEST 35: Large Graph Performance Test ==========
821TEST(BellmanFordTest, LargeGraphPerformance) {
822
823 GT g;
824 const size_t N = 100;
825
826 // Create nodes
827 std::vector<Node*> nodes;
828 for (size_t i = 0; i < N; ++i)
829 nodes.push_back(g.insert_node(i));
830
831 // Create chain of arcs
832 for (size_t i = 0; i < N - 1; ++i)
833 g.insert_arc(nodes[i], nodes[i + 1], 1);
834
835 Bellman_Ford<GT> bf(g);
836 bool negative_cycle = bf.paint_spanning_tree(nodes[0]);
837
838 ASSERT_FALSE(negative_cycle);
839
840 // Verify path to last node
841 Path<GT> path(g);
842 int distance = bf.get_min_path(nodes[N - 1], path);
843
844 ASSERT_EQ(distance, N - 1);
845}
846
847// ========== TEST 36: State Getters ==========
848TEST(BellmanFordTest, StateGetters) {
849
850 GT g;
851 Node* n0 = g.insert_node(0);
852 Node* n1 = g.insert_node(1);
853 g.insert_arc(n0, n1, 1);
854
855 Bellman_Ford<GT> bf(g);
856
857 // Before painting
858 ASSERT_FALSE(bf.is_painted());
859 ASSERT_FALSE(bf.has_computation());
860 ASSERT_EQ(bf.get_start_node(), nullptr);
861 ASSERT_EQ(&bf.get_graph(), &g);
862
863 // After painting
864 bf.paint_spanning_tree(n0);
865 ASSERT_TRUE(bf.is_painted());
866 ASSERT_TRUE(bf.has_computation());
867 ASSERT_EQ(bf.get_start_node(), n0);
868}
869
870// ========== TEST 37: get_min_path without Painting ==========
871TEST(BellmanFordTest, GetMinPathWithoutPainting) {
872
873 GT g;
874 Node* n0 = g.insert_node(0);
875 Node* n1 = g.insert_node(1);
876 g.insert_arc(n0, n1, 1);
877
878 Bellman_Ford<GT> bf(g);
879
880 Path<GT> path(g);
881 bool caught = false;
882 try {
883 bf.get_min_path(n1, path);
884 } catch (const std::domain_error&) {
885 caught = true;
886 }
887 ASSERT_TRUE(caught);
888}
889
890// ========== TEST 38: Negative Cycle Path Validity ==========
891TEST(BellmanFordTest, NegativeCyclePathValidity) {
892
893 GT g;
894 Node* n0 = g.insert_node(0);
895 Node* n1 = g.insert_node(1);
896 Node* n2 = g.insert_node(2);
897
898 g.insert_arc(n0, n1, 1);
899 g.insert_arc(n1, n2, -2);
900 g.insert_arc(n2, n0, -1); // Total: -2 (negative cycle)
901
902 Bellman_Ford<GT> bf(g);
903 Path<GT> cycle = bf.test_negative_cycle(n0);
904
905 ASSERT_FALSE(cycle.is_empty());
906
907 // Verify cycle properties:
908 // 1. Has at least 2 nodes (for a cycle)
909 size_t cycle_length = 0;
910 for (typename Path<GT>::Iterator it(cycle); it.has_current_node(); it.next_ne())
911 cycle_length++;
912
913 ASSERT_GE(cycle_length, 2u);
914}
915
916// ========== TEST 39: Single Node with Self-loop (Positive) ==========
917TEST(BellmanFordTest, SingleNodePositiveSelfLoop) {
918
919 GT g;
920 Node* n0 = g.insert_node(0);
921 g.insert_arc(n0, n0, 1); // Positive self-loop
922
923 Bellman_Ford<GT> bf(g);
924 bool has_neg_cycle = bf.has_negative_cycle(n0);
925
926 ASSERT_FALSE(has_neg_cycle);
927}
928
929// ========== Cycle Closed Only by the Checking Pass ==========
930TEST(BellmanFordTest, CycleClosedByTheCheckingPassIsReturned) {
931 // Final independent review of the arbitrage branch, mutation M45: the
932 // checking pass must record the arc it relaxes, which closes the cycle in
933 // the predecessor graph. With two nodes, the single regular pass relaxes
934 // only 0 -> 1, because the arc out of 1 comes first.
935 for (const bool loop : {false, true})
936 {
937 GT g;
938 Node* n0 = g.insert_node(0);
939 Node* n1 = g.insert_node(1);
940 if (loop)
941 {
942 g.insert_arc(n1, n1, -4); // negative loop at 1
943 g.insert_arc(n0, n1, 4);
944 }
945 else
946 {
947 g.insert_arc(n1, n0, -2); // 2-cycle of total -4
948 g.insert_arc(n0, n1, -2);
949 }
950
951 Bellman_Ford<GT> bf(g);
952 Path<GT> cycle = bf.test_negative_cycle(n0);
953 ASSERT_FALSE(cycle.is_empty()) << (loop ? "loop" : "2-cycle");
954 EXPECT_TRUE(cycle.is_cycle());
955 int total = 0;
956 cycle.for_each_arc([&total](Arc* a) { total += a->get_info(); });
957 EXPECT_LT(total, 0);
958 }
959}
960
961// ========== TEST 40: Faster Version with Negative Cycle ==========
962TEST(BellmanFordTest, FasterVersionWithNegativeCycle) {
963
964 GT g;
965 Node* n0 = g.insert_node(0);
966 Node* n1 = g.insert_node(1);
967 Node* n2 = g.insert_node(2);
968
969 g.insert_arc(n0, n1, 1);
970 g.insert_arc(n1, n2, -3);
971 g.insert_arc(n2, n0, 1);
972
973 Bellman_Ford<GT> bf(g);
974 bool has_neg_cycle = bf.faster_paint_spanning_tree(n0);
975
976 ASSERT_TRUE(has_neg_cycle);
977}
978
979// ========== TEST 41: Search Negative Cycle (Double Overload) ==========
980TEST(BellmanFordTest, SearchNegativeCycleDoubleOverload) {
981
982 GT g;
983 Node* n0 = g.insert_node(0);
984 Node* n1 = g.insert_node(1);
985 Node* n2 = g.insert_node(2);
986
987 g.insert_arc(n0, n1, 1);
988 g.insert_arc(n1, n2, -3);
989 g.insert_arc(n2, n0, 1);
990
991 Bellman_Ford<GT> bf(g);
992
993 // search_negative_cycle(start, it_factor, step)
994 auto [path, iter] = bf.search_negative_cycle(n0, 0.5, 1);
995
996 ASSERT_FALSE(path.is_empty());
997}
998
999// ========== TEST 42: search_negative_cycle (No Params Overload) ==========
1000TEST(BellmanFordTest, SearchNegativeCycleNoParamsVariant) {
1001
1002 GT g;
1003 [[maybe_unused]] Node* n0 = g.insert_node(0);
1004 Node* n1 = g.insert_node(1);
1005 Node* n2 = g.insert_node(2);
1006
1007 // Disconnected negative cycle
1008 g.insert_arc(n1, n2, -2);
1009 g.insert_arc(n2, n1, -1);
1010
1011 Bellman_Ford<GT> bf(g);
1012
1013 // Using the overload without start node (uses dummy node)
1014 Path<GT> path = bf.search_negative_cycle();
1015
1016 ASSERT_FALSE(path.is_empty());
1017}
1018
1019// ========== TEST 43: Build Tree Without Prior Painting ==========
1020TEST(BellmanFordTest, BuildTreeWithoutPriorPainting) {
1021
1022 GT g;
1023 Node* n0 = g.insert_node(0);
1024 Node* n1 = g.insert_node(1);
1025 g.insert_arc(n0, n1, 1);
1026
1027 Bellman_Ford<GT> bf(g);
1028
1029 GT tree;
1030 bool caught = false;
1031 try {
1032 bf.build_tree(tree, true); // with_map = true requires painting
1033 } catch (const std::domain_error&) {
1034 caught = true;
1035 }
1036 ASSERT_TRUE(caught);
1037}
1038
1039// ========== TEST 44: Multiple Calls to paint_spanning_tree ==========
1040TEST(BellmanFordTest, MultiplePaintCalls) {
1041
1042 GT g;
1043 Node* n0 = g.insert_node(0);
1044 Node* n1 = g.insert_node(1);
1045 Node* n2 = g.insert_node(2);
1046
1047 g.insert_arc(n0, n1, 1);
1048 g.insert_arc(n0, n2, 10);
1049 g.insert_arc(n1, n2, 2);
1050
1051 Bellman_Ford<GT> bf(g);
1052
1053 // First call
1054 bf.paint_spanning_tree(n0);
1055 ASSERT_TRUE(bf.is_painted());
1056 ASSERT_EQ(bf.get_start_node(), n0);
1057
1058 Path<GT> path1(g);
1059 int dist1 = bf.get_min_path(n2, path1);
1060 ASSERT_EQ(dist1, 3);
1061
1062 // Can we paint again from a different node? (fresh graph state)
1063 GT g2;
1064 Node* m0 = g2.insert_node(0);
1065 Node* m1 = g2.insert_node(1);
1066 g2.insert_arc(m0, m1, 5);
1067
1068 Bellman_Ford<GT> bf2(g2);
1069 bf2.paint_spanning_tree(m0);
1070 ASSERT_TRUE(bf2.is_painted());
1071
1072 Path<GT> path2(g2);
1073 int dist2 = bf2.get_min_path(m1, path2);
1074 ASSERT_EQ(dist2, 5);
1075}
1076
1077// ========== TEST 45: Functor With Different Signatures ==========
1078TEST(BellmanFordTest, FunctorDifferentSignatures) {
1079
1080 GT g;
1081 Node* n0 = g.insert_node(0);
1082 Node* n1 = g.insert_node(1);
1083 Node* n2 = g.insert_node(2);
1084
1085 g.insert_arc(n0, n1, 1);
1086 g.insert_arc(n1, n2, -3);
1087 g.insert_arc(n2, n0, 1);
1088
1090
1091 // Signature: (g, s, d, sa) -> Path
1092 Dft_Dist<GT> dist;
1094 Path<GT> path1 = detector(g, n0, dist, sa);
1095 ASSERT_FALSE(path1.is_empty());
1096
1097 // Signature: (g, d, sa) -> Path
1098 Path<GT> path2 = detector(g, dist, sa);
1099 ASSERT_FALSE(path2.is_empty());
1100
1101 // Signature: (g) -> Path with default args
1102 Path<GT> path3 = detector(g);
1103 ASSERT_FALSE(path3.is_empty());
1104}
1105
1106// ========== TEST 46: Strongly Connected Component with Negative Cycle ==========
1107TEST(BellmanFordTest, StronglyConnectedWithNegativeCycle) {
1108
1109 GT g;
1110 Node* n0 = g.insert_node(0);
1111 Node* n1 = g.insert_node(1);
1112 Node* n2 = g.insert_node(2);
1113 Node* n3 = g.insert_node(3);
1114
1115 // Connect all nodes strongly
1116 g.insert_arc(n0, n1, 1);
1117 g.insert_arc(n1, n2, 1);
1118 g.insert_arc(n2, n3, 1);
1119 g.insert_arc(n3, n0, 1);
1120
1121 // Add negative cycle within
1122 g.insert_arc(n1, n3, -5);
1123 g.insert_arc(n3, n1, 1);
1124
1125 Bellman_Ford<GT> bf(g);
1126 bool has_neg = bf.has_negative_cycle(n0);
1127
1128 ASSERT_TRUE(has_neg);
1129}
1130
1131// ========== TEST 47: Very Long Chain Performance ==========
1132TEST(BellmanFordTest, VeryLongChainPerformance) {
1133
1134 GT g;
1135 const size_t N = 500;
1136
1137 std::vector<Node*> nodes;
1138 for (size_t i = 0; i < N; ++i)
1139 nodes.push_back(g.insert_node(static_cast<int>(i)));
1140
1141 for (size_t i = 0; i < N - 1; ++i)
1142 g.insert_arc(nodes[i], nodes[i + 1], 1);
1143
1144 Bellman_Ford<GT> bf(g);
1145 bool neg_cycle = bf.paint_spanning_tree(nodes[0]);
1146
1147 ASSERT_FALSE(neg_cycle);
1148
1149 Path<GT> path(g);
1150 int dist = bf.get_min_path(nodes[N - 1], path);
1151
1152 ASSERT_EQ(dist, static_cast<int>(N - 1));
1153}
1154
1155// ========== TEST 48: Bidirectional Edges ==========
1156TEST(BellmanFordTest, BidirectionalEdges) {
1157
1158 GT g;
1159 Node* n0 = g.insert_node(0);
1160 Node* n1 = g.insert_node(1);
1161
1162 g.insert_arc(n0, n1, 3);
1163 g.insert_arc(n1, n0, 5);
1164
1165 Bellman_Ford<GT> bf(g);
1166 bool neg_cycle = bf.paint_spanning_tree(n0);
1167
1168 ASSERT_FALSE(neg_cycle);
1169
1170 Path<GT> path(g);
1171 int dist = bf.get_min_path(n1, path);
1172
1173 ASSERT_EQ(dist, 3);
1174}
1175
1176// ========== TEST 49: Unreachable Node ==========
1177TEST(BellmanFordTest, UnreachableNode) {
1178
1179 GT g;
1180 Node* n0 = g.insert_node(0);
1181 Node* n1 = g.insert_node(1);
1182 Node* n2 = g.insert_node(2); // Not connected
1183
1184 g.insert_arc(n0, n1, 1);
1185
1186 Bellman_Ford<GT> bf(g);
1187 bf.paint_spanning_tree(n0);
1188
1189 // Node n2 is unreachable - get_min_path should throw
1190 Path<GT> path(g);
1191 bool caught = false;
1192 try {
1193 bf.get_min_path(n2, path);
1194 } catch (const std::domain_error&) {
1195 caught = true;
1196 }
1197
1198 ASSERT_TRUE(caught);
1199}
1200
1201// ========== TEST 50: Dense Graph ==========
1202TEST(BellmanFordTest, DenseGraph) {
1203
1204 GT g;
1205 const size_t N = 20;
1206
1207 std::vector<Node*> nodes;
1208 for (size_t i = 0; i < N; ++i)
1209 nodes.push_back(g.insert_node(static_cast<int>(i)));
1210
1211 // Create dense graph (almost complete)
1212 for (size_t i = 0; i < N; ++i)
1213 for (size_t j = 0; j < N; ++j)
1214 if (i != j)
1215 g.insert_arc(nodes[i], nodes[j], static_cast<int>(i + j));
1216
1217 Bellman_Ford<GT> bf(g);
1218 bool neg_cycle = bf.paint_spanning_tree(nodes[0]);
1219
1220 ASSERT_FALSE(neg_cycle);
1221}
1222
1223// ========== TEST 51: get_distance Method ==========
1224TEST(BellmanFordTest, GetDistance) {
1225
1226 GT g;
1227 Node* n0 = g.insert_node(0);
1228 Node* n1 = g.insert_node(1);
1229 Node* n2 = g.insert_node(2);
1230 Node* n3 = g.insert_node(3);
1231
1232 g.insert_arc(n0, n1, 1);
1233 g.insert_arc(n1, n2, 2);
1234 g.insert_arc(n2, n3, 3);
1235
1236 Bellman_Ford<GT> bf(g);
1237 bf.paint_spanning_tree(n0);
1238
1239 // Distance to n3 should be 1+2+3 = 6
1240 int dist_n3 = bf.get_distance(n3);
1241 ASSERT_EQ(dist_n3, 6);
1242
1243 // Distance to n1 should be 1
1244 int dist_n1 = bf.get_distance(n1);
1245 ASSERT_EQ(dist_n1, 1);
1246
1247 // Distance to start node should be 0
1248 int dist_n0 = bf.get_distance(n0);
1249 ASSERT_EQ(dist_n0, 0);
1250}
1251
1252// ========== TEST 52: get_distance Without Painting ==========
1253TEST(BellmanFordTest, GetDistanceWithoutPainting) {
1254
1255 GT g;
1256 Node* n0 = g.insert_node(0);
1257 Node* n1 = g.insert_node(1);
1258 g.insert_arc(n0, n1, 1);
1259
1260 Bellman_Ford<GT> bf(g);
1261
1262 bool caught = false;
1263 try {
1264 bf.get_distance(n1);
1265 } catch (const std::domain_error&) {
1266 caught = true;
1267 }
1268 ASSERT_TRUE(caught);
1269}
1270
1271// ========== TEST 53: get_distance Unreachable Node ==========
1272TEST(BellmanFordTest, GetDistanceUnreachableNode) {
1273
1274 GT g;
1275 Node* n0 = g.insert_node(0);
1276 Node* n1 = g.insert_node(1);
1277 Node* n2 = g.insert_node(2); // Not connected
1278
1279 g.insert_arc(n0, n1, 1);
1280
1281 Bellman_Ford<GT> bf(g);
1282 bf.paint_spanning_tree(n0);
1283
1284 bool caught = false;
1285 try {
1286 bf.get_distance(n2);
1287 } catch (const std::domain_error&) {
1288 caught = true;
1289 }
1290 ASSERT_TRUE(caught);
1291}
1292
1293// ========== TEST 54: extract_min_spanning_tree Without Painting ==========
1294TEST(BellmanFordTest, ExtractMinSpanningTreeWithoutPainting) {
1295
1296 GT g;
1297 Node* n0 = g.insert_node(0);
1298 Node* n1 = g.insert_node(1);
1299 g.insert_arc(n0, n1, 1);
1300
1301 Bellman_Ford<GT> bf(g);
1302
1303 bool caught = false;
1304 try {
1306 } catch (const std::domain_error&) {
1307 caught = true;
1308 }
1309 ASSERT_TRUE(caught);
1310}
1311
1312// ========== TEST 55: get_distance with Null Node ==========
1313TEST(BellmanFordTest, GetDistanceNullNode) {
1314
1315 GT g;
1316 Node* n0 = g.insert_node(0);
1317 Node* n1 = g.insert_node(1);
1318 g.insert_arc(n0, n1, 1);
1319
1320 Bellman_Ford<GT> bf(g);
1321 bf.paint_spanning_tree(n0);
1322
1323 bool caught = false;
1324 try {
1325 bf.get_distance(nullptr);
1326 } catch (const std::domain_error&) {
1327 caught = true;
1328 }
1329 ASSERT_TRUE(caught);
1330}
1331
1332// ========== TEST 56: get_distance vs get_min_path Consistency ==========
1333TEST(BellmanFordTest, GetDistanceConsistentWithGetMinPath) {
1334
1335 GT g;
1336 Node* n0 = g.insert_node(0);
1337 Node* n1 = g.insert_node(1);
1338 Node* n2 = g.insert_node(2);
1339 Node* n3 = g.insert_node(3);
1340
1341 g.insert_arc(n0, n1, 5);
1342 g.insert_arc(n0, n2, 10);
1343 g.insert_arc(n1, n2, 2);
1344 g.insert_arc(n2, n3, 3);
1345
1346 Bellman_Ford<GT> bf(g);
1347 bf.paint_spanning_tree(n0);
1348
1349 // Verify that get_distance returns the same value as get_min_path
1350 for (Node* target : {n1, n2, n3}) {
1351 Path<GT> path(g);
1352 int path_dist = bf.get_min_path(target, path);
1353 int direct_dist = bf.get_distance(target);
1354 ASSERT_EQ(path_dist, direct_dist);
1355 }
1356}
1357
1358// ========== TEST: Parallel Arcs (Multigraph) ==========
1359// Test that Bellman-Ford correctly handles graphs with multiple arcs between same nodes
1360TEST(BellmanFordTest, ParallelArcsChoosesMinimum) {
1361 GT g;
1362 Node* n0 = g.insert_node(0);
1363 Node* n1 = g.insert_node(1);
1364 Node* n2 = g.insert_node(2);
1365
1366 // Multiple arcs between n0 and n1 with different weights
1367 g.insert_arc(n0, n1, 10); // expensive
1368 g.insert_arc(n0, n1, 3); // cheap - should be chosen
1369 g.insert_arc(n0, n1, 7); // medium
1370
1371 // Single arc to destination
1372 g.insert_arc(n1, n2, 2);
1373
1374 // Check if graph supports parallel arcs
1375 if (g.get_num_arcs() < 4) {
1376 GTEST_SKIP() << "Graph type does not support parallel arcs (multigraph)";
1377 }
1378
1379 Bellman_Ford<GT> bf(g);
1380 bool has_neg = bf.paint_spanning_tree(n0);
1381 EXPECT_FALSE(has_neg);
1382
1383 Path<GT> path(g);
1384 int d = bf.get_min_path(n2, path);
1385
1386 // Shortest path should use the 3 arc: 3 + 2 = 5
1387 EXPECT_EQ(d, 5);
1388}
1389
1390// ========== TEST: Parallel Arcs with Negative Weights ==========
1391TEST(BellmanFordTest, ParallelArcsNegativeWeights) {
1392 GT g;
1393 Node* n0 = g.insert_node(0);
1394 Node* n1 = g.insert_node(1);
1395 Node* n2 = g.insert_node(2);
1396
1397 // Multiple arcs including negative
1398 g.insert_arc(n0, n1, 5);
1399 g.insert_arc(n0, n1, -2); // Best (negative)
1400 g.insert_arc(n1, n2, 3);
1401
1402 // Check if graph supports parallel arcs
1403 if (g.get_num_arcs() < 3) {
1404 GTEST_SKIP() << "Graph type does not support parallel arcs (multigraph)";
1405 }
1406
1407 Bellman_Ford<GT> bf(g);
1408 bool has_neg = bf.paint_spanning_tree(n0);
1409 EXPECT_FALSE(has_neg); // No negative cycle
1410
1411 Path<GT> path(g);
1412 int d = bf.get_min_path(n2, path);
1413
1414 // Best path: -2 + 3 = 1
1415 EXPECT_EQ(d, 1);
1416}
1417
1418// ========== TEST: Complex Multigraph ==========
1419TEST(BellmanFordTest, ComplexMultigraph) {
1420 GT g;
1421 Node* n0 = g.insert_node(0);
1422 Node* n1 = g.insert_node(1);
1423 Node* n2 = g.insert_node(2);
1424 Node* n3 = g.insert_node(3);
1425
1426 // Multiple paths with parallel arcs
1427 g.insert_arc(n0, n1, 4);
1428 g.insert_arc(n0, n1, 2); // Best n0->n1
1429 g.insert_arc(n1, n2, 3);
1430 g.insert_arc(n1, n2, 1); // Best n1->n2
1431 g.insert_arc(n2, n3, 5);
1432 g.insert_arc(n2, n3, 2); // Best n2->n3
1433
1434 // Alternative direct path
1435 g.insert_arc(n0, n3, 10);
1436
1437 // Check if graph supports parallel arcs
1438 if (g.get_num_arcs() < 7) {
1439 GTEST_SKIP() << "Graph type does not support parallel arcs (multigraph)";
1440 }
1441
1442 Bellman_Ford<GT> bf(g);
1443 bool has_neg = bf.paint_spanning_tree(n0);
1444 EXPECT_FALSE(has_neg);
1445
1446 Path<GT> path(g);
1447 int d = bf.get_min_path(n3, path);
1448
1449 // Best path: 2 + 1 + 2 = 5
1450 EXPECT_EQ(d, 5);
1451}
1452
1453// ========== TEST: Parallel Arcs Creating Negative Cycle ==========
1454TEST(BellmanFordTest, ParallelArcsNegativeCycle) {
1455 GT g;
1456 Node* n0 = g.insert_node(0);
1457 Node* n1 = g.insert_node(1);
1458
1459 // Parallel arcs that form a negative cycle in undirected interpretation
1460 g.insert_arc(n0, n1, 1);
1461 g.insert_arc(n1, n0, -5); // Creates negative cycle: 1 + (-5) = -4
1462
1463 // Check if graph supports parallel arcs
1464 if (g.get_num_arcs() < 2) {
1465 GTEST_SKIP() << "Graph type does not support parallel arcs (multigraph)";
1466 }
1467
1468 Bellman_Ford<GT> bf(g);
1469 bool has_neg = bf.paint_spanning_tree(n0);
1470
1471 // Should detect negative cycle
1472 EXPECT_TRUE(has_neg);
1473}
1474
1475// The policy of the report on 7.0.0: the weight of an arc times a factor.
1476struct Scaled_Distance
1477{
1478 using Distance_Type = int;
1479
1480 int factor = 1;
1481
1482 int operator()(Arc * a) const { return factor * a->get_info(); }
1483};
1484
1485// get_min_path() added up the weights with a default-constructed distance
1486// instead of the one given to the constructor.
1487TEST(BellmanFordTest, GetMinPathUsesTheDistanceItWasGiven) {
1488 GT g;
1489 Node* n0 = g.insert_node(0);
1490 Node* n1 = g.insert_node(1);
1491 Node* n2 = g.insert_node(2);
1492 g.insert_arc(n0, n1, 3);
1493 g.insert_arc(n1, n2, 4);
1494 g.insert_arc(n0, n2, 20);
1495
1497 ASSERT_FALSE(bf.paint_spanning_tree(n0));
1498
1499 Path<GT> path(g);
1500 EXPECT_EQ(bf.get_min_path(n2, path), 21);
1501 EXPECT_EQ(path.get_first_node(), n0);
1502 EXPECT_EQ(path.get_last_node(), n2);
1503}
1504
1505// A negative loop that the start reaches only through a sum beyond max():
1506// the searches from the start cannot see it, so that they throw, as the
1507// paintings do
1508TEST(BellmanFordTest, ANegativeCycleBeyondMaxThrowsFromTheStart) {
1509 constexpr int M = std::numeric_limits<int>::max();
1510 GT g;
1511 Node* a = g.insert_node(0);
1512 Node* b = g.insert_node(1);
1513 Node* c = g.insert_node(2);
1514 g.insert_arc(a, a, -1);
1515 g.insert_arc(b, a, M - 5);
1516 g.insert_arc(c, b, M / 2); // from c, a is at M / 2 + M - 5
1517
1518 EXPECT_THROW(Bellman_Ford<GT>(g).has_negative_cycle(c), std::overflow_error);
1519 EXPECT_THROW(Bellman_Ford<GT>(g).test_negative_cycle(c), std::overflow_error);
1520 Path<GT> cycle(g);
1521 EXPECT_THROW(Bellman_Ford<GT>(g).test_negative_cycle(c, cycle), std::overflow_error);
1522 EXPECT_THROW(Bellman_Ford<GT>(g).search_negative_cycle(c), std::overflow_error);
1523 EXPECT_THROW(Bellman_Ford<GT>(g).search_negative_cycle(c, 0.5, 1), std::overflow_error);
1524 EXPECT_THROW(Bellman_Ford<GT>(g).paint_spanning_tree(c), std::overflow_error);
1525 EXPECT_THROW(Bellman_Ford<GT>(g).faster_paint_spanning_tree(c), std::overflow_error);
1526
1527 // From a start within the range, and without a start, the loop is found
1528 EXPECT_TRUE(Bellman_Ford<GT>(g).has_negative_cycle(b));
1529 EXPECT_FALSE(Bellman_Ford<GT>(g).test_negative_cycle(b).is_empty());
1530 EXPECT_FALSE(Bellman_Ford<GT>(g).search_negative_cycle(b).is_empty());
1531 EXPECT_TRUE(Bellman_Ford<GT>(g).has_negative_cycle());
1532 EXPECT_FALSE(Bellman_Ford<GT>(g).search_negative_cycle().is_empty());
1533}
1534
1535// ========== A distance with a tolerance ==========
1536
1538
1539// The weight of an arc, with a tolerance that a relaxation must beat
1541{
1542 double tol = 0;
1543
1544 Tolerant_Dist() = default;
1545 explicit Tolerant_Dist(double t) : tol(t) {}
1546
1547 double tolerance() const noexcept { return tol; }
1548};
1549
1550// A cycle that weighs less than zero by less than the tolerance, as the
1551// rounding of the sums of weights that are not exact in binary may make
1552// one of weight zero, is no negative cycle for a distance with a tolerance
1553TEST(BellmanFordTest, ATolerantDistanceTakesNoCycleWithinItsTolerance)
1554{
1555 DGT g;
1556 auto a = g.insert_node(0);
1557 auto b = g.insert_node(1);
1558 g.insert_arc(a, b, 1.0);
1559 auto ba = g.insert_arc(b, a, -1.0 - 1e-14);
1560 using Tolerant_BF = Bellman_Ford<DGT, Tolerant_Dist>;
1561
1562 EXPECT_TRUE(Bellman_Ford<DGT>(g).has_negative_cycle(a));
1563 EXPECT_FALSE(Tolerant_BF(g, Tolerant_Dist(1e-12)).has_negative_cycle(a));
1564 EXPECT_TRUE(Tolerant_BF(g, Tolerant_Dist(1e-12)).search_negative_cycle(a).is_empty());
1565 EXPECT_FALSE(Tolerant_BF(g, Tolerant_Dist(1e-12)).has_negative_cycle());
1566
1567 // Beyond the tolerance, the cycle is negative
1568 ba->get_info() = -1.1;
1569 EXPECT_TRUE(Tolerant_BF(g, Tolerant_Dist(1e-12)).has_negative_cycle(a));
1570 EXPECT_FALSE(Tolerant_BF(g, Tolerant_Dist(1e-12)).search_negative_cycle(a).is_empty());
1571}
1572
1573// The weight of an arc of a graph of integer weights, with a tolerance
1574template <class G>
1576{
1578
1580
1583
1584 Distance_Type tolerance() const noexcept { return tol; }
1585};
1586
1588
1589// With an unsigned distance, accum - tolerance() went around below 0: any
1590// sum relaxed a distance below the tolerance, as the one of the start, and
1591// a cycle of weight zero, or a positive one, was taken for a negative one
1592TEST(BellmanFordTest, AnUnsignedToleranceDoesNotWrapAround)
1593{
1595 for (const unsigned w : {0u, 1u}) // a cycle of weight zero, and a positive one
1596 for (const unsigned tol : {1u, 5u})
1597 for (const bool faster : {false, true})
1598 {
1599 UGT g;
1600 auto a = g.insert_node(0);
1601 auto b = g.insert_node(1);
1602 g.insert_arc(a, b, w);
1603 g.insert_arc(b, a, w);
1604 const Tolerant_Int_Dist<UGT> d(tol);
1605
1606 EXPECT_FALSE(UBF(g, d).has_negative_cycle(a));
1607 EXPECT_FALSE(UBF(g, d).has_negative_cycle());
1608 UBF bf(g, d);
1609 ASSERT_FALSE(faster ? bf.faster_paint_spanning_tree(a) : bf.paint_spanning_tree(a));
1610 EXPECT_EQ(bf.get_distance(b), w);
1611 }
1612}
1613
1614// A node without a distance, at max(), did not take a sum that fits within
1615// the tolerance of max(): it was left without one
1616TEST(BellmanFordTest, AnIntegerToleranceLeavesNoNodeWithoutADistance)
1617{
1619 const Tolerant_Int_Dist<GT> d(2);
1620 constexpr int max = std::numeric_limits<int>::max();
1621 for (const bool faster : {false, true})
1622 {
1623 GT g;
1624 auto a = g.insert_node(0);
1625 auto b = g.insert_node(1);
1626 g.insert_arc(a, b, max - 1);
1627
1628 IBF bf(g, d);
1629 ASSERT_FALSE(faster ? bf.faster_paint_spanning_tree(a) : bf.paint_spanning_tree(a));
1630 EXPECT_EQ(bf.get_distance(b), max - 1);
1631 }
1632}
1633
1634// With a signed distance, accum - tolerance() overflowed below lowest(): a
1635// sum that did not improve a distance relaxed it, and there was a negative
1636// cycle where there is no cycle
1637TEST(BellmanFordTest, ASignedToleranceDoesNotOverflow)
1638{
1640 const Tolerant_Int_Dist<GT> d(2);
1641 constexpr int lowest = std::numeric_limits<int>::lowest();
1642
1643 // b gets lowest() + 1, and then 0, by a parallel arc, does not relax it
1644 for (const bool faster : {false, true})
1645 {
1646 GT g;
1647 auto a = g.insert_node(0);
1648 auto b = g.insert_node(1);
1649 g.insert_arc(a, b, lowest + 1);
1650 g.insert_arc(a, b, 0);
1651
1652 EXPECT_FALSE(IBF(g, d).has_negative_cycle(a));
1653 EXPECT_FALSE(IBF(g, d).has_negative_cycle());
1654 IBF bf(g, d);
1655 ASSERT_FALSE(faster ? bf.faster_paint_spanning_tree(a) : bf.paint_spanning_tree(a));
1656 EXPECT_EQ(bf.get_distance(b), lowest + 1);
1657 }
1658}
1659
1660// ========== GoogleTest main ==========
1661int main(int argc, char **argv)
1662{
1663 ::testing::InitGoogleTest(&argc, argv);
1664 return RUN_ALL_TESTS();
1665}
Bellman-Ford algorithm for single-source shortest paths.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int main()
long double w
Definition btreepic.C:153
int num_nodes
Definition btreepic.C:410
Bellman-Ford algorithm for shortest paths with negative weights.
Distance_Type get_distance(typename GT::Node *node)
Get the accumulated distance to a node from a previously painted tree.
DynArray< Arc * > extract_min_spanning_tree()
Extract the shortest paths tree in a compressed form.
bool has_computation() const noexcept
Check if a shortest-path tree has been computed or painted.
bool faster_paint_spanning_tree(Node *start)
Faster shortest paths tree painting from a start node.
DynMapTree< Node *, Distance_Type > compute_nodes_weights()
Returns a mapping with the shortest distances to each node obtained after executing the Bellman-Ford ...
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
bool is_painted() const noexcept
Check if a shortest-path tree has been painted.
std::tuple< Path< GT >, size_t > search_negative_cycle(Node *start, double it_factor, const size_t step)
Searches a negative cycle using the faster version of Bellman-Ford algorithm and iteratively searchin...
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extract the shortest path to a node from a previously painted tree.
const GT & get_graph() const noexcept
Get reference to the graph.
Node * get_start_node() const noexcept
Get the start node of the last computation.
Path< GT > test_negative_cycle(Node *start)
Search a negative cycle on all possible paths starting from start node.
void build_tree(GT &tree, bool with_map=true)
Extract from the graph a previously painted shortest paths tree.
Default distance accessor for arc weights.
GT::Arc_Type Distance_Type
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Arc Arc
Definition graph-dry.H:4381
typename BaseGraph::Node Node
Definition graph-dry.H:4380
size_t size() const noexcept
Return the current dimension of array.
void next()
Advances the iterator to the next filtered element.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Iterator on nodes and arcs of a path.
Definition tpl_graph.H:4395
bool has_current_node() const noexcept
Return true if the iterator has a current node.
Definition tpl_graph.H:4512
Path on a graph.
Definition tpl_graph.H:3832
bool is_cycle() const
Return true if this is a cycle; throws if path is empty.
Definition tpl_graph.H:4351
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4316
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4323
void for_each_arc(Operation op=Operation()) const
Execute an operation on each arc of path.
Definition tpl_graph.H:4540
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
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
#define TEST(name)
#define N
Definition fib.C:294
static Geom_Number dist2(const Point &a, const Point &b)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
bool has_cycle(const GT &g)
Return true if an undirected graph has at least one cycle.
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
@ Spanning_Tree
Definition aleph-graph.H:79
Main namespace for Aleph-w library functions.
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Definition ahPair.H:89
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Detects if a negative cycle exists and eventually computes it.
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
int operator()(Arc *a) const
Tolerant_Dist()=default
double tolerance() const noexcept
Tolerant_Int_Dist()=default
Distance_Type tolerance() const noexcept
Tolerant_Int_Dist(Distance_Type t)
typename Dft_Dist< G >::Distance_Type Distance_Type
Generic graph and digraph implementations.