Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Negative_Cycles.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
32
161# ifndef NEGATIVE_CYCLES_H
162# define NEGATIVE_CYCLES_H
163
164# include <ah-graph-concepts.H>
165
166# include <algorithm>
167# include <bit>
168# include <cfloat>
169# include <cmath>
170# include <cstddef>
171# include <cstdint>
172# include <limits>
173# include <type_traits>
174# include <utility>
175
176# include <ah-errors.H>
177# include <htlist.H>
178# include <shortest_path_common.H>
179# include <tpl_array.H>
180# include <tpl_graph.H>
181
182namespace Aleph
183{
190 {
196
204 };
205
217 {
225 Exact,
226
233 Rounded
234 };
235
242 template <AlephGraph GT, typename Cost_Type>
244 {
246 Cost_Type total_cost = Cost_Type{0};
247 size_t length = 0;
248 };
249
260 template <AlephGraph GT, typename Cost_Type>
262 {
263 bool has_cycle = false;
264
287 bool is_exact = false;
288
301
312 Cost_Type optimality_gap = Cost_Type{0};
313
316
317 Cost_Type total_cost = Cost_Type{0};
318 size_t length = 0;
321
323 [[nodiscard]] bool is_negative() const noexcept
324 {
325 return has_cycle and total_cost < Cost_Type{0};
326 }
327 };
328
342 template <AlephGraph GT, typename Cost_Type>
344 {
345 bool has_cycle = false;
346 Cost_Type total_cost = Cost_Type{0};
347 size_t length = 0;
350
354 [[nodiscard]] bool is_negative() const noexcept
355 {
356 return has_cycle and total_cost < Cost_Type{0};
357 }
358 };
359
360 namespace negative_cycles_detail
361 {
368 template <AlephGraph GT, typename Cost_Type>
369 struct Arc_Rec
370 {
371 size_t src = 0;
372 size_t tgt = 0;
373 typename GT::Arc * arc = nullptr;
374 Cost_Type weight = Cost_Type{0};
375 };
376
383 template <AlephGraph GT, typename Cost_Type>
385 {
387 Array<Arc_Rec<GT, Cost_Type>> arcs; // accepted arcs, in Arc_Iterator order
388 };
389
390 template <typename Cost_Type>
391 inline void check_finite([[maybe_unused]] const Cost_Type & value,
392 [[maybe_unused]] const char * context)
393 {
394 if constexpr (std::is_floating_point_v<Cost_Type>)
395 ah_domain_error_if(not std::isfinite(value)) << context;
396 }
397
406# if defined(FLT_EVAL_METHOD) and FLT_EVAL_METHOD != 0
407 template <typename T>
408 using exact_float_t = long double;
409# else
410 template <typename T>
412# endif
413
430 template <typename F>
431 inline void two_sum(const F a, const F b, F & s, F & e) noexcept
432 {
433 s = a + b;
434 const F b_virtual = s - a;
435 e = (a - (s - b_virtual)) + (b - b_virtual);
436 if (not std::isfinite(e)) [[unlikely]]
437 e = std::fabs(a) >= std::fabs(b) ? b - (s - a) : a - (s - b);
438 }
439
455 template <typename T>
457 {
458 public:
461
462 private:
463 Array<Component> h_; // h_(0) .. h_(n_ - 1): nonzero components, increasing magnitude
464 Array<Component> g_; // scratch of compress() and upper()
465 size_t n_ = 0;
466
467 static void put(Array<Component> & a, const size_t i, const Component x)
468 {
469 if (i < a.size())
470 a(i) = x;
471 else
472 a.append(x);
473 }
474
475 // Add b to a(0 .. n - 1). Inside Grow-Expansion a partial sum can
476 // overflow although the value fits: b near the largest finite value,
477 // lower components of its sign, a higher one of the other sign. The
478 // lower components of an expansion add up to less than the lowest bit
479 // of the next one, at most half the range, so with |b| at most a
480 // quarter of it every partial sum stays below three quarters: a larger
481 // b is added as four exact quarters, and only the value itself (within
482 // one unit in the last place of the largest finite number, or beyond)
483 // can overflow.
484 static bool grow(Array<Component> & a, size_t & n, const Component b)
485 {
486 constexpr Component quarter_of_max = std::numeric_limits<Component>::max() / 4;
487 if (not (std::fabs(b) > quarter_of_max)) // NaN included: it fails below
488 return grow_expansion(a, n, b);
489 const Component quarter = b / 4; // exact: |b| is far above the subnormals
490 for (int i = 0; i < 4; ++i)
491 if (not grow_expansion(a, n, quarter))
492 return false;
493 return true;
494 }
495
496 // Shewchuk's Grow-Expansion with zero elimination on a(0 .. n - 1).
497 static bool grow_expansion(Array<Component> & a, size_t & n, const Component b)
498 {
499 Component q = b;
500 size_t k = 0;
501 for (size_t i = 0; i < n; ++i)
502 {
503 Component s, e;
504 two_sum(q, a(i), s, e);
505 q = s;
506 if (e != Component(0))
507 a(k++) = e;
508 }
509 n = k;
510 if (q != Component(0))
511 put(a, n++, q);
512 return std::isfinite(q);
513 }
514
515 public:
517 void clear() noexcept
518 {
519 n_ = 0;
520 }
521
523 [[nodiscard]] bool is_zero() const noexcept
524 {
525 return n_ == 0;
526 }
527
529 [[nodiscard]] int sign() const noexcept
530 {
531 return n_ == 0 ? 0 : (h_(n_ - 1) < Component(0) ? -1 : 1);
532 }
533
540 [[nodiscard]] bool add(const Component b)
541 {
542 return grow(h_, n_, b);
543 }
544
552 [[nodiscard]] bool add(const Exact_Sum & x, const int exponent = 0, const bool negate = false)
553 {
554 ah_invalid_argument_if(&x == this) << "Exact_Sum::add(): a sum cannot be added to itself";
555 for (size_t i = 0; i < x.n_; ++i)
556 {
557 const Component c = std::ldexp(x.h_(i), exponent);
558 if (not add(negate ? -c : c))
559 return false;
560 }
561 return true;
562 }
563
571 [[nodiscard]] bool add_multiple(const Exact_Sum & x, size_t factor, const bool negate = false)
572 {
573 for (int bit = 0; factor != 0; ++bit, factor >>= 1)
574 if ((factor & 1) != 0 and not add(x, bit, negate))
575 return false;
576 return true;
577 }
578
581 void compress()
582 {
583 if (n_ < 2)
584 return;
585 while (g_.size() < n_)
586 g_.append(Component(0));
587
588 Component q = h_(n_ - 1);
589 size_t bottom = n_ - 1;
590 for (size_t i = n_ - 1; i-- > 0; )
591 {
592 Component s, e;
593 two_sum(q, h_(i), s, e);
594 if (e != Component(0))
595 {
596 g_(bottom--) = s;
597 q = e;
598 }
599 else
600 q = s;
601 }
602 g_(bottom) = q;
603
604 size_t top = 0;
605 for (size_t i = bottom + 1; i < n_; ++i)
606 {
607 Component s, e;
608 two_sum(g_(i), q, s, e);
609 if (e != Component(0))
610 h_(top++) = e;
611 q = s;
612 }
613 h_(top++) = q;
614 n_ = top;
615 }
616
623 [[nodiscard]] T rounded()
624 {
625 compress();
626 return n_ == 0 ? T(0) : static_cast<T>(h_(n_ - 1));
627 }
628
633 [[nodiscard]] T upper()
634 {
635 for (size_t i = 0; i < n_; ++i)
636 if (not std::isfinite(h_(i)))
637 return std::numeric_limits<T>::infinity();
638 T b = rounded();
639 for (;;)
640 {
641 if (b == std::numeric_limits<T>::infinity())
642 return b; // no finite bound; -b would not be finite either
643 size_t n = n_; // value - b, computed exactly in g_
644 for (size_t i = 0; i < n_; ++i)
645 put(g_, i, h_(i));
646 const bool finite = grow(g_, n, -static_cast<Component>(b));
647 if (finite and (n == 0 or g_(n - 1) < Component(0)))
648 return b; // value <= b
649 b = std::nextafter(b, std::numeric_limits<T>::infinity());
650 }
651 }
652 };
653
662 template <typename T>
663 void bit_span(const T x, int & low, int & high) noexcept
664 {
665 if constexpr (std::numeric_limits<T>::is_iec559
666 and (std::is_same_v<T, double> or std::is_same_v<T, float>))
667 {
668 // Read the fields: |x| = m * 2^e with m the integer significand.
669 using Bits = std::conditional_t<std::is_same_v<T, double>, std::uint64_t, std::uint32_t>;
670 constexpr int fraction_bits = std::numeric_limits<T>::digits - 1;
671 constexpr int exponent_mask = std::is_same_v<T, double> ? 0x7FF : 0xFF;
672 constexpr int bias = std::numeric_limits<T>::max_exponent - 1;
673 const Bits bits = std::bit_cast<Bits>(x);
674 const Bits fraction = bits & ((Bits(1) << fraction_bits) - 1);
675 const int biased = static_cast<int>((bits >> fraction_bits) & Bits(exponent_mask));
676 const Bits m = biased == 0 ? fraction : (fraction | (Bits(1) << fraction_bits));
677 const int e = (biased == 0 ? 1 : biased) - bias - fraction_bits;
678 low = e + std::countr_zero(m);
679 high = e + static_cast<int>(sizeof(Bits) * 8) - 1 - std::countl_zero(m);
680 }
681 else
682 {
683 int e = 0;
684 const T f = std::frexp(std::fabs(x), &e); // |x| = f * 2^e, f in [0.5, 1)
685 constexpr int digits = std::numeric_limits<T>::digits;
686 T m = std::ldexp(f, digits); // an integer in [2^(digits - 1), 2^digits)
687 int zeros = 0;
688 if constexpr (digits <= 64)
689 zeros = std::countr_zero(static_cast<unsigned long long>(m));
690 else
691 while (std::fmod(m, T(2)) == T(0))
692 {
693 m /= T(2);
694 ++zeros;
695 }
696 low = e - digits + zeros;
697 high = e - 1;
698 }
699 }
700
707 template <typename T>
708 std::uint64_t odd_significand(const T x) noexcept
709 {
710 static_assert(std::numeric_limits<T>::digits <= 64,
711 "odd_significand(): the significand must fit 64 bits");
712 if constexpr (std::numeric_limits<T>::is_iec559
713 and (std::is_same_v<T, double> or std::is_same_v<T, float>))
714 {
715 using Bits = std::conditional_t<std::is_same_v<T, double>, std::uint64_t, std::uint32_t>;
716 constexpr int fraction_bits = std::numeric_limits<T>::digits - 1;
717 constexpr int exponent_mask = std::is_same_v<T, double> ? 0x7FF : 0xFF;
718 const Bits bits = std::bit_cast<Bits>(x);
719 const Bits fraction = bits & ((Bits(1) << fraction_bits) - 1);
720 const bool subnormal = ((bits >> fraction_bits) & Bits(exponent_mask)) == 0;
721 const Bits m = subnormal ? fraction : (fraction | (Bits(1) << fraction_bits));
722 return static_cast<std::uint64_t>(m >> std::countr_zero(m));
723 }
724 else
725 {
726 int low = 0;
727 int high = 0;
728 bit_span(x, low, high);
729 return static_cast<std::uint64_t>(std::ldexp(std::fabs(x), -low));
730 }
731 }
732
751 template <AlephGraph GT, typename Cost_Type>
753 const Array<size_t> & arcs,
754 const char * context)
755 {
756 if constexpr (std::is_floating_point_v<Cost_Type>)
757 {
759 for (size_t i = 0; i < arcs.size(); ++i)
760 ah_domain_error_if(not sum.add(ig.arcs(arcs(i)).weight)) << context;
761 const Cost_Type total = sum.rounded();
762 ah_domain_error_if(not std::isfinite(total)) << context;
763 return total;
764 }
765 else
766 {
767 Cost_Type sum = Cost_Type{0};
768 for (size_t i = 0; i < arcs.size(); ++i)
770 return sum;
771 }
772 }
773
792 template <AlephGraph GT, typename Cost_Type>
793 bool short_sums_are_exact(const Indexed_Graph<GT, Cost_Type> & ig, const size_t L,
794 Cost_Type & error_bound)
795 {
796 static_assert(std::is_floating_point_v<Cost_Type>);
797 constexpr int digits = std::numeric_limits<Cost_Type>::digits;
798 constexpr Cost_Type inf = std::numeric_limits<Cost_Type>::infinity();
799
800 bool any = false;
801 int low_min = 0;
802 int high_max = 0;
803 Cost_Type max_abs = Cost_Type{0};
804 for (size_t a = 0; a < ig.arcs.size(); ++a)
805 {
806 const Cost_Type w = ig.arcs(a).weight;
807 if (w == Cost_Type{0})
808 continue;
809 int low = 0;
810 int high = 0;
811 bit_span(w, low, high);
812 low_min = any ? std::min(low_min, low) : low;
813 high_max = any ? std::max(high_max, high) : high;
814 max_abs = std::max(max_abs, std::fabs(w));
815 any = true;
816 }
817
818 error_bound = Cost_Type{0};
819 if (not any or L < 2)
820 return true; // all zero, or single weights: nothing is ever rounded
821 if (high_max + 1 + static_cast<int>(std::bit_width(L - 1)) <= digits + low_min)
822 return true;
823
824 // 2 (L - 1) L u max|w|, every step rounded up; u = 2^-digits.
825 const Cost_Type factor = std::nextafter(static_cast<Cost_Type>(2.0L * static_cast<long double>(L - 1)
826 * static_cast<long double>(L)), inf);
827 const Cost_Type scaled = std::ldexp(max_abs, -digits) + std::numeric_limits<Cost_Type>::denorm_min();
828 error_bound = std::nextafter(factor * scaled, inf);
829 return false;
830 }
831
846 template <typename Node>
848 {
851 size_t mask_ = 0;
852
853 static size_t slot_of(const Node * node) noexcept
854 {
855 auto x = reinterpret_cast<std::uintptr_t>(node);
856 x += 0x9e3779b97f4a7c15ULL;
857 x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
858 x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
859 return x ^ (x >> 31);
860 }
861
862 public:
866 explicit Node_Index(const size_t n)
867 {
868 ah_overflow_error_if(n > (std::numeric_limits<size_t>::max() >> 2))
869 << "Node_Index: capacity overflow";
870 size_t capacity = 4;
871 while (capacity < 2 * n)
872 capacity <<= 1;
873 keys_ = Array<Node *>(capacity, nullptr);
874 positions_ = Array<size_t>(capacity, size_t{0});
875 mask_ = capacity - 1;
876 }
877
881 void insert(Node * node, const size_t position)
882 {
883 ah_domain_error_if(node == nullptr) << "Node_Index: null node";
884 size_t i = slot_of(node) & mask_;
885 while (keys_(i) != nullptr)
886 i = (i + 1) & mask_;
887 keys_(i) = node;
888 positions_(i) = position;
889 }
890
896 [[nodiscard]] size_t find(const Node * node) const
897 {
898 ah_domain_error_if(node == nullptr) << "Node_Index: null node";
899 size_t i = slot_of(node) & mask_;
900 while (keys_(i) != node)
901 {
902 ah_domain_error_if(keys_(i) == nullptr)
903 << "Node_Index: the arc endpoint is not a node of the graph";
904 i = (i + 1) & mask_;
905 }
906 return positions_(i);
907 }
908 };
909
913 template <AlephGraph GT, ArcDistance<GT> Distance, ArcFilter<GT> SA>
914 Indexed_Graph<GT, typename Distance::Distance_Type>
915 index_graph(const GT & g, Distance & distance, SA & sa, const char * fn)
916 {
917 using Node = typename GT::Node;
918 using Arc = typename GT::Arc;
919 using Cost_Type = typename Distance::Distance_Type;
920
921 static_assert(std::is_arithmetic_v<Cost_Type>,
922 "negative cycle search requires arithmetic arc costs");
923
924 ah_domain_error_if(not g.is_digraph()) << fn << "(): graph must be directed";
925
927 const size_t n = g.get_num_nodes();
928 ig.nodes.reserve(n);
929
930 Node_Index<Node> node_to_idx(n);
931 size_t idx = 0;
932 for (Node_Iterator<GT> it(g); it.has_curr(); it.next_ne(), ++idx)
933 {
934 Node * node = it.get_curr_ne();
935 ig.nodes.append(node);
936 node_to_idx.insert(node, idx);
937 }
938
939 ig.arcs.reserve(g.get_num_arcs());
940 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
941 {
942 Arc * arc = it.get_curr_ne();
943 const Cost_Type w = distance(arc);
944 check_finite(w, "negative cycle search requires finite arc weights");
945 ig.arcs.append(Arc_Rec<GT, Cost_Type>{node_to_idx.find(g.get_src_node(arc)),
946 node_to_idx.find(g.get_tgt_node(arc)),
947 arc, w});
948 }
949
950 return ig;
951 }
952
970 template <AlephGraph GT, typename Cost_Type>
972 const Array<long> & pred,
973 Array<long> & mark)
974 {
975 const size_t n = mark.size();
976 for (size_t i = 0; i < n; ++i)
977 mark(i) = 0;
978
979 long chain = 0;
980 for (size_t s = 0; s < n; ++s)
981 {
982 if (mark(s) != 0)
983 continue;
984
985 ++chain;
986 for (size_t v = s; ; )
987 {
988 mark(v) = chain;
989 const long a = pred(v);
990 if (a == -1)
991 break;
992 const size_t u = ig.arcs(static_cast<size_t>(a)).src;
993 if (mark(u) == chain)
994 return static_cast<long>(u); // u closes a cycle of this chain
995 if (mark(u) != 0)
996 break; // joins an older chain, already known to be cycle-free
997 v = u;
998 }
999 }
1000 return -1;
1001 }
1010 template <typename Cost_Type>
1018
1023 template <AlephGraph GT, typename Cost_Type>
1025 {
1026 const size_t n = ig.nodes.size();
1027 const size_t m = ig.arcs.size();
1028
1030 adj.start = Array<size_t>(n + 1, 0);
1031 for (size_t a = 0; a < m; ++a)
1032 ++adj.start(ig.arcs(a).src + 1);
1033 for (size_t i = 0; i < n; ++i)
1034 adj.start(i + 1) += adj.start(i);
1035
1036 adj.arc = Array<size_t>(m, 0);
1037 adj.tgt = Array<size_t>(m, 0);
1038 adj.weight = Array<Cost_Type>(m, Cost_Type{0});
1039 Array<size_t> fill(n, 0);
1040 for (size_t a = 0; a < m; ++a)
1041 {
1042 const auto & rec = ig.arcs(a);
1043 const size_t p = adj.start(rec.src) + fill(rec.src)++;
1044 adj.arc(p) = a;
1045 adj.tgt(p) = rec.tgt;
1046 adj.weight(p) = rec.weight;
1047 }
1048 return adj;
1049 }
1050
1077 template <AlephGraph GT, typename Cost_Type>
1079 const Out_Adjacency<Cost_Type> & adj,
1081 {
1082 constexpr size_t unset = std::numeric_limits<size_t>::max();
1083 const size_t n = ig.nodes.size();
1084 const size_t m = ig.arcs.size();
1085 const Array<size_t> & start = adj.start;
1086
1087 // Iterative Tarjan: `next(v)` is the position of the next arc of v to examine.
1088 Array<size_t> order(n, unset);
1089 Array<size_t> low(n, 0);
1090 Array<size_t> comp(n, unset);
1091 Array<size_t> next(n, 0);
1092 Array<bool> on_stack(n, false);
1093 Array<size_t> scc_stack;
1094 Array<size_t> frames;
1095 size_t counter = 0;
1096 size_t components = 0;
1097
1098 for (size_t root = 0; root < n; ++root)
1099 {
1100 if (order(root) != unset)
1101 continue;
1102
1103 order(root) = low(root) = counter++;
1104 next(root) = start(root);
1105 scc_stack.append(root);
1106 on_stack(root) = true;
1107 frames.append(root);
1108
1109 while (not frames.is_empty())
1110 {
1111 const size_t v = frames.get_last();
1112 if (next(v) < start(v + 1))
1113 {
1114 const size_t w = adj.tgt(next(v)++);
1115 if (order(w) == unset)
1116 {
1117 order(w) = low(w) = counter++;
1118 next(w) = start(w);
1119 scc_stack.append(w);
1120 on_stack(w) = true;
1121 frames.append(w);
1122 }
1123 else if (on_stack(w) and order(w) < low(v))
1124 low(v) = order(w);
1125 continue;
1126 }
1127
1128 if (low(v) == order(v))
1129 {
1130 for (size_t x = unset; x != v; )
1131 {
1132 x = scc_stack.get_last();
1133 (void) scc_stack.remove_last();
1134 on_stack(x) = false;
1135 comp(x) = components;
1136 }
1137 ++components;
1138 }
1139
1140 (void) frames.remove_last();
1141 if (not frames.is_empty() and low(v) < low(frames.get_last()))
1142 low(frames.get_last()) = low(v);
1143 }
1144 }
1145
1146 Array<size_t> new_id(n, unset);
1147 size_t kept = 0;
1148 for (size_t a = 0; a < m; ++a)
1149 {
1150 const auto & rec = ig.arcs(a);
1151 if (comp(rec.src) != comp(rec.tgt))
1152 continue;
1153 ++kept;
1154 new_id(rec.src) = 0; // marks the node as part of the core
1155 new_id(rec.tgt) = 0;
1156 }
1157
1158 size_t active = 0;
1159 for (size_t i = 0; i < n; ++i)
1160 if (new_id(i) != unset)
1161 ++active;
1162 if (kept == m and active == n)
1163 return true;
1164
1165 core.nodes.reserve(active);
1166 for (size_t i = 0; i < n; ++i)
1167 if (new_id(i) != unset)
1168 {
1169 new_id(i) = core.nodes.size();
1170 core.nodes.append(ig.nodes(i));
1171 }
1172 core.arcs.reserve(kept);
1173 for (size_t a = 0; a < m; ++a)
1174 {
1175 const auto & rec = ig.arcs(a);
1176 if (comp(rec.src) == comp(rec.tgt))
1177 core.arcs.append(Arc_Rec<GT, Cost_Type>{new_id(rec.src), new_id(rec.tgt),
1178 rec.arc, rec.weight});
1179 }
1180 return false;
1181 }
1182
1183 } // namespace negative_cycles_detail
1184
1185
1265 template <AlephGraph GT,
1266 ArcDistance<GT> Distance = Dft_Dist<GT>,
1267 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1270 const size_t max_cycles,
1271 const Negative_Cycle_Exclusion exclusion =
1273 Distance distance = Distance(),
1274 SA sa = SA())
1275 {
1276 using Cost_Type = typename Distance::Distance_Type;
1278
1279 DynList<Item> result;
1280 if (max_cycles == 0)
1281 return result; // documented: no snapshot, no validation, no distance call
1282
1283 const auto ig = negative_cycles_detail::index_graph(g, distance, sa,
1284 "find_disjoint_negative_cycles");
1285 const size_t n = ig.nodes.size();
1286 const size_t m = ig.arcs.size();
1287 if (n == 0 or m == 0)
1288 return result;
1289
1290 constexpr long none = -1;
1291 Array<bool> forbidden(m, false);
1292 Array<Cost_Type> dist(n, Cost_Type{0});
1293 Array<long> pred(n, none); // index into ig.arcs of the arc that last relaxed the node
1294 Array<long> mark(n, 0); // scratch for the predecessor cycle check
1295 Array<size_t> reversed; // the cycle of a round, last arc first
1296 Array<size_t> forward; // the same cycle in order
1297 size_t reported = 0; // cycles in `result`: DynList::size() is O(length)
1298
1299 while (reported < max_cycles)
1300 {
1301 for (size_t i = 0; i < n; ++i)
1302 {
1303 dist(i) = Cost_Type{0};
1304 pred(i) = none;
1305 }
1306
1307 // Up to n passes; after each one the predecessor graph is scanned
1308 // for a cycle, which certifies a negative cycle as soon as one has
1309 // taken shape instead of waiting for a relaxation in the n-th pass.
1310 long cycle_entry = none;
1311 for (size_t pass = 0; pass < n and cycle_entry == none; ++pass)
1312 {
1313 bool relaxed = false;
1314 for (size_t a = 0; a < m; ++a)
1315 {
1316 if (forbidden(a))
1317 continue;
1318
1319 const auto & rec = ig.arcs(a);
1320 const Cost_Type cand =
1321 shortest_path_detail::checked_add(dist(rec.src), rec.weight);
1323 cand, "find_disjoint_negative_cycles(): accumulation became non-finite");
1324
1325 if (cand < dist(rec.tgt))
1326 {
1327 dist(rec.tgt) = cand;
1328 pred(rec.tgt) = static_cast<long>(a);
1329 relaxed = true;
1330 }
1331 }
1332
1333 if (not relaxed)
1334 break; // converged: no negative cycle among the allowed arcs
1335
1337 }
1338
1339 if (cycle_entry == none)
1340 break; // no negative cycle among the allowed arcs
1341
1342 // cycle_entry lies on a cycle of the predecessor graph.
1343 const size_t y = static_cast<size_t>(cycle_entry);
1344 bool ok = true;
1345
1346 // Extract the cycle through y; predecessors give it in reverse order.
1347 reversed.empty();
1348 for (size_t cur = y, guard = 0; ; ++guard)
1349 {
1350 const long a = pred(cur);
1351 if (a == none or guard > n)
1352 {
1353 ok = false;
1354 break;
1355 }
1356 reversed.append(static_cast<size_t>(a));
1357 cur = ig.arcs(static_cast<size_t>(a)).src;
1358 if (cur == y)
1359 break;
1360 }
1361 if (not ok)
1362 break;
1363
1364 const size_t len = reversed.size();
1365 forward.empty();
1366 for (size_t i = len; i > 0; --i)
1367 forward.append(reversed(i - 1));
1368
1369 const Cost_Type total = negative_cycles_detail::cycle_cost(
1370 ig, forward, "find_disjoint_negative_cycles(): cycle cost became non-finite");
1371
1372 // Exclude before deciding whether to report, so that the search
1373 // always makes progress.
1374 if (exclusion == Negative_Cycle_Exclusion::All_Arcs)
1375 for (size_t i = 0; i < len; ++i)
1376 forbidden(forward(i)) = true;
1377 else
1378 {
1379 size_t min_arc = forward(0);
1380 for (size_t i = 1; i < len; ++i)
1381 if (ig.arcs(forward(i)).weight < ig.arcs(min_arc).weight)
1382 min_arc = forward(i);
1383 forbidden(min_arc) = true;
1384 }
1385
1386 if (not (total < Cost_Type{0}))
1387 continue; // the accurate total is not negative: not reportable
1388
1389 Item item;
1390 item.cycle = Path<GT>(g);
1391 item.cycle.init(ig.nodes(y));
1392 for (size_t i = 0; i < len; ++i)
1393 item.cycle.append_directed(ig.arcs(forward(i)).arc);
1394 item.total_cost = total;
1395 item.length = len;
1396 result.append(std::move(item));
1397 ++reported;
1398 }
1399
1400 return result;
1401 }
1402
1403
1404 namespace negative_cycles_detail
1405 {
1407 template <typename Cost_Type>
1409 {
1410 bool found = false;
1411 Cost_Type cost = Cost_Type{0}; // plain sum: what the search computed
1412 Array<size_t> arcs; // indices into Indexed_Graph::arcs, in cycle order
1413
1418 template <AlephGraph GT>
1419 Best_Cycle(const Indexed_Graph<GT, Cost_Type> & ig, const size_t L)
1420 {
1421 if constexpr (std::is_floating_point_v<Cost_Type>)
1423 }
1424
1435 template <AlephGraph GT>
1436 void offer(const Indexed_Graph<GT, Cost_Type> & ig, const Cost_Type & c,
1437 const size_t * candidate, const size_t length)
1438 {
1439 if constexpr (std::is_floating_point_v<Cost_Type>)
1440 {
1441 if (exact_sums_)
1442 {
1443 if (found and not (c < cost or (c == cost and length < arcs.size())))
1444 return;
1445 store(c, candidate, length);
1446 return;
1447 }
1448 if (found and c > reject_above_)
1449 return;
1451 for (size_t i = 0; i < length; ++i)
1452 ah_domain_error_if(not exact_candidate_.add(ig.arcs(candidate[i]).weight))
1453 << "most_negative_cycle_bounded(): cycle cost out of range";
1454 if (found)
1455 {
1458 or not difference_.add(exact_best_, 0, true))
1459 << "most_negative_cycle_bounded(): cycle cost out of range";
1460 const int sign = difference_.sign();
1461 if (not (sign < 0 or (sign == 0 and length < arcs.size())))
1462 return;
1463 }
1464 std::swap(exact_best_, exact_candidate_);
1465 constexpr Cost_Type inf = std::numeric_limits<Cost_Type>::infinity();
1466 reject_above_ = std::nextafter(std::nextafter(c + error_, inf) + error_, inf);
1467 }
1468 else if (found and not (c < cost or (c == cost and length < arcs.size())))
1469 return;
1470
1471 store(c, candidate, length);
1472 }
1473
1474 private:
1475 void store(const Cost_Type & c, const size_t * candidate, const size_t length)
1476 {
1477 found = true;
1478 cost = c;
1479 arcs.empty();
1480 for (size_t i = 0; i < length; ++i)
1481 arcs.append(candidate[i]);
1482 }
1483
1484 // Floating-point costs only: whether every plain sum is exact, else the
1485 // bound of its error, and the plain sum above which a candidate is
1486 // exactly worse than the best (the best's plain sum plus twice that bound).
1487 bool exact_sums_ = true;
1488 Cost_Type error_ = Cost_Type{0};
1489 Cost_Type reject_above_ = Cost_Type{0};
1490 // Floating-point costs only: exact cost of the best cycle, and scratch.
1494 };
1495
1503 {
1507
1512 Decomposition_Scratch(const size_t max_nodes, const size_t max_walk)
1513 : st_nodes(max_nodes + 1, 0), st_in_arc(max_nodes + 1, 0), component(max_walk + 1, 0)
1514 {
1515 // empty
1516 }
1517 };
1518
1524 template <AlephGraph GT, typename Cost_Type>
1526 const Array<size_t> & walk,
1527 Array<long> & pos, // n entries, all -1 on entry and exit
1528 Decomposition_Scratch & scratch,
1529 Best_Cycle<Cost_Type> & best)
1530 {
1531 if (walk.is_empty())
1532 return;
1533
1534 Array<size_t> & st_nodes = scratch.st_nodes;
1535 Array<size_t> & st_in_arc = scratch.st_in_arc;
1536 Array<size_t> & component = scratch.component;
1537
1538 const size_t origin = ig.arcs(walk(0)).src;
1539 size_t top = 0; // logical depth of both stacks
1540 st_nodes(top) = origin;
1541 st_in_arc(top) = std::numeric_limits<size_t>::max(); // no arc enters the origin
1542 pos(origin) = 0;
1543 ++top;
1544
1545 for (size_t i = 0; i < walk.size(); ++i)
1546 {
1547 const size_t a = walk(i);
1548 const size_t t = ig.arcs(a).tgt;
1549 if (pos(t) == -1)
1550 {
1551 st_nodes(top) = t;
1552 st_in_arc(top) = a;
1553 pos(t) = static_cast<long>(top);
1554 ++top;
1555 continue;
1556 }
1557
1558 // t is already on the stack at position p: the arcs entering the
1559 // nodes above p, plus the current one, form a simple cycle.
1560 const size_t p = static_cast<size_t>(pos(t));
1561 size_t length = 0;
1562 for (size_t j = p + 1; j < top; ++j)
1563 component(length++) = st_in_arc(j);
1564 component(length++) = a;
1565
1566 Cost_Type c = Cost_Type{0};
1567 for (size_t j = 0; j < length; ++j)
1568 {
1569 c = shortest_path_detail::checked_add(c, ig.arcs(component(j)).weight);
1570 check_finite(c, "most_negative_cycle_bounded(): cycle cost became non-finite");
1571 }
1572 best.offer(ig, c, &component(0), length);
1573
1574 while (top > p + 1)
1575 {
1576 --top;
1577 pos(st_nodes(top)) = -1;
1578 }
1579 }
1580
1581 // The walk is closed, so everything above the origin was popped.
1582 while (top > 0)
1583 {
1584 --top;
1585 pos(st_nodes(top)) = -1;
1586 }
1587 }
1588 } // namespace negative_cycles_detail
1589
1590
1743 template <AlephGraph GT,
1744 ArcDistance<GT> Distance = Dft_Dist<GT>,
1745 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1748 const size_t max_length,
1749 Distance distance = Distance(),
1750 SA sa = SA())
1751 {
1752 using Cost_Type = typename Distance::Distance_Type;
1754
1755 Result result;
1756 if constexpr (std::is_floating_point_v<Cost_Type>)
1758 if (max_length == 0)
1759 return result; // documented: no snapshot, no validation, no distance call
1760
1761 const auto snapshot = negative_cycles_detail::index_graph(g, distance, sa,
1762 "most_negative_cycle_bounded");
1763 if (snapshot.nodes.is_empty() or snapshot.arcs.is_empty())
1764 return result;
1765
1766 // The bound is a property of the whole graph (see the documentation), not
1767 // of the cyclic core the search runs on.
1768 const size_t L = std::min(max_length, snapshot.nodes.size());
1769
1770 // Only arcs inside strongly connected components can be on a cycle: the
1771 // search runs on that cyclic core, which is the snapshot itself when the
1772 // whole graph is cyclic.
1775 const bool whole = negative_cycles_detail::cyclic_core(snapshot, adj, core);
1776 if (not whole)
1777 {
1778 if (core.arcs.is_empty())
1779 return result; // no cycle at all
1781 }
1782 const auto & ig = whole ? snapshot : core;
1783 const size_t n = ig.nodes.size();
1784 const size_t m = ig.arcs.size();
1785
1786 ah_overflow_error_if(L + 1 > std::numeric_limits<size_t>::max() / n)
1787 << "most_negative_cycle_bounded(): predecessor table size overflow";
1788
1789 constexpr long none = -1;
1790
1791 // A layer visits the arcs of the reached nodes only if they are less than
1792 // one in `frontier_arc_ratio` of all the arcs.
1793 constexpr size_t frontier_arc_ratio = 3;
1794
1795 // Reachability is tracked apart from the cost: every value of Cost_Type,
1796 // including numeric_limits::max(), is a legitimate cost. The layers are
1797 // kept apart (`prev` is layer k - 1, `cur` is layer k) because a walk of
1798 // exactly k arcs may only extend a walk of exactly k - 1 arcs. Each layer
1799 // also lists the nodes it reached, so that nothing is ever reset or
1800 // scanned for the nodes it did not reach.
1801 Array<Cost_Type> prev(n, Cost_Type{0});
1802 Array<Cost_Type> cur(n, Cost_Type{0});
1803 Array<bool> prev_reached(n, false);
1804 Array<bool> cur_reached(n, false);
1805 Array<size_t> prev_list(n, 0);
1806 Array<size_t> cur_list(n, 0);
1807 Array<long> pred((L + 1) * n, none); // pred(k * n + u): arc that reaches u in step k
1808
1809 bool has_walk = false;
1810 Cost_Type best_walk = Cost_Type{0}; // minimum cost over all closed walks considered
1812
1813 Array<long> pos(n, none);
1815 Array<size_t> walk;
1816 walk.reserve(L);
1817
1818 for (size_t v = 0; v < n; ++v)
1819 {
1820 prev(v) = Cost_Type{0};
1821 prev_reached(v) = true;
1822 prev_list(0) = v;
1823 size_t prev_count = 1;
1824 size_t prev_arcs = adj.start(v + 1) - adj.start(v); // arcs leaving the reached nodes
1825
1826 for (size_t k = 1; k <= L; ++k)
1827 {
1828 // Relax the arcs that leave the nodes reached in step k - 1. A
1829 // node is relaxed to the cheapest candidate and, among equally
1830 // cheap ones, to the arc with the lowest index in the snapshot, so
1831 // the outcome does not depend on the order the arcs are visited
1832 // in. When the reached nodes own few arcs it is cheaper to visit
1833 // just those (through the out-adjacency); otherwise one sequential
1834 // scan of all the arcs, in index order, is faster than many short
1835 // adjacency lists.
1836 size_t cur_count = 0;
1837 size_t cur_arcs = 0;
1838 auto reach = [&](const size_t t, const Cost_Type & cand, const size_t a)
1839 {
1840 cur(t) = cand;
1841 cur_reached(t) = true;
1842 pred(k * n + t) = static_cast<long>(a);
1843 cur_list(cur_count++) = t;
1844 cur_arcs += adj.start(t + 1) - adj.start(t);
1845 };
1846
1847 if (prev_arcs * frontier_arc_ratio < m)
1848 {
1849 for (size_t i = 0; i < prev_count; ++i)
1850 {
1851 const size_t u = prev_list(i);
1852 if (k > 1 and u == v)
1853 continue; // the origin is visited only at the ends
1854
1855 const Cost_Type base = prev(u);
1856 for (size_t p = adj.start(u); p < adj.start(u + 1); ++p)
1857 {
1858 const size_t t = adj.tgt(p);
1859 const Cost_Type cand = shortest_path_detail::checked_add(base, adj.weight(p));
1861 cand, "most_negative_cycle_bounded(): accumulation became non-finite");
1862
1863 if (not cur_reached(t))
1864 reach(t, cand, adj.arc(p));
1865 else if (cand < cur(t)
1866 or (cand == cur(t)
1867 and adj.arc(p) < static_cast<size_t>(pred(k * n + t))))
1868 {
1869 cur(t) = cand;
1870 pred(k * n + t) = static_cast<long>(adj.arc(p));
1871 }
1872 }
1873 }
1874 }
1875 else
1876 for (size_t a = 0; a < m; ++a)
1877 {
1878 const auto & rec = ig.arcs(a);
1879 if (k > 1 and rec.src == v)
1880 continue; // the origin is visited only at the ends
1881
1882 if (not prev_reached(rec.src))
1883 continue;
1884
1885 const Cost_Type cand = shortest_path_detail::checked_add(prev(rec.src), rec.weight);
1887 cand, "most_negative_cycle_bounded(): accumulation became non-finite");
1888
1889 if (not cur_reached(rec.tgt))
1890 reach(rec.tgt, cand, a);
1891 else if (cand < cur(rec.tgt)) // arcs come in index order: ties keep the lowest
1892 {
1893 cur(rec.tgt) = cand;
1894 pred(k * n + rec.tgt) = static_cast<long>(a);
1895 }
1896 }
1897
1898 for (size_t i = 0; i < prev_count; ++i)
1899 prev_reached(prev_list(i)) = false;
1900
1901 if (cur_count == 0)
1902 {
1903 prev_count = 0;
1904 break; // nothing is reachable in k steps, so nothing in more
1905 }
1906
1907 if (cur_reached(v))
1908 {
1909 result.has_cycle = true;
1910 if (not has_walk or cur(v) < best_walk)
1911 {
1912 has_walk = true;
1913 best_walk = cur(v);
1914 }
1915
1916 // Reconstruct the closed walk of k arcs (predecessors give it
1917 // backwards) and offer its simple components.
1918 walk.empty();
1919 size_t node = v;
1920 for (size_t kk = k; kk > 0; --kk)
1921 {
1922 const long a = pred(kk * n + node);
1924 << "most_negative_cycle_bounded(): broken predecessor chain";
1925 walk.append(static_cast<size_t>(a));
1926 node = ig.arcs(static_cast<size_t>(a)).src;
1927 }
1928 ah_logic_error_if(node != v)
1929 << "most_negative_cycle_bounded(): walk does not close at its origin";
1930
1931 for (size_t i = 0, j = walk.size() - 1; i < j; ++i, --j)
1932 std::swap(walk(i), walk(j));
1933
1934 negative_cycles_detail::offer_simple_components(ig, walk, pos, scratch, best);
1935 }
1936
1937 prev.swap(cur);
1938 prev_reached.swap(cur_reached);
1939 prev_list.swap(cur_list);
1940 prev_count = cur_count;
1941 prev_arcs = cur_arcs;
1942 }
1943
1944 for (size_t i = 0; i < prev_count; ++i)
1945 prev_reached(prev_list(i)) = false;
1946 }
1947
1948 if (not best.found)
1949 return result;
1950
1951 // The reported cost is recomputed from the arcs of the cycle (an exact sum,
1952 // rounded once, for floating point). The relaxed-bound condition is what
1953 // the search concluded in its own arithmetic; it is withdrawn if its
1954 // plain-sum cost and the exact one disagree on the sign.
1955 result.total_cost = negative_cycles_detail::cycle_cost(
1956 ig, best.arcs, "most_negative_cycle_bounded(): cycle cost became non-finite");
1957 result.length = best.arcs.size();
1958 const bool sign_agrees = (best.cost < Cost_Type{0}) == (result.total_cost < Cost_Type{0});
1959 result.matches_relaxed_bound = sign_agrees and not (best_walk < best.cost);
1960
1961 // The certificate. No simple cycle of the bound costs less than the true
1962 // minimum over the relaxed set, and the dynamic program computes that
1963 // minimum up to the rounding of its sums: by monotonicity of rounding,
1964 // its value at every node is at most the plain sum of any walk that
1965 // reaches it, so the true minimum is at least `best_walk - error_bound`.
1966 // `optimality_gap` is therefore a rigorous bound of how much cheaper than
1967 // the reported cycle the best one can be, and a zero gap is a proof.
1968 if constexpr (std::is_floating_point_v<Cost_Type>)
1969 {
1970 Cost_Type error_bound = Cost_Type{0};
1971 if (negative_cycles_detail::short_sums_are_exact(ig, L, error_bound))
1972 result.numeric_quality = Cycle_Numeric_Quality::Exact;
1974 bool finite = gap.add(-best_walk) and gap.add(error_bound);
1975 for (size_t i = 0; finite and i < best.arcs.size(); ++i)
1976 finite = gap.add(ig.arcs(best.arcs(i)).weight);
1977 result.optimality_gap = finite ? gap.upper() : std::numeric_limits<Cost_Type>::infinity();
1978 }
1979 else
1980 {
1981 // Exact sums: the gap is the difference itself (saturated if it
1982 // does not fit the type).
1983 const Cost_Type exact_cost = result.total_cost;
1984 if (best_walk < Cost_Type{0}
1985 and exact_cost > std::numeric_limits<Cost_Type>::max() + best_walk)
1986 result.optimality_gap = std::numeric_limits<Cost_Type>::max();
1987 else
1988 result.optimality_gap = exact_cost - best_walk;
1989 }
1990 result.is_exact = result.optimality_gap == Cost_Type{0};
1991
1992 result.cycle_nodes.append(ig.nodes(ig.arcs(best.arcs(0)).src));
1993 for (size_t i = 0; i < best.arcs.size(); ++i)
1994 {
1995 const auto & rec = ig.arcs(best.arcs(i));
1996 result.cycle_nodes.append(ig.nodes(rec.tgt));
1997 result.cycle_arcs.append(rec.arc);
1998 }
1999
2000 return result;
2001 }
2002
2003 namespace negative_cycles_detail
2004 {
2011 template <AlephGraph GT, typename Cost_Type>
2014 {
2015 constexpr size_t none = std::numeric_limits<size_t>::max();
2016 const size_t n = ig.nodes.size();
2017 Array<size_t> best(n, none);
2019 out.start = Array<size_t>(n + 1, 0);
2020 out.arc.reserve(ig.arcs.size());
2021 out.tgt.reserve(ig.arcs.size());
2022 out.weight.reserve(ig.arcs.size());
2023 for (size_t u = 0; u < n; ++u)
2024 {
2025 for (size_t p = adj.start(u); p < adj.start(u + 1); ++p)
2026 {
2027 const size_t v = adj.tgt(p), a = adj.arc(p);
2028 if (best(v) == none or ig.arcs(a).weight < ig.arcs(best(v)).weight)
2029 best(v) = a;
2030 }
2031 for (size_t p = adj.start(u); p < adj.start(u + 1); ++p)
2032 {
2033 const size_t v = adj.tgt(p), a = adj.arc(p);
2034 if (best(v) != a)
2035 continue;
2036 out.arc.append(a);
2037 out.tgt.append(v);
2038 out.weight.append(ig.arcs(a).weight);
2039 best(v) = none;
2040 }
2041 out.start(u + 1) = out.arc.size();
2042 }
2043 return out;
2044 }
2045
2053 template <typename Cost_Type>
2055 {
2056 Cost_Type plain_ = Cost_Type{0};
2057 Cost_Type error_ = Cost_Type{0};
2058 Cost_Type reject_above_ = Cost_Type{0};
2059 bool exact_sums_ = true;
2061
2062 // Plain sum of the weights of `idx`, in that order: 0, or the sign of
2063 // the bound a partial sum crossed (1 above the type, -1 below it).
2064 template <AlephGraph GT>
2065 static int plain_sum(const Indexed_Graph<GT, Cost_Type> & ig, const size_t * idx,
2066 const size_t len, Cost_Type & sum)
2067 {
2068 sum = Cost_Type{0};
2069 for (size_t i = 0; i < len; ++i)
2070 {
2071 const Cost_Type w = ig.arcs(idx[i]).weight;
2072 if constexpr (std::is_floating_point_v<Cost_Type>)
2073 {
2074 sum = sum + w;
2075 if (not std::isfinite(sum))
2076 return sum > Cost_Type{0} ? 1 : -1;
2077 }
2078 else
2079 {
2080 if (w > Cost_Type{0} and sum > std::numeric_limits<Cost_Type>::max() - w)
2081 return 1;
2082 if (w < Cost_Type{0} and sum < std::numeric_limits<Cost_Type>::lowest() - w)
2083 return -1;
2084 sum = static_cast<Cost_Type>(sum + w);
2085 }
2086 }
2087 return 0;
2088 }
2089
2090 public:
2091 size_t length = 0;
2092 size_t arcs[3] = {};
2095 bool above_range = false;
2096
2101 template <AlephGraph GT>
2102 Short_Cycle_Best(const Indexed_Graph<GT, Cost_Type> & ig, const size_t bound)
2103 {
2104 if constexpr (std::is_floating_point_v<Cost_Type>)
2106 }
2107
2124 template <AlephGraph GT>
2125 void offer(const Indexed_Graph<GT, Cost_Type> & ig, const size_t * path, const size_t len)
2126 {
2127 size_t order[3] = {path[0], len > 1 ? path[1] : 0, len > 2 ? path[2] : 0};
2128 Cost_Type sum = Cost_Type{0};
2129 int out = plain_sum(ig, order, len, sum);
2130 if (out != 0 and len == 3)
2131 for (size_t i = 0; i < 2; ++i)
2132 for (size_t j = i + 1; j < 3; ++j)
2133 if (out != 0 and (ig.arcs(path[i]).weight < Cost_Type{0})
2134 != (ig.arcs(path[j]).weight < Cost_Type{0}))
2135 {
2136 order[0] = path[i];
2137 order[1] = path[j];
2138 order[2] = path[3 - i - j];
2139 out = plain_sum(ig, order, len, sum);
2140 }
2141 if (out > 0)
2142 {
2143 above_range = true;
2144 return;
2145 }
2146 if constexpr (std::is_floating_point_v<Cost_Type>)
2147 {
2148 ah_domain_error_if(out < 0) << "most_negative_cycle_up_to_3(): cycle cost out of range";
2149 }
2150 else
2151 {
2152 ah_overflow_error_if(out < 0) << "most_negative_cycle_up_to_3(): cycle cost out of range";
2153 }
2154
2155 if constexpr (std::is_floating_point_v<Cost_Type>)
2156 {
2157 if (not exact_sums_)
2158 {
2159 if (length != 0 and sum > reject_above_)
2160 return;
2161 candidate_.clear();
2162 bool fits = true;
2163 for (size_t i = 0; fits and i < len; ++i)
2164 fits = candidate_.add(ig.arcs(order[i]).weight);
2165 if (not fits)
2166 {
2167 // The plain sums fitted, so the exact total is within
2168 // rounding of the limit on the side of their sign.
2169 ah_domain_error_if(sum < Cost_Type{0})
2170 << "most_negative_cycle_up_to_3(): cycle cost out of range";
2171 above_range = true;
2172 return;
2173 }
2174 if (length != 0)
2175 {
2176 // Different signs order the totals without subtracting
2177 // values near opposite ends of the floating-point range.
2178 int order = candidate_.sign() - best_.sign();
2179 if (order == 0)
2180 {
2183 or not difference_.add(best_, 0, true))
2184 << "most_negative_cycle_up_to_3(): comparison out of range";
2185 order = difference_.sign();
2186 }
2187 if (not (order < 0 or (order == 0 and len < length)))
2188 return;
2189 }
2190 std::swap(best_, candidate_);
2191 constexpr Cost_Type inf = std::numeric_limits<Cost_Type>::infinity();
2192 reject_above_ = std::nextafter(std::nextafter(sum + error_, inf) + error_, inf);
2193 }
2194 else if (length != 0 and not (sum < plain_ or (sum == plain_ and len < length)))
2195 return;
2196 }
2197 else if (length != 0 and not (sum < plain_ or (sum == plain_ and len < length)))
2198 return;
2199
2200 plain_ = sum;
2201 length = len;
2202 for (size_t i = 0; i < len; ++i)
2203 arcs[i] = path[i];
2204 }
2205
2212 Cost_Type total()
2213 {
2214 if constexpr (std::is_floating_point_v<Cost_Type>)
2215 if (not exact_sums_)
2216 {
2217 // Infinite only if the best total is out of range, which
2218 // `add()` does not report when the components are wider.
2219 const Cost_Type t = best_.rounded();
2220 ah_domain_error_if(not std::isfinite(t))
2221 << "most_negative_cycle_up_to_3(): cycle cost out of range";
2222 return t;
2223 }
2224 return plain_;
2225 }
2226 };
2227 } // namespace negative_cycles_detail
2228
2276 template <AlephGraph GT,
2277 ArcDistance<GT> Distance = Dft_Dist<GT>,
2278 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
2280 most_negative_cycle_up_to_3(const GT & g, const size_t max_length = 3,
2281 Distance distance = Distance(), SA sa = SA())
2282 {
2283 using Cost_Type = typename Distance::Distance_Type;
2284 constexpr size_t none = std::numeric_limits<size_t>::max();
2286 ah_invalid_argument_if(max_length > 3)
2287 << "most_negative_cycle_up_to_3(): max_length must be in [0, 3]";
2288 if (max_length == 0)
2289 return result;
2290 const auto snapshot = negative_cycles_detail::index_graph(g, distance, sa,
2291 "most_negative_cycle_up_to_3");
2292 if (snapshot.arcs.is_empty())
2293 return result;
2294
2297 bool whole = true;
2298 if (max_length > 1)
2299 {
2301 whole = negative_cycles_detail::cyclic_core(snapshot, adj, core);
2302 if (not whole)
2303 {
2304 if (core.arcs.is_empty())
2305 return result;
2307 }
2308 adj = negative_cycles_detail::cheapest_parallel_arcs(whole ? snapshot : core, adj);
2309 }
2310 const auto & ig = whole ? snapshot : core;
2311 const size_t n = ig.nodes.size();
2313
2314 if (max_length == 1)
2315 {
2316 for (size_t a = 0; a < ig.arcs.size(); ++a)
2317 if (ig.arcs(a).src == ig.arcs(a).tgt)
2318 best.offer(ig, &a, 1);
2319 }
2320 else
2321 {
2322 // Incoming adjacency lets each origin mark all its closing arcs in
2323 // O(in-degree), using one shared O(V) array instead of a dense matrix.
2324 Array<size_t> in_start(n + 1, 0);
2325 for (size_t p = 0; p < adj.arc.size(); ++p)
2326 ++in_start(adj.tgt(p) + 1);
2327 for (size_t u = 0; u < n; ++u)
2328 in_start(u + 1) += in_start(u);
2329 Array<size_t> incoming(adj.arc.size(), 0), fill(n, 0), closing(n, none);
2330 for (size_t p = 0; p < adj.arc.size(); ++p)
2331 incoming(in_start(adj.tgt(p)) + fill(adj.tgt(p))++) = adj.arc(p);
2332
2333 // All shorter cycles are offered before triangles, which gives the
2334 // rounding filter a useful incumbent even in a clean, dense market.
2335 for (size_t phase = 2; phase <= max_length; ++phase)
2336 for (size_t u = 0; u < n; ++u)
2337 {
2338 for (size_t p = in_start(u); p < in_start(u + 1); ++p)
2339 closing(ig.arcs(incoming(p)).src) = incoming(p);
2340 if (phase == 2 and closing(u) != none)
2341 best.offer(ig, &closing(u), 1);
2342 for (size_t p = adj.start(u); p < adj.start(u + 1); ++p)
2343 {
2344 const size_t v = adj.tgt(p);
2345 if (v <= u)
2346 continue; // the origin is the smallest node of the cycle
2347 if (phase == 2)
2348 {
2349 if (closing(v) != none)
2350 {
2351 const size_t path[] = {adj.arc(p), closing(v)};
2352 best.offer(ig, path, 2);
2353 }
2354 }
2355 else
2356 for (size_t q = adj.start(v); q < adj.start(v + 1); ++q)
2357 {
2358 const size_t w = adj.tgt(q);
2359 if (w <= u or w == v or closing(w) == none)
2360 continue;
2361 const size_t path[] = {adj.arc(p), adj.arc(q), closing(w)};
2362 best.offer(ig, path, 3);
2363 }
2364 }
2365 for (size_t p = in_start(u); p < in_start(u + 1); ++p)
2366 closing(ig.arcs(incoming(p)).src) = none;
2367 }
2368 }
2369
2370 if (best.length == 0)
2371 {
2372 // Every cycle had a total above the cost type: the best one does not fit.
2373 if constexpr (std::is_floating_point_v<Cost_Type>)
2374 {
2376 << "most_negative_cycle_up_to_3(): cycle cost out of range";
2377 }
2378 else
2379 {
2381 << "most_negative_cycle_up_to_3(): cycle cost out of range";
2382 }
2383 return result;
2384 }
2385 result.has_cycle = true;
2386 result.length = best.length;
2387 result.total_cost = best.total();
2388 result.cycle_nodes.append(ig.nodes(ig.arcs(best.arcs[0]).src));
2389 for (size_t i = 0; i < best.length; ++i)
2390 {
2391 const auto & arc = ig.arcs(best.arcs[i]);
2392 result.cycle_arcs.append(arc.arc);
2393 result.cycle_nodes.append(ig.nodes(arc.tgt));
2394 }
2395 return result;
2396 }
2397} // namespace Aleph
2398
2399# endif // NEGATIVE_CYCLES_H
Exception handling system with formatted messages for Aleph-w.
#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
#define ah_logic_error_if(C)
Throws std::logic_error if condition holds.
Definition ah-errors.H:474
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
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
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
T & get_last()
Return a modifiable reference to the last element.
Definition tpl_array.H:483
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
Default distance accessor for arc weights.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Path on a graph.
Definition tpl_graph.H:3832
Exact sum of floating-point numbers.
exact_float_t< T > Component
Type of the components (see exact_float_t).
bool add(const Component b)
Add b exactly.
bool is_zero() const noexcept
True if the value is exactly zero.
T upper()
The smallest number of T not below the value, or a slightly larger one; checked exactly,...
int sign() const noexcept
Exact sign of the value: -1, 0 or 1.
bool add(const Exact_Sum &x, const int exponent=0, const bool negate=false)
Add the value of x, multiplied by 2^exponent and negated if asked.
static bool grow_expansion(Array< Component > &a, size_t &n, const Component b)
void clear() noexcept
Set the value to zero; the storage is kept.
static bool grow(Array< Component > &a, size_t &n, const Component b)
void compress()
Rewrite the expansion so that its largest component approximates the value within one unit in its las...
T rounded()
The value rounded to T: within one unit in the last place, zero only if the value is zero,...
static void put(Array< Component > &a, const size_t i, const Component x)
bool add_multiple(const Exact_Sum &x, size_t factor, const bool negate=false)
Add factor times the value of x, negated if asked.
Map from node pointers to their positions, built once and never modified afterwards.
static size_t slot_of(const Node *node) noexcept
size_t find(const Node *node) const
Position of node.
void insert(Node *node, const size_t position)
Record that node (not yet inserted) is at position.
Rank cycles of at most three arcs exactly, reusing scratch sums.
bool above_range
Whether a cycle was skipped because its total is above the largest value of the cost type.
Cost_Type total()
Published total of the winning cycle.
size_t length
Zero until the first cycle is offered.
static int plain_sum(const Indexed_Graph< GT, Cost_Type > &ig, const size_t *idx, const size_t len, Cost_Type &sum)
void offer(const Indexed_Graph< GT, Cost_Type > &ig, const size_t *path, const size_t len)
Offer a cycle; exact cost and then length decide the winner.
Short_Cycle_Best(const Indexed_Graph< GT, Cost_Type > &ig, const size_t bound)
Prepare a rigorous rounding filter for this graph and bound.
size_t arcs[3]
Original snapshot indices in cycle order.
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
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
static Tree_Node< int > * chain(size_t n)
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
DynList< Negative_Cycle_Item< GT, typename Distance::Distance_Type > > find_disjoint_negative_cycles(const GT &g, const size_t max_cycles, const Negative_Cycle_Exclusion exclusion=Negative_Cycle_Exclusion::Min_Weight_Arc, Distance distance=Distance(), SA sa=SA())
Find up to max_cycles negative cycles, excluding arcs of each cycle found before searching for the ne...
Cycle_Numeric_Quality
How far the numbers behind the result of a cycle search can be trusted.
Bounded_Cycle_Result< GT, typename Distance::Distance_Type > most_negative_cycle_bounded(const GT &g, const size_t max_length, Distance distance=Distance(), SA sa=SA())
Most negative simple cycle of at most max_length arcs, ranked by total cost (not by mean cost as Karp...
Negative_Cycle_Exclusion
Which arcs of a found negative cycle are excluded before searching for the next one in find_disjoint_...
Short_Cycle_Result< GT, typename Distance::Distance_Type > most_negative_cycle_up_to_3(const GT &g, const size_t max_length=3, Distance distance=Distance(), SA sa=SA())
Minimum-total-cost simple cycle with at most one, two or three arcs.
@ Exact
Every sum and comparison that decided the result was exact: integral costs (an overflow throws instea...
@ Rounded
The cycle was chosen with rounded values (floating-point costs, or means compared in long double by K...
@ Min_Weight_Arc
Exclude only the arc of minimum (most negative) weight.
@ All_Arcs
Exclude every arc of the cycle.
Singly linked list implementations with head-tail access.
Freq_Node * pred
Predecessor node in level-order traversal.
Knapsack_Item< int, int > Item
static mpfr_t y
Definition mpfr_mul_d.c:3
void offer_simple_components(const Indexed_Graph< GT, Cost_Type > &ig, const Array< size_t > &walk, Array< long > &pos, Decomposition_Scratch &scratch, Best_Cycle< Cost_Type > &best)
Decompose the closed walk walk (arc indices, in order, starting and ending at the same node) into sim...
Indexed_Graph< GT, typename Distance::Distance_Type > index_graph(const GT &g, Distance &distance, SA &sa, const char *fn)
Snapshot the graph: index its nodes and the arcs accepted by sa, reading each weight once.
long find_predecessor_cycle(const Indexed_Graph< GT, Cost_Type > &ig, const Array< long > &pred, Array< long > &mark)
Scan the predecessor graph for a cycle.
void check_finite(const Cost_Type &value, const char *context)
bool short_sums_are_exact(const Indexed_Graph< GT, Cost_Type > &ig, const size_t L, Cost_Type &error_bound)
Rounding behaviour of the sums of at most L weights of ig, added left to right in a floating-point Co...
void bit_span(const T x, int &low, int &high) noexcept
Exponents of the lowest and of the highest set bit of a nonzero finite x: |x| is an odd integer times...
Out_Adjacency< Cost_Type > cheapest_parallel_arcs(const Indexed_Graph< GT, Cost_Type > &ig, const Out_Adjacency< Cost_Type > &adj)
Keep the cheapest parallel arc of each ordered pair.
Out_Adjacency< Cost_Type > build_out_adjacency(const Indexed_Graph< GT, Cost_Type > &ig)
Build the out-adjacency of ig by a counting sort, O(V + E).
Cost_Type cycle_cost(const Indexed_Graph< GT, Cost_Type > &ig, const Array< size_t > &arcs, const char *context)
Total cost of the arcs arcs (indices into ig.arcs).
bool cyclic_core(const Indexed_Graph< GT, Cost_Type > &ig, const Out_Adjacency< Cost_Type > &adj, Indexed_Graph< GT, Cost_Type > &core)
Cyclic core of a snapshot: the nodes and arcs that lie inside a strongly connected component with at ...
void two_sum(const F a, const F b, F &s, F &e) noexcept
Error-free sum (Knuth's TwoSum): s = fl(a + b) and s + e == a + b exactly.
T exact_float_t
Floating-point format in which the error-free transformations on values of T are carried out.
std::uint64_t odd_significand(const T x) noexcept
The odd integer |x| / 2^low, with low the exponent of the lowest set bit of the nonzero finite x (see...
T checked_add(const T &a, const T &b)
Safely add two distance values with overflow checking.
Main namespace for Aleph-w library functions.
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Definition ahAlgo.H:707
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Common utilities and base class for shortest path algorithms.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Result of most_negative_cycle_bounded().
bool matches_relaxed_bound
True when, in the arithmetic of the search, the cost the search computed for the reported cycle equal...
Cost_Type optimality_gap
Rigorous upper bound of how much cheaper than total_cost the best simple cycle of at most max_length ...
Cost_Type total_cost
Sum of the arc weights of the reported cycle (for floating-point costs the exact sum,...
bool is_negative() const noexcept
True if a cycle was found and its total cost is negative.
DynList< typename GT::Arc * > cycle_arcs
Arcs aligned with cycle_nodes.
Cycle_Numeric_Quality numeric_quality
Whether the sums and comparisons behind this result were exact.
DynList< typename GT::Node * > cycle_nodes
Closed walk, first node repeated at the end.
size_t length
Number of arcs of the reported cycle.
bool has_cycle
True if the graph has a cycle of at most max_length arcs.
bool is_exact
Proof that total_cost is the minimum cost of a simple cycle of at most max_length arcs: true exactly ...
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
One negative cycle reported by find_disjoint_negative_cycles().
Path< GT > cycle
Closed path: is_cycle() holds, every arc is a graph arc.
Cost_Type total_cost
Sum of the arc weights, negative; for floating-point costs the exact sum, rounded once.
size_t length
Number of arcs.
Exact optimum returned by most_negative_cycle_up_to_3().
DynList< typename GT::Arc * > cycle_arcs
Original arcs aligned with consecutive nodes.
bool has_cycle
Whether a cycle within the bound exists.
Cost_Type total_cost
Exact weight sum, rounded for floating-point costs.
bool is_negative() const noexcept
Whether the optimum has strictly negative total cost.
DynList< typename GT::Node * > cycle_nodes
Closed node list, first node repeated last.
size_t length
Number of arcs, at most three.
Snapshot of one graph arc: endpoint positions, the arc and its weight (read once from the distance ac...
Best simple cycle found so far by most_negative_cycle_bounded().
void offer(const Indexed_Graph< GT, Cost_Type > &ig, const Cost_Type &c, const size_t *candidate, const size_t length)
Keep the cycle of length arcs candidate[0..length), of plain-sum cost c, if it is cheaper than the be...
void store(const Cost_Type &c, const size_t *candidate, const size_t length)
Best_Cycle(const Indexed_Graph< GT, Cost_Type > &ig, const size_t L)
Prepare the rounding filter for cycles of at most L arcs.
Scratch space of offer_simple_components(), allocated once.
Array< size_t > component
Arcs of the simple cycle being offered.
Array< size_t > st_in_arc
Arc entering each stacked node, aligned with st_nodes.
Decomposition_Scratch(const size_t max_nodes, const size_t max_walk)
Positional snapshot of a graph: nodes by position and the arcs accepted by the arc filter,...
Array< Arc_Rec< GT, Cost_Type > > arcs
Out-adjacency of a snapshot in compressed form.
Array< Cost_Type > weight
Weight of the arc.
Array< size_t > tgt
Position of the target node.
Array< size_t > arc
Index of the arc in Indexed_Graph::arcs.
Distance accessor.
Aleph::Array< Display_Node > nodes
Root at index zero.
std::vector< std::array< int, 2 > > arcs
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static long counter
Definition test-splice.C:40
static int * k
Dynamic array container with automatic resizing.
Generic graph and digraph implementations.