Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Bellman_Ford.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
72#ifndef BELLMAN_FORD_H
73#define BELLMAN_FORD_H
74
75# include <ah-graph-concepts.H>
76
77#include <cmath>
78#include <concepts>
79#include <type_traits>
80#include <limits>
81#include <vector>
82
83#include <tpl_array.H>
84#include <tpl_dynListQueue.H>
85#include <tpl_dynSetTree.H>
86#include <tpl_graph_utils.H>
87#include <tpl_dfs_stack.H>
88#include <Tarjan.H>
89#include <ah-errors.H>
90#include <ah_init_guard.H>
91#include <cookie_guard.H>
92
93namespace Aleph {
183template <AlephGraph GT,
184 ArcDistance<GT> Distance = Dft_Dist<GT>,
185 template <class, class> class Ait = Arc_Iterator,
186 template <class, class> class NAit = Out_Iterator,
187 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
189{
191
192 using Node = typename GT::Node;
193 using Arc = typename GT::Arc;
194
195 struct Sni
196 {
198 };
199
200 struct Ni : public Sni
201 {
202 int idx; // index in the predecessor arrays
203 size_t mark; // the walk that reached it, when a cycle is searched
204 };
205
206 static Distance_Type &accum(Node *p) noexcept
207 {
208 return static_cast<Sni *>(NODE_COOKIE(p))->accum;
209 }
210
211 static int &idx(Node *p) noexcept
212 {
213 return static_cast<Ni *>(NODE_COOKIE(p))->idx;
214 }
215
216 static size_t &mark(Node *p) noexcept
217 {
218 return static_cast<Ni *>(NODE_COOKIE(p))->mark;
219 }
220
221 // Checked addition to prevent integer overflow
223 {
224 if constexpr (std::is_integral_v<Distance_Type>)
225 {
226 // Check for positive overflow
227 ah_overflow_error_if(b > 0 && a > std::numeric_limits<Distance_Type>::max() - b)
228 << "Integer overflow in distance addition: " << a << " + " << b;
229
230 // Check for negative overflow (underflow)
231 ah_overflow_error_if(b < 0 && a < std::numeric_limits<Distance_Type>::min() - b)
232 << "Integer underflow in distance addition: " << a << " + " << b;
233 }
234
235 return a + b;
236 }
237
238 // Sets out to a + b and returns true; for an integral type whose sum goes
239 // beyond max(), no distance that fits goes through it: it returns false,
240 // and the painting remembers it in beyond_max_
241 [[gnu::always_inline]] bool add_if_fits(const Distance_Type &a,
242 const Distance_Type &b,
244 {
245 if constexpr (std::is_integral_v<Distance_Type>)
246 {
247 if (b > 0 and a > std::numeric_limits<Distance_Type>::max() - b) [[unlikely]]
248 {
249 beyond_max_ = true;
250 return false;
251 }
252 ah_overflow_error_if(b < 0 and a < std::numeric_limits<Distance_Type>::min() - b)
253 << "Integer underflow in distance addition: " << a << " + " << b;
254 }
255 out = a + b; // the checks of checked_add(), each once
256 return true;
257 }
258
259 // After a painting from start in which a sum went beyond max(): a node
260 // that start reaches through the arcs that the filter shows, and that has
261 // no distance, has one that does not fit
263 {
266 seen.insert(start);
267 queue.put(start);
268 while (not queue.is_empty())
269 {
270 Node *p = queue.get();
272 << "Bellman_Ford: the distance from the start to a node does not fit "
273 << "in its type";
274 // each arc from its source, as the relaxations read it
275 for (NAit<GT, SA> it(p, sa_); it.has_curr(); it.next_ne())
276 if (auto arc = it.get_curr(); g_.get_src_node(arc) == p)
277 if (Node *t = g_.get_tgt_node(arc); seen.insert(t) != nullptr)
278 queue.put(t);
279 }
280 }
281
282 // The arc that reached each node, by its index: contiguous, as every
283 // relaxation reads or writes it
285 GT &g_; // Non-const: algorithm modifies node/arc bits and cookies
287 bool painted_ = false;
288 bool parents_ = false; // the node cookies hold the parents in the tree
289 bool beyond_max_ = false; // a sum of the painting went beyond max()
290 Node *s_ = nullptr;
291 Node *relaxed_ = nullptr; // the last node that the last pass relaxed
292 SA sa_;
294
295 [[noreturn, gnu::noinline, gnu::cold]] static void throw_not_finite()
296 {
297 ah_domain_error() << "Bellman_Ford: a distance is -inf or NaN, "
298 << "from a weight or from an overflow";
299 }
300
306 [[gnu::always_inline]] bool relaxes(const Distance_Type &sum, const Distance_Type &accum) const
307 {
308 if constexpr (requires (const Distance &d)
309 { { d.tolerance() } -> std::convertible_to<Distance_Type>; })
310 {
311 if constexpr (std::is_integral_v<Distance_Type>)
312 {
313 const Distance_Type tol = dist_.tolerance();
314 if (accum == Inf)
315 return sum < accum;
316 return accum >= std::numeric_limits<Distance_Type>::lowest() + tol
317 and sum < accum - tol;
318 }
319 else
320 return sum < accum - dist_.tolerance();
321 }
322 else
323 return sum < accum;
324 }
325
330 [[gnu::always_inline]] static void check_finite(const Distance_Type &sum)
331 {
332 if constexpr (std::is_floating_point_v<Distance_Type>)
333 if (not (sum > -std::numeric_limits<Distance_Type>::infinity()))
335 }
336
341 {
342 Init_Guard guard([this]()
343 {
344 uninit<Ni>();
345 arcs_.empty();
346 });
347
348 const size_t n = g_.get_num_nodes();
349 arcs_.empty(); // Clear any previous data
350 arcs_.reserve(n);
351
352 typename GT::Node_Iterator it(g_);
353 for (size_t i = 0; it.has_curr(); ++i, it.next())
354 {
355 arcs_.append(nullptr); // the entry of index i
356 auto p = it.get_curr();
357 g_.reset_bit(p, Aleph::Spanning_Tree); // set bit to zero
358 NODE_COOKIE(p) = nullptr; // clear stale pointer before allocating
359 auto ptr = new Ni;
360 ptr->accum = start == nullptr ? Distance_Type(0) : Inf;
361 ptr->idx = static_cast<int>(i);
362 ptr->mark = 0;
363 NODE_BITS(p).set_bit(Spanning_Tree, false);
364 NODE_BITS(p).set_bit(Depth_First, false); // indicates if it is in queue
365 NODE_COOKIE(p) = ptr;
366 }
367
368 painted_ = false;
369 parents_ = false;
370 beyond_max_ = false;
371 relaxed_ = nullptr;
372 s_ = start;
373 if (s_ != nullptr)
374 accum(s_) = 0;
375
376 g_.reset_arcs();
377
378 guard.release(); // Successful initialization, prevent cleanup
379 }
380
383 void abandon() noexcept
384 {
385 uninit<Ni>();
386 arcs_.empty();
387 painted_ = false;
388 parents_ = false;
389 s_ = nullptr;
390 }
391
394 template <class Info_Type>
395 void uninit() noexcept
396 {
397 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next())
398 {
399 auto p = it.get_curr();
400 delete static_cast<Info_Type *>(NODE_COOKIE(p));
401 NODE_COOKIE(p) = nullptr;
402 NODE_BITS(p).set_bit(Depth_First, false);
403 }
404 }
405
419 {
420 if (s_ == nullptr)
421 return false;
422
423 size_t num_painted_arcs = 0;
424 size_t num_painted_nodes = 0;
425
426 // Count painted arcs
427 for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
428 if (IS_ARC_VISITED(it.get_curr(), Aleph::Spanning_Tree))
429 ++num_painted_arcs;
430
431 // Count painted nodes and verify each has exactly one incoming painted arc
432 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
433 {
434 auto node = it.get_curr();
436 continue;
437
438 ++num_painted_nodes;
439
440 // Skip root node - it should have no incoming painted arcs
441 if (node == s_)
442 continue;
443
444 // Count incoming painted arcs to this node
445 size_t incoming_count = 0;
446 for (Ait<GT, SA> ait(g_, sa_); ait.has_curr(); ait.next_ne())
447 if (auto arc = ait.get_curr();
449 ++incoming_count;
450
451 // Each non-root painted node must have exactly 1 incoming painted arc
452 if (incoming_count != 1)
453 return false;
454 }
455
456 // Tree property: #arcs == #nodes - 1
457 return num_painted_nodes != 0 and num_painted_arcs == num_painted_nodes - 1;
458 }
459
460public:
474 Bellman_Ford(GT &__g, Distance d = Distance(), SA __sa = SA())
475 : g_(__g), Inf(std::numeric_limits<Distance_Type>::max()), painted_(false), sa_(__sa), dist_(d)
476 {
477 // empty
478 }
479
500 void clear() noexcept(nothrow_arc_filter_v<GT, SA>)
501 {
502 if (painted_)
503 {
504 // Clear Spanning_Tree bits from all nodes and arcs
505 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
506 NODE_BITS(it.get_curr()).set_bit(Aleph::Spanning_Tree, false);
507
508 for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
509 ARC_BITS(it.get_curr()).set_bit(Aleph::Spanning_Tree, false);
510 }
511
512 arcs_.empty();
513 painted_ = false;
514 parents_ = false;
515 s_ = nullptr;
516 }
517
520 [[nodiscard]] bool has_computation() const noexcept
521 {
522 return s_ != nullptr;
523 }
524
527 [[nodiscard]] bool is_painted() const noexcept
528 {
529 return painted_;
530 }
531
534 Node *get_start_node() const noexcept
535 {
536 return s_;
537 }
538
541 const GT &get_graph() const noexcept
542 {
543 return g_;
544 }
545
546private:
553 {
554 const size_t &n = g_.vsize();
555 if (n <= 1)
556 return; // Nothing to relax for empty or single-node graphs
557
558 for (size_t i = 0; i < n - 1; ++i)
559 {
560 bool relaxed = false;
561 for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
562 {
563 auto arc = it.get_curr();
564 auto src = g_.get_src_node(arc);
565 const auto &accum_src = accum(src);
566 if (accum_src == Inf)
567 continue;
568
569 auto tgt = it.get_tgt_node_ne();
570 auto w = dist_(arc);
572 if (not add_if_fits(accum_src, w, sum))
573 continue; // no distance that fits goes through arc
574 auto &accum_tgt = accum(tgt);
575 if (relaxes(sum, accum_tgt)) // Relax Arc
576 {
577 const auto &index = idx(tgt);
578 arcs_(index) = arc;
579 accum_tgt = sum;
580 relaxed = true;
581 }
582 }
583 if (not relaxed)
584 return; // converged early
585 }
586 }
587
590 {
591 if (IS_NODE_VISITED(p, Depth_First)) // is already inside the queue?
592 return;
593 NODE_BITS(p).set_bit(Depth_First, true);
594 q.put(p);
595 }
596
599 {
600 auto ret = q.get();
601 assert(IS_NODE_VISITED(ret, Depth_First));
602 NODE_BITS(ret).set_bit(Depth_First, false);
603 return ret;
604 }
605
608 [[gnu::always_inline]] void relax_arcs(typename GT::Node *src,
610 {
611 for (NAit<GT, SA> it(src, sa_); it.has_curr(); it.next_ne())
612 {
613 auto arc = it.get_curr();
614 auto arc_src = g_.get_src_node(arc);
615 const auto &accum_src = accum(arc_src);
616 if (accum_src == Inf)
617 continue;
618
619 auto tgt = g_.get_tgt_node(arc);
620 auto w = dist_(arc);
622 if (not add_if_fits(accum_src, w, sum))
623 continue; // no distance that fits goes through arc
624 auto &accum_tgt = accum(tgt);
625 if (relaxes(sum, accum_tgt)) // Relax Arc
626 {
627 const auto &index = idx(tgt);
628 arcs_(index) = arc;
629 accum_tgt = sum;
630 put_in_queue(q, tgt);
631 }
632 }
633 }
634
636 void paint_tree() noexcept
637 { // paint the involved nodes and arcs
638 const size_t n = g_.vsize();
639 for (size_t i = 0; i < n; ++i)
640 {
641 auto arc = arcs_(i);
642 if (arc == nullptr)
643 continue;
644
645 ARC_BITS(arc).set_bit(Aleph::Spanning_Tree, true);
646 auto src = g_.get_src_node(arc);
647 auto tgt = g_.get_tgt_node(arc);
648 NODE_BITS(src).set_bit(Aleph::Spanning_Tree, true);
649 NODE_BITS(tgt).set_bit(Aleph::Spanning_Tree, true);
650 }
651 NODE_BITS(s_).set_bit(Aleph::Spanning_Tree, true);
652
653 painted_ = true;
654 }
655
660 {
661 bool negative_cycle = false;
662 for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
663 {
664 auto arc = it.get_curr();
665 auto src = g_.get_src_node(arc);
666 auto &accum_src = accum(src);
667 if (accum_src == Inf)
668 continue;
669
670 auto tgt = g_.get_tgt_node(arc);
671 auto d = dist_(arc);
672 auto &accum_tgt = accum(tgt);
674 if (not add_if_fits(accum_src, d, sum))
675 continue; // no distance that fits goes through arc
677 if (relaxes(sum, accum_tgt))
678 {
679 negative_cycle = true;
680 const auto &index = idx(tgt);
681 arcs_(index) = arc;
682 accum_tgt = sum;
683 relaxed_ = tgt;
684 }
685 }
686 return negative_cycle;
687 }
688
691 {
692 for (Ait<GT, SA> it(g_, sa_); it.has_curr(); it.next_ne())
693 {
694 auto arc = it.get_curr();
695 auto src = g_.get_src_node(arc);
696 auto &accum_src = accum(src);
697 if (accum_src == Inf)
698 continue;
699
700 auto tgt = g_.get_tgt_node(arc);
701 auto d = dist_(arc);
702 auto &accum_tgt = accum(tgt);
704 if (not add_if_fits(accum_src, d, sum))
705 continue; // no distance that fits goes through arc
707 if (relaxes(sum, accum_tgt))
708 return true;
709 }
710 return false;
711 }
712
714 void link_cookies_and_free(typename GT::Node *start) noexcept
715 {
716 uninit<Ni>();
717
718 // Construct the inverted paths to the start origin node
719 const size_t n = g_.vsize();
720 for (size_t i = 0; i < n; ++i)
721 {
722 auto arc = arcs_(i);
723 if (arc == nullptr)
724 continue;
725
726 auto tgt = g_.get_tgt_node(arc);
727 NODE_COOKIE(tgt) = g_.get_src_node(arc);
728 }
729
730 if (start != nullptr)
731 NODE_COOKIE(start) = nullptr; // just in case there is a negative cycle
732 parents_ = true;
733 }
734
738 {
739 if (s_ != nullptr)
740 put_in_queue(q, s_);
741 else
742 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
743 put_in_queue(q, it.get_curr());
744 }
745
748 Node *pred_node(Node *p) noexcept
749 {
750 auto arc = arcs_(idx(p));
751 return arc == nullptr ? nullptr : g_.get_src_node(arc);
752 }
753
762 {
763 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
764 mark(it.get_curr()) = 0;
765
766 size_t walk = 0;
767 auto cycle_reached_from = [&](Node *v) -> Node *
768 {
769 if (mark(v) != 0)
770 return nullptr; // an earlier walk went on from it
771 ++walk;
772 Node *p = v;
773 while (p != nullptr and mark(p) == 0)
774 {
775 mark(p) = walk;
776 p = pred_node(p);
777 }
778 return p != nullptr and mark(p) == walk ? p : nullptr;
779 };
780
781 Node *c = relaxed_ == nullptr ? nullptr : cycle_reached_from(relaxed_);
782 for (typename GT::Node_Iterator it(g_); c == nullptr and it.has_curr(); it.next_ne())
783 c = cycle_reached_from(it.get_curr());
784
785 if (c == nullptr)
786 return Path<GT>(g_);
787
788 DynList<Arc *> cycle; // its arcs from c, as they go
789 Node *p = c;
790 do
791 {
792 Arc *arc = arcs_(idx(p));
793 cycle.insert(arc);
794 p = g_.get_src_node(arc);
795 }
796 while (p != c);
797
798 Path<GT> ret(g_, c);
799 for (auto it = cycle.get_it(); it.has_curr(); it.next_ne())
800 ret.append_directed(it.get_curr());
801 return ret;
802 }
803
806 {
808 if (ret.is_empty())
809 {
810 WARNING(
811 "Serious inconsistency. Bellman-Ford algorithm has detected\n"
812 "a negative cycle, but the graph of the predecessors has no\n"
813 "cycle\n\n"
814 "Be very careful, this is provably a bug");
815 }
816 return ret;
817 }
818
819public:
830 {
831 ah_domain_error_if(start == nullptr) << "start node cannot be null";
832
833 init_with_indexes(start);
834 Init_Guard guard([this]() { abandon(); });
835
836 relax_arcs();
837 const bool negative_cycle = last_relax_and_prepare_check_negative_cycle();
838 if (beyond_max_ and not negative_cycle)
840 guard.release();
841
842 // Only paint the tree if there's no negative cycle
843 // A negative cycle makes the shortest path tree meaningless
844 if (not negative_cycle)
845 paint_tree();
846
848
849 // After the cookies are freed: the check calls the filter, which can
850 // throw
851 assert(negative_cycle or check_painted_arcs());
852
853 return negative_cycle;
854 }
855
869 {
870 ah_domain_error_if(start == nullptr) << "start node cannot be null";
871
872 init_with_indexes(start);
873 Init_Guard guard([this]() { abandon(); });
874
875 const auto &n = g_.get_num_nodes();
876
878
879 Node __sentinel;
880 Node *sentinel = &__sentinel;
881
882 put_in_queue(q, s_);
883 put_in_queue(q, sentinel);
884
885 for (size_t i = 0; not q.is_empty();)
886 {
887 auto src = get_from_queue(q);
888 if (src == sentinel) // Is the sentinel removed?
889 {
890 if (i++ > n)
891 break;
892
893 put_in_queue(q, sentinel);
894 }
895 else
896 relax_arcs(src, q);
897 }
898
899 const bool negative_cycle = last_relax_and_prepare_check_negative_cycle();
900 if (beyond_max_ and not negative_cycle)
902 guard.release();
903
904 // Only paint the tree if there's no negative cycle
905 // A negative cycle makes the shortest path tree meaningless
906 if (not negative_cycle)
907 paint_tree();
908
910
911 // After the cookies are freed: the check calls the filter, which can
912 // throw
913 assert(negative_cycle or check_painted_arcs());
914
915 return negative_cycle;
916 }
917
918public:
926 {
927 ah_domain_error_if(start == nullptr) << "start node cannot be null";
928
929 return detect_negative_cycle(start);
930 }
931
940 {
941 return detect_negative_cycle(nullptr);
942 }
943
944private:
946 {
947 init_with_indexes(start);
948 Init_Guard guard([this]() { abandon(); });
949
950 relax_arcs();
951 const bool negative_cycle = last_relax_and_test_negative_cycle();
952 if (beyond_max_ and not negative_cycle)
954 guard.release();
955 uninit<Ni>();
956
957 return negative_cycle;
958 }
959
962 {
963 init_with_indexes(start);
964 Init_Guard guard([this]() { abandon(); });
965
966 relax_arcs();
967 Path<GT> ret(g_);
970 else if (beyond_max_)
972 guard.release();
973
975 return ret;
976 }
977
981 std::tuple<Path<GT>, size_t> faster_find_negative_cycle(Node *start,
982 double it_factor,
983 size_t step)
984 {
985 init_with_indexes(start);
986 Init_Guard guard([this]() { abandon(); });
987
988 const auto &n = g_.get_num_nodes();
990 Node __sentinel;
991 Node *sentinel = &__sentinel;
993 put_in_queue(q, sentinel);
994
995 double threshold = it_factor * n;
996 Path<GT> ret(g_);
997
998 size_t i = 0;
999 while (not q.is_empty())
1000 {
1001 auto src = get_from_queue(q);
1002 if (src == sentinel)
1003 {
1004 if (i++ > n)
1005 break;
1006
1007 put_in_queue(q, sentinel);
1008 if (i >= threshold) // must I search negative cycles?
1009 {
1010 ret = cycle_of_predecessors();
1011 if (not ret.is_empty()) // negative cycle found?
1012 {
1013 guard.release();
1015 return std::make_tuple(std::move(ret), i);
1016 }
1017 threshold += step;
1018 }
1019 }
1020 else
1021 relax_arcs(src, q);
1022 }
1023
1025 ret = negative_cycle_witness();
1026 else if (beyond_max_)
1028 guard.release();
1029
1031 return std::make_tuple(std::move(ret), i);
1032 }
1033
1036 {
1037 init_with_indexes(start);
1038 Init_Guard guard([this]() { abandon(); });
1039
1040 const auto &n = g_.get_num_nodes();
1042 Node __sentinel;
1043 Node *sentinel = &__sentinel;
1045 put_in_queue(q, sentinel);
1046
1047 for (size_t i = 0; not q.is_empty(); /* nothing */)
1048 {
1049 auto src = get_from_queue(q);
1050 if (src == sentinel)
1051 {
1052 if (i++ > n)
1053 break;
1054
1055 put_in_queue(q, sentinel);
1056 }
1057 else
1058 relax_arcs(src, q);
1059 }
1060
1061 Path<GT> ret(g_);
1063 ret = negative_cycle_witness();
1064 else if (beyond_max_)
1066 guard.release();
1067
1069 return ret;
1070 }
1071
1072public:
1085 {
1086 ah_domain_error_if(start == nullptr) << "start node cannot be null";
1087
1088 return find_negative_cycle(start);
1089 }
1090
1100 {
1101 return find_negative_cycle(nullptr);
1102 }
1103
1147 std::tuple<Path<GT>, size_t> search_negative_cycle(Node *start, double it_factor, const size_t step)
1148 {
1149 ah_domain_error_if(start == nullptr) << "start node cannot be null";
1150
1151 return faster_find_negative_cycle(start, it_factor, step);
1152 }
1153
1162 {
1163 ah_domain_error_if(start == nullptr) << "start node cannot be null";
1164
1165 return faster_find_negative_cycle(start);
1166 }
1167
1177 std::tuple<Path<GT>, size_t> search_negative_cycle(double it_factor, const size_t step)
1178 {
1179 return faster_find_negative_cycle(nullptr, it_factor, step);
1180 }
1181
1186 {
1187 return faster_find_negative_cycle(nullptr);
1188 }
1189
1200 {
1201 ah_domain_error_if(not painted_) << "Spanning tree has not been painted";
1202
1203 DynArray<Arc *> ret;
1204 ret.reserve(arcs_.size());
1205 for (size_t i = 0; i < arcs_.size(); ++i)
1206 ret.touch(i) = arcs_(i);
1207 return ret;
1208 }
1209
1221 {
1222 ah_domain_error_if(not painted_) << "Graph has not been previously painted";
1223 ah_domain_error_if(not parents_) << "build_tree() mapped the tree; paint it again";
1224
1225 ah_domain_error_if(node == nullptr) << "node cannot be null";
1226
1227 // The arcs of the path, from node up to the start
1228 Dfs_Stack<Arc *> path;
1229 for (auto curr = node; curr != s_; )
1230 {
1231 auto parent = static_cast<Node *>(NODE_COOKIE(curr));
1232 ah_domain_error_if(parent == nullptr) << "Node is not reachable from start node";
1233
1234 // Find the arc from parent to curr
1235 for (NAit<GT, SA> it(parent, sa_); it.has_curr(); it.next_ne())
1236 if (auto arc = it.get_curr();
1237 g_.get_tgt_node(arc) == curr && IS_ARC_VISITED(arc, Aleph::Spanning_Tree))
1238 {
1239 path.push(arc);
1240 break;
1241 }
1242 curr = parent;
1243 }
1244
1245 // From the start, so that each partial sum is the distance of a node of
1246 // the path, which fits; from node, a sum could leave Distance_Type
1247 Distance_Type total = 0;
1248 for (; not path.is_empty(); path.pop())
1249 total = checked_add(total, dist_(path.top()));
1250 return total;
1251 }
1252
1266 void build_tree(GT &tree, bool with_map = true)
1267 {
1268 ah_domain_error_if(not painted_) << "Spanning tree has not been painted";
1269 ah_domain_error_if(not parents_) << "build_tree() mapped the tree; paint it again";
1270
1271 clear_graph(tree);
1272
1274 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
1275 {
1276 auto gp = it.get_curr();
1277 auto tp = tree.insert_node(gp->get_info());
1278 table.insert(gp, tp);
1279 }
1280
1281 for (typename GT::Node_Iterator it(g_); it.has_curr(); it.next_ne())
1282 {
1283 auto gtgt = it.get_curr();
1284 auto gsrc = static_cast<Node *>(NODE_COOKIE(gtgt));
1285 if (gsrc == nullptr)
1286 continue; // This is the source node of the spanning tree
1287
1288 // Find the spanning tree arc from gsrc to gtgt
1289 Arc *garc = nullptr;
1290 for (Out_Iterator<GT, SA> ait(gsrc, sa_); ait.has_curr(); ait.next_ne())
1291 {
1292 auto a = ait.get_curr();
1294 {
1295 garc = a;
1296 break;
1297 }
1298 }
1299 ah_logic_error_unless(garc != nullptr) << "Arc not found between nodes in spanning tree";
1300
1301 auto tsrc_ptr = table.search(gsrc);
1302 auto ttgt_ptr = table.search(gtgt);
1303 ah_logic_error_unless(tsrc_ptr) << "Source node not found in mapping table";
1304 ah_logic_error_unless(ttgt_ptr) << "Target node not found in mapping table";
1305 auto tarc = tree.insert_arc(tsrc_ptr->second, ttgt_ptr->second, garc->get_info());
1306 if (with_map)
1307 {
1308 ARC_COOKIE(garc) = nullptr; // else it would compose with a former tree
1309 GT::map_arcs(garc, tarc);
1310 }
1311 }
1312
1313 // the cookies of the nodes held their parents, already used
1314 if (with_map)
1315 table.for_each([](const auto &p)
1316 {
1317 NODE_COOKIE(p.first) = nullptr;
1318 GT::map_nodes(p.first, p.second);
1319 });
1320 parents_ = parents_ and not with_map;
1321 }
1322
1329 bool test_negative_cycle(typename GT::Node *s, Path<GT> &cycle)
1330 {
1331 cycle = test_negative_cycle(s);
1332 return not cycle.is_empty();
1333 }
1334
1341 {
1342 cycle = test_negative_cycle();
1343 return not cycle.is_empty();
1344 }
1345
1354 {
1355 ah_domain_error_if(not painted_) << "Graph has not been previously painted";
1356 ah_domain_error_if(not parents_) << "build_tree() mapped the tree; paint it again";
1357
1358 return Aleph::get_min_path<GT, Distance>(s_, end, path, dist_);
1359 }
1360
1372 {
1373 init_with_indexes(nullptr);
1374 Init_Guard guard([this]() { abandon(); });
1375
1376 const auto &n = g_.get_num_nodes();
1377
1379
1380 Node __sentinel;
1381 Node *sentinel = &__sentinel;
1382
1384 put_in_queue(q, sentinel);
1385
1386 for (size_t i = 0; not q.is_empty(); /* nothing */)
1387 {
1388 auto src = get_from_queue(q);
1389 if (src == sentinel) // Is the sentinel removed?
1390 {
1391 if (i++ > n)
1392 break;
1393 put_in_queue(q, sentinel);
1394 }
1395 else
1396 relax_arcs(src, q);
1397 }
1398
1399 const bool negative_cycle = last_relax_and_prepare_check_negative_cycle();
1400
1402
1403 // build mapping if there are no negative cycles
1404 if (not negative_cycle)
1405 for (auto it = g_.get_node_it(); it.has_curr(); it.next_ne())
1406 {
1407 auto p = it.get_curr();
1408 ret.insert(p, accum(p));
1409 }
1410
1411 guard.release();
1412 abandon(); // the data of the nodes go, and the object has no computation
1413
1414 ah_domain_error_if(negative_cycle) << "negative cycles detected";
1415
1416 return ret;
1417 }
1418};
1419
1438template <AlephGraph GT,
1439 ArcDistance<GT> Distance = Dft_Dist<GT>,
1440 template <class, class> class Ait = Arc_Iterator,
1441 template <class, class> class NAit = Node_Arc_Iterator,
1442 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1444{
1455 bool operator()(GT &g, Path<GT> &path, Distance &d, SA &sa) const
1456 {
1458 }
1459
1460 bool operator()(GT &g, Path<GT> &path, Distance &&d = Distance(), SA &&sa = SA()) const
1461 {
1463 }
1464
1476 bool operator()(GT &g, typename GT::Node *s, Path<GT> &path, Distance &d, SA &sa) const
1477 {
1479 }
1480
1482 typename GT::Node *s,
1483 Path<GT> &path,
1484 Distance &&d = Distance(),
1485 SA &&sa = SA()) const
1486 {
1488 }
1489
1498 Path<GT> operator()(GT &g, typename GT::Node *s, Distance &d, SA &sa) const
1499 {
1501 }
1502
1504 Path<GT> operator()(GT &g, typename GT::Node *s, Distance &&d = Distance(), SA &&sa = SA()) const
1505 {
1507 }
1508
1516 Path<GT> operator()(GT &g, Distance &d, SA &sa) const
1517 {
1519 }
1520
1522 Path<GT> operator()(GT &g, Distance &&d = Distance(), SA &&sa = SA()) const
1523 {
1525 }
1526};
1527} // end namespace Aleph
1528
1529#endif // BELLMAN_FORD_H
Tarjan's algorithm for strongly connected components.
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error()
Throws std::domain_error unconditionally.
Definition ah-errors.H:702
#define ah_logic_error_unless(C)
Throws std::logic_error if condition does NOT hold.
Definition ah-errors.H:458
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
C++20 concepts for the protocol shared by graph algorithms.
#define WARNING(...)
Print a warning message (no-op when MESSAGES is not defined).
Definition ahDefs.H:262
RAII guard for exception-safe resource cleanup.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double w
Definition btreepic.C:153
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void empty() noexcept
Empties the container.
Definition tpl_array.H:426
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
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.
void init_with_indexes(Node *start)
Initialize node cookies with predecessor tracking for path reconstruction.
Path< GT > negative_cycle_witness()
The witness of a negative cycle that the last pass found.
bool has_computation() const noexcept
Check if a shortest-path tree has been computed or painted.
bool last_relax_and_prepare_check_negative_cycle()
Perform one more relaxation pass and check for negative cycle.
bool check_painted_arcs() noexcept(nothrow_arc_filter_v< GT, SA >)
Check that painted arcs form a valid spanning tree structure.
static void throw_not_finite()
bool faster_paint_spanning_tree(Node *start)
Faster shortest paths tree painting from a start node.
void link_cookies_and_free(typename GT::Node *start) noexcept
Free node cookies and set up predecessor pointers for path reconstruction.
bool relaxes(const Distance_Type &sum, const Distance_Type &accum) const
Whether sum relaxes the distance accum: it is below it, by more than the tolerance of the distance,...
void relax_arcs()
Relax all arcs up to n-1 times (standard Bellman-Ford).
const Distance_Type Inf
DynMapTree< Node *, Distance_Type > compute_nodes_weights()
Returns a mapping with the shortest distances to each node obtained after executing the Bellman-Ford ...
Path< GT > search_negative_cycle(Node *start)
Searches a negative cycle using the faster version of Bellman-Ford algorithm (SPFA variant).
bool test_negative_cycle(typename GT::Node *s, Path< GT > &cycle)
Test for negative cycle and return it if found.
void check_beyond_max(Node *start)
std::tuple< Path< GT >, size_t > faster_find_negative_cycle(Node *start, double it_factor, size_t step)
SPFA, which, from it_factor * n rounds, and then every step rounds, looks for a cycle among the prede...
static GT::Node * get_from_queue(DynListQueue< typename GT::Node * > &q)
Remove a node from the queue and clear its in-queue flag.
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
bool detect_negative_cycle(Node *start)
void uninit() noexcept
Release the memory associated with the node cookies, and the bits Depth_First that SPFA leaves on the...
Path< GT > search_negative_cycle()
See search_negative_cycle(Node * start).
Path< GT > test_negative_cycle()
Searches and returns a negative cycle (if it exists).
void clear() noexcept(nothrow_arc_filter_v< GT, SA >)
Clear the painted state and reset internal data structures.
void paint_tree() noexcept
Paint the spanning tree nodes and arcs with the Spanning_Tree bit.
std::tuple< Path< GT >, size_t > search_negative_cycle(double it_factor, const size_t step)
Searches a negative cycle using the faster version of Bellman-Ford algorithm and iteratively searchin...
Path< GT > cycle_of_predecessors()
A cycle of the graph of the predecessors, the arcs of the last relaxations, as a path of its arcs; em...
void put_sources_in_queue(DynListQueue< typename GT::Node * > &q)
Put in q the start, or, without one, every node, as the virtual source reaches them.
typename GT::Node Node
bool is_painted() const noexcept
Check if a shortest-path tree has been painted.
void abandon() noexcept
Leave the object without a computation, and the graph without the data of the nodes,...
bool add_if_fits(const Distance_Type &a, const Distance_Type &b, Distance_Type &out)
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()
Test if a negative cycle exists anywhere in the graph.
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
bool last_relax_and_test_negative_cycle()
Perform one more relaxation pass to detect (but not prepare) negative cycle.
void relax_arcs(typename GT::Node *src, DynListQueue< typename GT::Node * > &q)
Relax outgoing arcs from a source node (SPFA variant).
static void put_in_queue(DynListQueue< typename GT::Node * > &q, typename GT::Node *p)
Insert a node into the queue if not already present (SPFA optimization).
Array< typename GT::Arc * > arcs_
static Distance_Type & accum(Node *p) noexcept
Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extract the shortest path to a node from a previously painted tree.
bool test_negative_cycle(Path< GT > &cycle)
Test for negative cycle anywhere in the graph.
Node * pred_node(Node *p) noexcept
The source of the arc by which the last relaxation of p reached it, or nullptr.
static int & idx(Node *p) noexcept
Bellman_Ford(GT &__g, Distance d=Distance(), SA __sa=SA())
Construct a Bellman-Ford executor.
const GT & get_graph() const noexcept
Get reference to the graph.
Path< GT > faster_find_negative_cycle(Node *start)
SPFA; without a start, every node is a source.
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.
Path< GT > find_negative_cycle(Node *start)
Without a start, every node is a source.
Distance_Type checked_add(const Distance_Type &a, const Distance_Type &b) const
void build_tree(GT &tree, bool with_map=true)
Extract from the graph a previously painted shortest paths tree.
typename GT::Arc Arc
Distance::Distance_Type Distance_Type
static void check_finite(const Distance_Type &sum)
Throw domain_error if a floating sum of the last pass is -inf or NaN, from a weight or from an overfl...
static size_t & mark(Node *p) noexcept
Stack of the frames of a depth-first search that does not recurse.
T & push(Args &&...args)
Builds a frame on top of the stack.
bool is_empty() const noexcept
Whether the stack has no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
Default distance accessor for arc weights.
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
T & touch(const size_t i)
Touch the entry i.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & insert(const T &item)
Definition htlist.H:1308
Generic key-value map implemented on top of a binary search tree.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Dynamic set backed by balanced binary search trees with automatic memory management.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
RAII guard for graph algorithm initialization.
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
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Path on a graph.
Definition tpl_graph.H:3832
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
void append_directed(Node *p)
Append a node to a directed path.
Definition tpl_graph.H:4124
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1213
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
static void map_arcs(A1 *p, A2 *q) noexcept
Map the arcs through their cookies.
Definition graph-dry.H:1312
void reset_bit(Node *node, int bit) const noexcept
Reset the bit of node (to zero)
Definition graph-dry.H:1087
constexpr size_t vsize() const noexcept
See get_num_nodes().
Definition graph-dry.H:984
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
static void map_nodes(N1 *p, N2 *q) noexcept
Map the nodes through their cookies.
Definition graph-dry.H:1281
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
RAII guards for graph node/arc cookies.
__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
constexpr bool nothrow_arc_filter_v
Whether a filter of type SA of the arcs of GT is copied, moved and called without exceptions: then an...
Definition tpl_graph.H:1043
#define ARC_COOKIE(p)
Return the arc cookie
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
Definition tpl_graph.H:4776
#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.
@ Depth_First
Definition aleph-graph.H:73
@ Spanning_Tree
Definition aleph-graph.H:79
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Detects if a negative cycle exists and eventually computes it.
Path< GT > operator()(GT &g, typename GT::Node *s, Distance &d, SA &sa) const
Search for a negative cycle starting from a specific node.
bool operator()(GT &g, typename GT::Node *s, Path< GT > &path, Distance &&d=Distance(), SA &&sa=SA()) const
Path< GT > operator()(GT &g, Distance &&d=Distance(), SA &&sa=SA()) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
bool operator()(GT &g, Path< GT > &path, Distance &d, SA &sa) const
Invokes the detection and calculation of a negative cycle.
bool operator()(GT &g, typename GT::Node *s, Path< GT > &path, Distance &d, SA &sa) const
Invokes the detection and calculation of a negative cycle.
Path< GT > operator()(GT &g, Distance &d, SA &sa) const
Search for a negative cycle in the entire graph.
Path< GT > operator()(GT &g, typename GT::Node *s, Distance &&d=Distance(), SA &&sa=SA()) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
bool operator()(GT &g, Path< GT > &path, Distance &&d=Distance(), SA &&sa=SA()) const
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Distance accessor.
Dynamic array container with automatic resizing.
Stack of the frames of a depth-first search that does not recurse.
Dynamic queue implementation based on linked lists.
Dynamic set implementations based on balanced binary search trees.
Utility algorithms and operations for graphs.