-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman_Ford.H
More file actions
1440 lines (1196 loc) · 45.1 KB
/
Copy pathBellman_Ford.H
File metadata and controls
1440 lines (1196 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Bellman_Ford.H
* @brief Bellman-Ford algorithm for single-source shortest paths.
*
* This file implements the Bellman-Ford algorithm, which computes the shortest
* paths from a single source vertex to all other vertices in a weighted
* directed graph. Unlike Dijkstra's algorithm, Bellman-Ford can handle
* graphs with negative edge weights and can detect negative-weight cycles.
*
* ## Complexity
*
* | Algorithm | Time (avg) | Time (worst) | Space |
* |-----------|------------|--------------|-------|
* | Standard | O(V*E) | O(V*E) | O(V) |
* | SPFA | O(E) | O(V*E) | O(V) |
*
* @par Example
* @code
* List_Digraph<Node, Arc> g;
* // ... build graph ...
* List_Digraph<Node, Arc>::Node * start = g.get_first_node();
*
* Bellman_Ford bf(g);
*
* // Check for negative cycles and compute shortest paths from 'start'
* if (bf.has_negative_cycle(start)) {
* Path<Graph> cycle = bf.build_negative_cycle();
* // handle negative cycle
* } else {
* // bf.is_painted() is true, Spanning_Tree bits are set
* }
* @endcode
*
* @see Dijkstra.H For graphs without negative weights (more efficient)
* @see Floyd_Warshall.H For all-pairs shortest paths
* @see Johnson.H For all-pairs with negative weights (uses Bellman-Ford)
*
* @ingroup Graphs
* @author Leandro Rabindranath León
*/
#ifndef BELLMAN_FORD_H
#define BELLMAN_FORD_H
#include <type_traits>
#include <limits>
#include <vector>
#include <tpl_dynListQueue.H>
#include <tpl_dynSetTree.H>
#include <tpl_graph_utils.H>
#include <Tarjan.H>
#include <ah-errors.H>
#include <ah_init_guard.H>
#include <cookie_guard.H>
namespace Aleph {
/** Bellman-Ford algorithm for shortest paths with negative weights.
This class implements the Bellman-Ford algorithm for finding shortest
paths from a single source node. Unlike Dijkstra's algorithm, Bellman-Ford
can handle graphs with negative edge weights and can detect negative cycles.
Two versions are provided:
- **Standard version**: O(V*E) time complexity
- **Faster version**: Uses a queue-based optimization (SPFA variant)
which is often faster in practice.
Template parameters:
- `GT`: Graph type (typically `List_Digraph`).
- `Distance`: Arc weight accessor. Must define `Distance_Type` and provide
`Distance_Type operator()(typename GT::Arc *a)`.
- `Ait`: Arc iterator template for traversing all arcs.
- `NAit`: Node arc iterator template for traversing arcs from a node.
- `SA`: Arc filter for the internal iterators.
Features:
- Detects negative cycles
- Can return the negative cycle as a path
- Computes a shortest-path tree (painted or separate)
- Used by Johnson's algorithm for node weight computation
## State Management
This class maintains internal state between operations:
- `painted`: Whether a spanning tree is currently painted on the graph
- `s`: The start node of the last computation
- `arcs`: Predecessor array for path reconstruction
**Important usage notes:**
1. **Graph modification**: The graph is temporarily modified during each
operation (node/arc bits and cookies). These modifications are cleaned
up when the operation completes. Do not modify the graph structure
during an operation.
2. **Sequential calls**: Calling paint_spanning_tree() twice without
calling clear() will overwrite the previous painted state. If you need
to preserve the previous state, call clear() first or use a new
Bellman_Ford instance.
3. **Reusability**: The same Bellman_Ford object can be reused for
multiple computations on the same graph. Each operation automatically
resets the internal state.
4. **Exception safety**: All operations are exception-safe. If an
exception is thrown, the graph is restored to a consistent state
(RAII guards ensure cleanup).
@warning This class is **not thread-safe**. Each instance maintains internal
state that would be corrupted by concurrent access.
@warning The constructor takes a non-const graph reference because the
algorithm temporarily modifies node/arc bits and cookies. For methods that
detect global negative cycles (no start node), a dummy node is temporarily
added to the graph and removed when the operation completes.
@note For graphs without negative weights, Dijkstra's algorithm is more
efficient (O((V+E) log V) vs O(V*E)).
@ingroup Graphs
@see Dijkstra_Min_Paths Johnson Floyd_All_Shortest_Paths
*/
template <class GT,
class Distance = Dft_Dist<GT>,
template <class, class> class Ait = Arc_Iterator,
template <class, class> class NAit = Out_Iterator,
class SA = Dft_Show_Arc<GT>>
class Bellman_Ford
{
typedef typename Distance::Distance_Type Distance_Type;
using Node = typename GT::Node;
using Arc = typename GT::Arc;
struct Sni
{
Distance_Type accum;
};
struct Ni : public Sni
{
int idx; // index in the predecessor arrays
};
static Distance_Type &accum(Node *p) noexcept
{
return static_cast<Sni *>(NODE_COOKIE(p))->accum;
}
static int &idx(Node *p) noexcept
{
return static_cast<Ni *>(NODE_COOKIE(p))->idx;
}
// Checked addition to prevent integer overflow
Distance_Type checked_add(const Distance_Type &a, const Distance_Type &b) const
{
if constexpr (std::is_integral_v<Distance_Type>)
{
// Check for positive overflow
ah_overflow_error_if(b > 0 && a > std::numeric_limits<Distance_Type>::max() - b)
<< "Integer overflow in distance addition: " << a << " + " << b;
// Check for negative overflow (underflow)
ah_overflow_error_if(b < 0 && a < std::numeric_limits<Distance_Type>::min() - b)
<< "Integer underflow in distance addition: " << a << " + " << b;
}
return a + b;
}
DynArray<typename GT::Arc *> arcs_;
GT &g_; // Non-const: algorithm modifies node/arc bits and cookies
const Distance_Type Inf;
bool painted_ = false;
Node *s_ = nullptr;
SA sa_;
Distance dist_;
/// Initialize node cookies for simple mode (without predecessor tracking).
void init_simple(Node *start)
{
Init_Guard guard([this]()
{
uninit<Sni>();
});
typename GT::Node_Iterator it(g_);
for (int i = 0; it.has_curr(); ++i, it.next_ne())
{
auto p = it.get_curr();
g_.reset_bit(p, Aleph::Spanning_Tree); // set bit to zero
NODE_COOKIE(p) = nullptr; // clear stale pointer before allocating
auto ptr = new Sni;
ptr->accum = Inf;
NODE_BITS(p).set_bit(Spanning_Tree, false);
NODE_COOKIE(p) = ptr;
}
s_ = start;
accum(s_) = 0;
g_.reset_arcs();
guard.release(); // Successful initialization, prevent cleanup
}
/// Initialize node cookies with predecessor tracking for path reconstruction.
void init_with_indexes(Node *start)
{
Init_Guard guard([this]()
{
uninit<Ni>();
arcs_.cut();
});
const size_t n = g_.get_num_nodes();
arcs_.cut(); // Clear any previous data
arcs_.reserve(n);
typename GT::Node_Iterator it(g_);
for (size_t i = 0; it.has_curr(); ++i, it.next())
{
// Use touch() to ensure memory is allocated for index i
arcs_.touch(i) = nullptr;
auto p = it.get_curr();
g_.reset_bit(p, Aleph::Spanning_Tree); // set bit to zero
NODE_COOKIE(p) = nullptr; // clear stale pointer before allocating
auto ptr = new Ni;
ptr->accum = Inf;
ptr->idx = static_cast<int>(i);
NODE_BITS(p).set_bit(Spanning_Tree, false);
NODE_BITS(p).set_bit(Depth_First, false); // indicates if it is in queue
NODE_COOKIE(p) = ptr;
}
painted_ = false;
s_ = start;
accum(s_) = 0;
g_.reset_arcs();
guard.release(); // Successful initialization, prevent cleanup
}
/// Release the memory associated with the node cookies.
template <class Info_Type>
void uninit()
{
for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next())
{
auto p = it.get_curr();
delete static_cast<Info_Type *>(NODE_COOKIE(p));
NODE_COOKIE(p) = nullptr;
}
}
/** Check that painted arcs form a valid spanning tree structure.
Verifies the following invariants:
1. Number of painted arcs == number of painted nodes - 1 (tree property)
2. Each painted node (except root) has exactly one incoming painted arc
3. Root node (s) has no incoming painted arcs
For disconnected graphs, only the component reachable from s is verified.
@return true if the painted structure is valid, false otherwise.
*/
bool check_painted_arcs() noexcept
{
if (s_ == nullptr)
return false;
size_t num_painted_arcs = 0;
size_t num_painted_nodes = 0;
// Count painted arcs
for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
if (IS_ARC_VISITED(it.get_curr(), Aleph::Spanning_Tree))
++num_painted_arcs;
// Count painted nodes and verify each has exactly one incoming painted arc
for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
{
auto node = it.get_curr();
if (not IS_NODE_VISITED(node, Aleph::Spanning_Tree))
continue;
++num_painted_nodes;
// Skip root node - it should have no incoming painted arcs
if (node == s_)
continue;
// Count incoming painted arcs to this node
size_t incoming_count = 0;
for (Ait<GT, SA> ait(g_, sa_); ait.has_curr(); ait.next_ne())
if (auto arc = ait.get_curr();
IS_ARC_VISITED(arc, Aleph::Spanning_Tree) and g_.get_tgt_node(arc) == node)
++incoming_count;
// Each non-root painted node must have exactly 1 incoming painted arc
if (incoming_count != 1)
return false;
}
// Tree property: #arcs == #nodes - 1
return num_painted_nodes != 0 and num_painted_arcs == num_painted_nodes - 1;
}
public:
/** Construct a Bellman-Ford executor.
@param[in] __g The graph to operate on. Note: the graph will be
temporarily modified (node/arc bits and cookies) during
algorithm execution. The modifications are cleaned up
after each operation completes.
@param[in] d Arc-weight accessor.
@param[in] __sa Arc filter for internal iterators.
@warning The graph reference is stored internally. Do not modify
the graph structure while a Bellman_Ford operation is in
progress.
*/
Bellman_Ford(GT &__g, Distance d = Distance(), SA __sa = SA())
: g_(__g), Inf(std::numeric_limits<Distance_Type>::max()), painted_(false), sa_(__sa), dist_(d)
{
// empty
}
/** Clear the painted state and reset internal data structures.
This method should be called if you want to reuse the same Bellman_Ford
object for a different computation, or if you want to clear the
Spanning_Tree bits that were painted on the graph.
After calling clear():
- has_computation() returns false
- is_painted() returns false
- All Spanning_Tree bits on nodes/arcs are cleared
- The predecessor array is cleared
- NODE_COOKIE pointers are NOT touched (they were already cleaned
by previous operations)
@note This is automatically called at the start of each paint/compute
operation, so explicit calls are usually not needed.
*/
void clear() noexcept
{
if (painted_)
{
// Clear Spanning_Tree bits from all nodes and arcs
for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
NODE_BITS(it.get_curr()).set_bit(Aleph::Spanning_Tree, false);
for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
ARC_BITS(it.get_curr()).set_bit(Aleph::Spanning_Tree, false);
}
arcs_.cut();
painted_ = false;
s_ = nullptr;
}
/// Check if a shortest-path tree has been computed or painted.
/// @return true if a previous computation exists, false otherwise.
[[nodiscard]] bool has_computation() const noexcept
{
return s_ != nullptr;
}
/// Check if a shortest-path tree has been painted.
/// @return true if a tree has been painted, false otherwise.
[[nodiscard]] bool is_painted() const noexcept
{
return painted_;
}
/// Get the start node of the last computation.
/// @return Pointer to the start node, or nullptr if no computation exists.
Node *get_start_node() const noexcept
{
return s_;
}
/// Get reference to the graph.
/// @return Reference to the graph.
const GT &get_graph() const noexcept
{
return g_;
}
private:
/// Relax all arcs n-1 times (standard Bellman-Ford).
void relax_arcs() noexcept
{
const size_t &n = g_.vsize();
if (n <= 1)
return; // Nothing to relax for empty or single-node graphs
for (size_t i = 0; i < n - 1; ++i)
for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
{
auto arc = it.get_curr();
auto src = g_.get_src_node(arc);
const auto &accum_src = accum(src);
if (accum_src == Inf)
continue;
auto tgt = it.get_tgt_node_ne();
auto w = dist_(arc);
auto sum = checked_add(accum_src, w);
auto &accum_tgt = accum(tgt);
if (sum < accum_tgt) // Relax Arc
{
const auto &index = idx(tgt);
arcs_(index) = arc;
accum_tgt = sum;
}
}
}
/// Insert a node into the queue if not already present (SPFA optimization).
static void put_in_queue(DynListQueue<typename GT::Node *> &q, typename GT::Node *p)
{
if (IS_NODE_VISITED(p, Depth_First)) // is already inside the queue?
return;
NODE_BITS(p).set_bit(Depth_First, true);
q.put(p);
}
/// Remove a node from the queue and clear its in-queue flag.
static typename GT::Node *get_from_queue(DynListQueue<typename GT::Node *> &q)
{
auto ret = q.get();
assert(IS_NODE_VISITED(ret, Depth_First));
NODE_BITS(ret).set_bit(Depth_First, false);
return ret;
}
/// Relax outgoing arcs from a source node (SPFA variant).
void relax_arcs(typename GT::Node *src, DynListQueue<typename GT::Node *> &q)
{
for (NAit<GT, SA> it(src, sa_); it.has_curr(); it.next_ne())
{
auto arc = it.get_curr();
auto arc_src = g_.get_src_node(arc);
const auto &accum_src = accum(arc_src);
if (accum_src == Inf)
continue;
auto tgt = g_.get_tgt_node(arc);
auto w = dist_(arc);
auto sum = checked_add(accum_src, w);
auto &accum_tgt = accum(tgt);
if (sum < accum_tgt) // Relax Arc
{
const auto &index = idx(tgt);
arcs_(index) = arc;
accum_tgt = sum;
put_in_queue(q, tgt);
}
}
}
/// Paint the spanning tree nodes and arcs with the Spanning_Tree bit.
void paint_tree() noexcept
{ // paint the involved nodes and arcs
const size_t n = g_.vsize();
for (size_t i = 0; i < n; ++i)
{
auto arc = arcs_(i);
if (arc == nullptr)
continue;
ARC_BITS(arc).set_bit(Aleph::Spanning_Tree, true);
auto src = g_.get_src_node(arc);
auto tgt = g_.get_tgt_node(arc);
NODE_BITS(src).set_bit(Aleph::Spanning_Tree, true);
NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
}
NODE_BITS(s_).set_bit(Aleph::Spanning_Tree, true);
assert(check_painted_arcs());
painted_ = true;
}
/// Perform one more relaxation pass and check for negative cycle.
/// Also updates predecessor array for cycle detection.
bool last_relax_and_prepare_check_negative_cycle() noexcept
{
bool negative_cycle = false;
for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
{
auto arc = it.get_curr();
auto src = g_.get_src_node(arc);
auto &accum_src = accum(src);
if (accum_src == Inf)
continue;
auto tgt = g_.get_tgt_node(arc);
auto d = dist_(arc);
auto &accum_tgt = accum(tgt);
auto sum = checked_add(accum_src, d);
if (sum < accum_tgt)
{
negative_cycle = true;
const auto &index = idx(tgt);
arcs_(index) = arc;
accum_tgt = sum;
}
}
return negative_cycle;
}
/// Perform one more relaxation pass to detect (but not prepare) negative cycle.
bool last_relax_and_test_negative_cycle() noexcept
{
for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
{
auto arc = it.get_curr();
auto src = g_.get_src_node(arc);
auto &accum_src = accum(src);
if (accum_src == Inf)
continue;
auto tgt = g_.get_tgt_node(arc);
auto d = dist_(arc);
auto &accum_tgt = accum(tgt);
auto sum = checked_add(accum_src, d);
if (sum < accum_tgt)
return true;
}
return false;
}
/// Free node cookies and set up predecessor pointers for path reconstruction.
void link_cookies_and_free(typename GT::Node *start) noexcept
{
uninit<Ni>();
// Construct the inverted paths to the start origin node
const size_t n = g_.vsize();
for (size_t i = 0; i < n; ++i)
{
auto arc = arcs_(i);
if (arc == nullptr)
continue;
auto tgt = g_.get_tgt_node(arc);
NODE_COOKIE(tgt) = g_.get_src_node(arc);
}
NODE_COOKIE(start) = nullptr; // just in case there is a negative cycle
}
public:
/** Paint the shortest paths tree from a `start` node.
@param[in] start source node from which the shortest paths will be
computed.
@return true if negative cycles are detected, in which case the
shortest paths tree has no sense. Otherwise, `false` is
returned and the shortest paths tree is painted with the bit
`Spanning_Tree`.
*/
bool paint_spanning_tree(Node *start)
{
ah_domain_error_if(start == nullptr) << "start node cannot be null";
init_with_indexes(start);
relax_arcs();
const bool negative_cycle = last_relax_and_prepare_check_negative_cycle();
// Only paint the tree if there's no negative cycle
// A negative cycle makes the shortest path tree meaningless
if (not negative_cycle)
paint_tree();
link_cookies_and_free(s_);
return negative_cycle;
}
/** Faster shortest paths tree painting from a `start` node.
This method executes a faster version of Bellman-Ford algorithm
(SPFA variant) which is often more efficient in practice.
@param[in] start source node from which the shortest paths will be
computed.
@return true if negative cycles are detected, in which case the
shortest paths tree has no sense. Otherwise, `false` is
returned and the shortest paths tree is painted with the bit
`Spanning_Tree`.
*/
bool faster_paint_spanning_tree(Node *start)
{
ah_domain_error_if(start == nullptr) << "start node cannot be null";
init_with_indexes(start);
const auto &n = g_.get_num_nodes();
DynListQueue<typename GT::Node *> q;
Node __sentinel;
Node *sentinel = &__sentinel;
put_in_queue(q, s_);
put_in_queue(q, sentinel);
for (size_t i = 0; not q.is_empty();)
{
auto src = get_from_queue(q);
if (src == sentinel) // Is the sentinel removed?
{
if (i++ > n)
{
while (not q.is_empty())
get_from_queue(q); // clear Depth_First bits on remaining nodes
break;
}
put_in_queue(q, sentinel);
}
else
relax_arcs(src, q);
}
const bool negative_cycle = last_relax_and_prepare_check_negative_cycle();
// Only paint the tree if there's no negative cycle
// A negative cycle makes the shortest path tree meaningless
if (not negative_cycle)
paint_tree();
link_cookies_and_free(s_);
return negative_cycle;
}
private:
/// Create a dummy node connected to all nodes with zero-weight edges.
/// Used for detecting negative cycles in the entire graph.
Node *create_dummy_node()
{
// RAII guard to ensure cleanup on exception
struct Dummy_Guard
{
GT &graph;
Node *dummy;
std::vector<Arc *> inserted_arcs;
bool released = false;
explicit Dummy_Guard(GT &g, Node *d) : graph(g), dummy(d)
{
inserted_arcs.reserve(g.get_num_nodes());
}
~Dummy_Guard()
{
if (not released)
{
// Remove all inserted arcs
for (auto arc : inserted_arcs)
graph.remove_arc(arc);
// Remove dummy node
if (dummy != nullptr)
graph.remove_node(dummy);
}
}
void add_arc(Arc *a)
{
inserted_arcs.push_back(a);
}
void release()
{
released = true;
}
Dummy_Guard(const Dummy_Guard &) = delete;
Dummy_Guard &operator=(const Dummy_Guard &) = delete;
};
s_ = g_.insert_node(typename GT::Node_Type());
Dummy_Guard guard(g_, s_);
for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
{
auto p = it.get_curr();
if (p == s_)
continue;
auto a = g_.insert_arc(s_, p);
guard.add_arc(a);
Distance::set_zero(a);
}
guard.release(); // Successful creation, prevent cleanup
return s_;
}
/// Remove a dummy node and clean up its cookie.
template <class Info_Type>
void remove_dummy_node(Node *p)
{
delete static_cast<Info_Type *>(NODE_COOKIE(p));
NODE_COOKIE(p) = nullptr;
if (p == s_)
s_ = nullptr;
g_.remove_node(p);
}
public:
/** Test if a negative cycle exists starting from a specific node.
@param[in] start Source node from which to check for negative cycles.
@return true if a negative cycle is reachable from start, false otherwise.
@throw std::domain_error if start is nullptr.
*/
bool has_negative_cycle(Node *start)
{
ah_domain_error_if(start == nullptr) << "start node cannot be null";
init_with_indexes(start);
// Note: s and accum(s) already set by init_with_indexes
relax_arcs();
const bool negative_cycle = last_relax_and_test_negative_cycle();
uninit<Ni>();
return negative_cycle;
}
/** Test if a negative cycle exists anywhere in the graph.
Creates a temporary dummy node connected to all other nodes with
zero-weight edges, then runs negative cycle detection from it.
@return true if any negative cycle exists in the graph, false otherwise.
@note This method temporarily modifies the graph by adding a dummy node.
The modification is rolled back even if an exception is thrown.
*/
bool has_negative_cycle()
{
Node *dummy = create_dummy_node();
// RAII guard ensures dummy node removal even on exception
struct Global_Cycle_Guard
{
Bellman_Ford &bf;
Node *dummy_node;
bool released = false;
Global_Cycle_Guard(Bellman_Ford &b, Node *d) : bf(b), dummy_node(d) {}
~Global_Cycle_Guard()
{
if (not released and dummy_node != nullptr)
{
// Clean up: remove dummy node and its arcs
bf.remove_dummy_node<Ni>(dummy_node);
}
}
void release()
{
released = true;
}
};
Global_Cycle_Guard guard(*this, dummy);
auto ret = has_negative_cycle(dummy);
guard.release();
remove_dummy_node<Ni>(dummy);
return ret;
}
private:
/// Build spanning tree from arcs and search for cycle using Tarjan's algorithm.
Path<GT> search_negative_cycle_on_partial_graph()
{
GT aux = build_spanning_tree<GT>(arcs_);
// we map because Tarjan algorithm modifies cookies
DynMapTree<Node *, Node *> table;
for (typename GT::Node_Iterator it(aux); it.has_curr(); it.next_ne())
{
auto p = it.get_curr();
table.insert(p, static_cast<Node *>(NODE_COOKIE(p)));
}
// Save and restore cookies around Tarjan call (Tarjan modifies cookies)
Cookie_Saver<GT> cookie_saver(aux, true, false); // only save node cookies
// Clear cookies for Tarjan's use
for (typename GT::Node_Iterator it(aux); it.has_curr(); it.next_ne())
NODE_COOKIE(it.get_curr()) = nullptr;
if (Path<GT> path(aux); Tarjan_Connected_Components<GT, NAit, SA>(sa_).compute_cycle(aux, path))
{
Path<GT> ret(g_);
for (typename Path<GT>::Iterator it(path); it.has_current_node(); it.next_ne())
ret.append_directed(static_cast<Node *>(table.find(it.get_current_node_ne())));
return ret;
}
return Path<GT>(g_);
}
public:
/** Search a negative cycle on all possible paths starting from
`start` node.
If a negative cycle is found, then the Tarjan algorithm is executed
for retrieving it. In this case the cycle is returned. Otherwise
(there is no negative cycle), the returned path is empty.
@param[in] start starting node
@return a valid path corresponding to a negative cycle if this is
found. Otherwise, an empty path
*/
Path<GT> test_negative_cycle(Node *start)
{
ah_domain_error_if(start == nullptr) << "start node cannot be null";
init_with_indexes(start);
relax_arcs();
const bool negative_cycle = last_relax_and_prepare_check_negative_cycle();
if (not negative_cycle)
{
link_cookies_and_free(s_);
return Path<GT>(g_);
}
Path<GT> ret = search_negative_cycle_on_partial_graph();
if (ret.is_empty())
WARNING(
"Serious inconsistency. Bellman-Ford algorithm has detected\n"
"a negative cycle, but Tarjan algorithm executed on partial\n"
"graph has not found such cycle\n\n"
"Be very careful, this is provably a bug");
link_cookies_and_free(s_);
return ret;
}
/** Searches and returns a negative cycle (if it exists).
@return a path containing a negative cycle (if it
exists). Otherwise, it returns an empty path.
*/
Path<GT> test_negative_cycle()
{
auto start = create_dummy_node();
// RAII guard ensures dummy node removal even on exception
Init_Guard guard([this, start]()
{
remove_dummy_node<Ni>(start);
});
auto ret_val = test_negative_cycle(start);
guard.release();
remove_dummy_node<Ni>(start);
return ret_val;
}
/** Searches a negative cycle using the faster version of Bellman-Ford
algorithm and iteratively searching the cycle before finishing up.
Normally, the Bellman-Ford algorith certainly detects a negative
cycle if during an additional arcs scanning an arc is
relaxed. However, very frequently the cycle appears in graph used
for representing the partial spanning tree.
This version could be seen as thus:
threshold = it_factor*|V|;
for (int i = 0; i < |V|; ++i)
{
for (e in Arcs) // for each arc e
relax e;
if (i >= threshold)
{
// search a cycle in the graph representing the spanning tree
threshold += step;
if negative cycle is found
return it;
}
}
So, from the threshold-th iteration, the algorithm tries to find a
negative cycle on the hope that if this exists, then the algorithm
will finish much before the normal completion.
@warning The cycle searching is done with respect to a source
node. So, if no negative cycle is found, then this is still not
conclusive for determining that the graph has no negative cycles.
@param[in] start node from which the spanning tree is built.
@param[in] it_factor iterative factor since then the negative
cycle is searched.
@param[in] step next step from which the next negative cycle will
be done.
@return a tuple whose `get<0>` value corresponds to the found
negative cycle (if this one exists) and `get<1>` value is the
external iteration when the cycle was found. The idea of this
second field is to give feedback in order to eventually refine the
`it_factor` value.
*/
std::tuple<Path<GT>, size_t> search_negative_cycle(Node *start, double it_factor, const size_t step)
{
ah_domain_error_if(start == nullptr) << "start node cannot be null";
init_with_indexes(start);
const auto &n = g_.get_num_nodes();
DynListQueue<typename GT::Node *> q;
Node __sentinel;
Node *sentinel = &__sentinel;
put_in_queue(q, s_);
put_in_queue(q, sentinel);
double threshold = it_factor * n;
Path<GT> ret(g_);
size_t i = 0;
while (not q.is_empty())
{
auto src = get_from_queue(q);
if (src == sentinel)
{
if (i++ > n)
break;
put_in_queue(q, sentinel);
if (i >= threshold) // must I search negative cycles?
{
ret = search_negative_cycle_on_partial_graph();
if (not ret.is_empty()) // negative cycle found?
{
link_cookies_and_free(s_);
return std::make_tuple(std::forward<Path<GT>>(ret), i);
}
threshold += step;
}
}
else
relax_arcs(src, q);
}
if (const bool negative_cycle = last_relax_and_prepare_check_negative_cycle())
{
ret = search_negative_cycle_on_partial_graph();
if (ret.is_empty())
WARNING(
"Serious inconsistency. Bellman-Ford algorithm has detected\n"
"a negative cycle, but Tarjan algorithm executed on partial\n"
"graph has not found such cycle\n\n"
"Be very careful, this provably is a bug");
}