161# ifndef NEGATIVE_CYCLES_H
162# define NEGATIVE_CYCLES_H
173# include <type_traits>
242 template <AlephGraph GT,
typename Cost_Type>
260 template <AlephGraph GT,
typename Cost_Type>
342 template <AlephGraph GT,
typename Cost_Type>
360 namespace negative_cycles_detail
368 template <AlephGraph GT,
typename Cost_Type>
383 template <AlephGraph GT,
typename Cost_Type>
390 template <
typename Cost_Type>
392 [[maybe_unused]]
const char * context)
394 if constexpr (std::is_floating_point_v<Cost_Type>)
406# if defined(FLT_EVAL_METHOD) and FLT_EVAL_METHOD != 0
407 template <
typename T>
410 template <
typename T>
430 template <
typename F>
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);
455 template <
typename T>
486 constexpr Component quarter_of_max = std::numeric_limits<Component>::max() / 4;
487 if (not (std::fabs(b) > quarter_of_max))
490 for (
int i = 0; i < 4; ++i)
501 for (
size_t i = 0; i < n; ++i)
512 return std::isfinite(q);
529 [[nodiscard]]
int sign() const noexcept
555 for (
size_t i = 0; i < x.
n_; ++i)
573 for (
int bit = 0; factor != 0; ++bit, factor >>= 1)
589 size_t bottom =
n_ - 1;
590 for (
size_t i =
n_ - 1; i-- > 0; )
605 for (
size_t i = bottom + 1; i <
n_; ++i)
626 return n_ == 0 ?
T(0) :
static_cast<T>(
h_(
n_ - 1));
635 for (
size_t i = 0; i <
n_; ++i)
636 if (not std::isfinite(
h_(i)))
637 return std::numeric_limits<T>::infinity();
641 if (b == std::numeric_limits<T>::infinity())
644 for (
size_t i = 0; i <
n_; ++i)
649 b = std::nextafter(b, std::numeric_limits<T>::infinity());
662 template <
typename T>
665 if constexpr (std::numeric_limits<T>::is_iec559
666 and (std::is_same_v<T, double> or std::is_same_v<T, float>))
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);
684 const T f = std::frexp(std::fabs(x), &e);
685 constexpr int digits = std::numeric_limits<T>::digits;
686 T m = std::ldexp(f, digits);
688 if constexpr (digits <= 64)
689 zeros = std::countr_zero(
static_cast<unsigned long long>(
m));
691 while (std::fmod(
m,
T(2)) ==
T(0))
696 low = e - digits + zeros;
707 template <
typename T>
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>))
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));
729 return static_cast<std::uint64_t
>(std::ldexp(std::fabs(x), -
low));
751 template <AlephGraph GT,
typename Cost_Type>
754 const char * context)
756 if constexpr (std::is_floating_point_v<Cost_Type>)
759 for (
size_t i = 0; i <
arcs.size(); ++i)
761 const Cost_Type total =
sum.rounded();
767 Cost_Type
sum = Cost_Type{0};
768 for (
size_t i = 0; i <
arcs.size(); ++i)
792 template <AlephGraph GT,
typename Cost_Type>
794 Cost_Type & error_bound)
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();
803 Cost_Type max_abs = Cost_Type{0};
804 for (
size_t a = 0; a < ig.
arcs.size(); ++a)
806 const Cost_Type
w = ig.
arcs(a).weight;
807 if (
w == Cost_Type{0})
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));
818 error_bound = Cost_Type{0};
819 if (not any or L < 2)
821 if (high_max + 1 +
static_cast<int>(std::bit_width(L - 1)) <= digits + low_min)
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);
846 template <
typename Node>
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);
869 <<
"Node_Index: capacity overflow";
871 while (capacity < 2 * n)
875 mask_ = capacity - 1;
885 while (
keys_(i) !=
nullptr)
900 while (
keys_(i) != node)
903 <<
"Node_Index: the arc endpoint is not a node of the graph";
913 template <AlephGraph GT, ArcDistance<GT> Distance, ArcFilter<GT> SA>
914 Indexed_Graph<GT, typename Distance::Distance_Type>
921 static_assert(std::is_arithmetic_v<Cost_Type>,
922 "negative cycle search requires arithmetic arc costs");
934 Node * node = it.get_curr_ne();
936 node_to_idx.
insert(node, idx);
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");
970 template <AlephGraph GT,
typename Cost_Type>
975 const size_t n = mark.
size();
976 for (
size_t i = 0; i < n; ++i)
980 for (
size_t s = 0; s < n; ++s)
986 for (
size_t v = s; ; )
989 const long a =
pred(v);
992 const size_t u = ig.
arcs(
static_cast<size_t>(a)).src;
993 if (mark(u) ==
chain)
994 return static_cast<long>(u);
1010 template <
typename Cost_Type>
1023 template <AlephGraph GT,
typename Cost_Type>
1027 const size_t m = ig.
arcs.size();
1031 for (
size_t a = 0; a <
m; ++a)
1033 for (
size_t i = 0; i < n; ++i)
1040 for (
size_t a = 0; a <
m; ++a)
1042 const auto & rec = ig.
arcs(a);
1043 const size_t p = adj.
start(rec.src) +
fill(rec.src)++;
1045 adj.
tgt(p) = rec.tgt;
1046 adj.
weight(p) = rec.weight;
1077 template <AlephGraph GT,
typename Cost_Type>
1082 constexpr size_t unset = std::numeric_limits<size_t>::max();
1084 const size_t m = ig.
arcs.size();
1096 size_t components = 0;
1100 if (order(
root) != unset)
1106 on_stack(
root) =
true;
1111 const size_t v = frames.
get_last();
1112 if (
next(v) < start(v + 1))
1114 const size_t w = adj.
tgt(
next(v)++);
1115 if (order(
w) == unset)
1123 else if (on_stack(
w)
and order(
w) <
low(v))
1128 if (
low(v) == order(v))
1130 for (
size_t x = unset; x != v; )
1134 on_stack(x) =
false;
1135 comp(x) = components;
1148 for (
size_t a = 0; a <
m; ++a)
1150 const auto & rec = ig.
arcs(a);
1151 if (comp(rec.src) != comp(rec.tgt))
1154 new_id(rec.src) = 0;
1155 new_id(rec.tgt) = 0;
1159 for (
size_t i = 0; i < n; ++i)
1160 if (new_id(i) != unset)
1162 if (kept ==
m and active == n)
1166 for (
size_t i = 0; i < n; ++i)
1167 if (new_id(i) != unset)
1172 core.
arcs.reserve(kept);
1173 for (
size_t a = 0; a <
m; ++a)
1175 const auto & rec = ig.
arcs(a);
1176 if (comp(rec.src) == comp(rec.tgt))
1178 rec.arc, rec.weight});
1265 template <AlephGraph
GT,
1270 const size_t max_cycles,
1280 if (max_cycles == 0)
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)
1290 constexpr long none = -1;
1297 size_t reported = 0;
1299 while (reported < max_cycles)
1301 for (
size_t i = 0; i < n; ++i)
1303 dist(i) = Cost_Type{0};
1310 long cycle_entry =
none;
1311 for (
size_t pass = 0; pass < n
and cycle_entry ==
none; ++pass)
1313 bool relaxed =
false;
1314 for (
size_t a = 0; a <
m; ++a)
1319 const auto & rec = ig.arcs(a);
1320 const Cost_Type cand =
1323 cand,
"find_disjoint_negative_cycles(): accumulation became non-finite");
1325 if (cand < dist(rec.tgt))
1327 dist(rec.tgt) = cand;
1328 pred(rec.tgt) =
static_cast<long>(a);
1339 if (cycle_entry ==
none)
1343 const size_t y =
static_cast<size_t>(cycle_entry);
1348 for (
size_t cur =
y, guard = 0; ; ++guard)
1350 const long a =
pred(cur);
1351 if (a ==
none or guard > n)
1356 reversed.append(
static_cast<size_t>(a));
1357 cur = ig.
arcs(
static_cast<size_t>(a)).src;
1364 const size_t len = reversed.size();
1366 for (
size_t i = len; i > 0; --i)
1367 forward.
append(reversed(i - 1));
1370 ig, forward,
"find_disjoint_negative_cycles(): cycle cost became non-finite");
1375 for (
size_t i = 0; i < len; ++i)
1376 forbidden(forward(i)) =
true;
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;
1386 if (not (total < Cost_Type{0}))
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;
1396 result.
append(std::move(item));
1404 namespace negative_cycles_detail
1407 template <
typename Cost_Type>
1418 template <AlephGraph GT>
1421 if constexpr (std::is_floating_point_v<Cost_Type>)
1435 template <AlephGraph GT>
1437 const size_t * candidate,
const size_t length)
1439 if constexpr (std::is_floating_point_v<Cost_Type>)
1445 store(c, candidate, length);
1451 for (
size_t i = 0; i < length; ++i)
1453 <<
"most_negative_cycle_bounded(): cycle cost out of range";
1459 <<
"most_negative_cycle_bounded(): cycle cost out of range";
1461 if (not (sign < 0 or (sign == 0
and length <
arcs.
size())))
1465 constexpr Cost_Type inf = std::numeric_limits<Cost_Type>::infinity();
1471 store(c, candidate, length);
1475 void store(
const Cost_Type & c,
const size_t * candidate,
const size_t length)
1480 for (
size_t i = 0; i < length; ++i)
1524 template <AlephGraph GT,
typename Cost_Type>
1538 const size_t origin = ig.
arcs(walk(0)).src;
1540 st_nodes(top) = origin;
1541 st_in_arc(top) = std::numeric_limits<size_t>::max();
1545 for (
size_t i = 0; i < walk.
size(); ++i)
1547 const size_t a = walk(i);
1548 const size_t t = ig.
arcs(a).tgt;
1553 pos(t) =
static_cast<long>(top);
1560 const size_t p =
static_cast<size_t>(pos(t));
1562 for (
size_t j = p + 1; j < top; ++j)
1563 component(length++) = st_in_arc(j);
1564 component(length++) = a;
1566 Cost_Type c = Cost_Type{0};
1567 for (
size_t j = 0; j < length; ++j)
1570 check_finite(c,
"most_negative_cycle_bounded(): cycle cost became non-finite");
1572 best.
offer(ig, c, &component(0), length);
1577 pos(st_nodes(top)) = -1;
1585 pos(st_nodes(top)) = -1;
1743 template <AlephGraph
GT,
1748 const size_t max_length,
1756 if constexpr (std::is_floating_point_v<Cost_Type>)
1758 if (max_length == 0)
1762 "most_negative_cycle_bounded");
1763 if (snapshot.
nodes.is_empty() or snapshot.arcs.is_empty())
1768 const size_t L = std::min(max_length, snapshot.
nodes.size());
1778 if (core.
arcs.is_empty())
1782 const auto & ig = whole ? snapshot : core;
1784 const size_t m = ig.arcs.
size();
1787 <<
"most_negative_cycle_bounded(): predecessor table size overflow";
1789 constexpr long none = -1;
1793 constexpr size_t frontier_arc_ratio = 3;
1809 bool has_walk =
false;
1810 Cost_Type best_walk = Cost_Type{0};
1818 for (
size_t v = 0; v < n; ++v)
1820 prev(v) = Cost_Type{0};
1821 prev_reached(v) =
true;
1823 size_t prev_count = 1;
1824 size_t prev_arcs = adj.start(v + 1) - adj.start(v);
1826 for (
size_t k = 1;
k <= L; ++
k)
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)
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);
1847 if (prev_arcs * frontier_arc_ratio <
m)
1849 for (
size_t i = 0; i < prev_count; ++i)
1851 const size_t u = prev_list(i);
1852 if (
k > 1
and u == v)
1855 const Cost_Type base = prev(u);
1856 for (
size_t p = adj.start(u); p < adj.start(u + 1); ++p)
1858 const size_t t = adj.tgt(p);
1861 cand,
"most_negative_cycle_bounded(): accumulation became non-finite");
1863 if (not cur_reached(t))
1864 reach(t, cand, adj.arc(p));
1865 else if (cand < cur(t)
1867 and adj.arc(p) <
static_cast<size_t>(
pred(
k * n + t))))
1870 pred(
k * n + t) =
static_cast<long>(adj.arc(p));
1876 for (
size_t a = 0; a <
m; ++a)
1878 const auto & rec = ig.arcs(a);
1879 if (
k > 1
and rec.src == v)
1882 if (not prev_reached(rec.src))
1887 cand,
"most_negative_cycle_bounded(): accumulation became non-finite");
1889 if (not cur_reached(rec.tgt))
1890 reach(rec.tgt, cand, a);
1891 else if (cand < cur(rec.tgt))
1893 cur(rec.tgt) = cand;
1894 pred(
k * n + rec.tgt) =
static_cast<long>(a);
1898 for (
size_t i = 0; i < prev_count; ++i)
1899 prev_reached(prev_list(i)) =
false;
1909 result.has_cycle =
true;
1910 if (not has_walk or cur(v) < best_walk)
1920 for (
size_t kk =
k; kk > 0; --kk)
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;
1929 <<
"most_negative_cycle_bounded(): walk does not close at its origin";
1931 for (
size_t i = 0, j = walk.
size() - 1; i < j; ++i, --j)
1932 std::swap(walk(i), walk(j));
1938 prev_reached.
swap(cur_reached);
1939 prev_list.
swap(cur_list);
1940 prev_count = cur_count;
1941 prev_arcs = cur_arcs;
1944 for (
size_t i = 0; i < prev_count; ++i)
1945 prev_reached(prev_list(i)) =
false;
1956 ig, best.
arcs,
"most_negative_cycle_bounded(): cycle cost became non-finite");
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);
1968 if constexpr (std::is_floating_point_v<Cost_Type>)
1970 Cost_Type error_bound = Cost_Type{0};
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();
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();
1988 result.optimality_gap = exact_cost - best_walk;
1990 result.is_exact = result.optimality_gap == Cost_Type{0};
1992 result.cycle_nodes.append(ig.nodes(ig.arcs(best.arcs(0)).src));
1993 for (
size_t i = 0; i < best.arcs.size(); ++i)
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);
2003 namespace negative_cycles_detail
2011 template <AlephGraph GT,
typename Cost_Type>
2015 constexpr size_t none = std::numeric_limits<size_t>::max();
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)
2025 for (
size_t p = adj.
start(u); p < adj.
start(u + 1); ++p)
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)
2031 for (
size_t p = adj.
start(u); p < adj.
start(u + 1); ++p)
2033 const size_t v = adj.
tgt(p), a = adj.
arc(p);
2038 out.weight.append(ig.
arcs(a).weight);
2053 template <
typename Cost_Type>
2064 template <AlephGraph GT>
2066 const size_t len, Cost_Type & sum)
2069 for (
size_t i = 0; i < len; ++i)
2071 const Cost_Type
w = ig.
arcs(idx[i]).weight;
2072 if constexpr (std::is_floating_point_v<Cost_Type>)
2075 if (not std::isfinite(
sum))
2076 return sum > Cost_Type{0} ? 1 : -1;
2080 if (
w > Cost_Type{0}
and sum > std::numeric_limits<Cost_Type>::max() -
w)
2082 if (
w < Cost_Type{0}
and sum < std::numeric_limits<Cost_Type>::lowest() -
w)
2084 sum =
static_cast<Cost_Type
>(
sum +
w);
2101 template <AlephGraph GT>
2104 if constexpr (std::is_floating_point_v<Cost_Type>)
2124 template <AlephGraph GT>
2127 size_t order[3] = {path[0], len > 1 ? path[1] : 0, len > 2 ? path[2] : 0};
2128 Cost_Type
sum = Cost_Type{0};
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}))
2138 order[2] = path[3 - i - j];
2146 if constexpr (std::is_floating_point_v<Cost_Type>)
2155 if constexpr (std::is_floating_point_v<Cost_Type>)
2163 for (
size_t i = 0; fits
and i < len; ++i)
2170 <<
"most_negative_cycle_up_to_3(): cycle cost out of range";
2184 <<
"most_negative_cycle_up_to_3(): comparison out of range";
2187 if (not (order < 0 or (order == 0
and len <
length)))
2191 constexpr Cost_Type inf = std::numeric_limits<Cost_Type>::infinity();
2202 for (
size_t i = 0; i < len; ++i)
2214 if constexpr (std::is_floating_point_v<Cost_Type>)
2221 <<
"most_negative_cycle_up_to_3(): cycle cost out of range";
2276 template <AlephGraph
GT,
2284 constexpr size_t none = std::numeric_limits<size_t>::max();
2287 <<
"most_negative_cycle_up_to_3(): max_length must be in [0, 3]";
2288 if (max_length == 0)
2291 "most_negative_cycle_up_to_3");
2292 if (snapshot.arcs.is_empty())
2304 if (core.
arcs.is_empty())
2310 const auto & ig = whole ? snapshot : core;
2314 if (max_length == 1)
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);
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);
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);
2335 for (
size_t phase = 2; phase <= max_length; ++phase)
2336 for (
size_t u = 0; u < n; ++u)
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)
2344 const size_t v = adj.
tgt(p);
2349 if (closing(v) !=
none)
2351 const size_t path[] = {adj.
arc(p), closing(v)};
2352 best.
offer(ig, path, 2);
2356 for (
size_t q = adj.
start(v); q < adj.
start(v + 1); ++q)
2358 const size_t w = adj.
tgt(q);
2359 if (
w <= u or
w == v or closing(
w) ==
none)
2361 const size_t path[] = {adj.
arc(p), adj.
arc(q), closing(
w)};
2362 best.
offer(ig, path, 3);
2365 for (
size_t p = in_start(u); p < in_start(u + 1); ++p)
2366 closing(ig.arcs(incoming(p)).src) =
none;
2373 if constexpr (std::is_floating_point_v<Cost_Type>)
2376 <<
"most_negative_cycle_up_to_3(): cycle cost out of range";
2381 <<
"most_negative_cycle_up_to_3(): cycle cost out of range";
2389 for (
size_t i = 0; i < best.
length; ++i)
2391 const auto & arc = ig.arcs(best.
arcs[i]);
Exception handling system with formatted messages for Aleph-w.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
#define ah_logic_error_if(C)
Throws std::logic_error if condition holds.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Node Node
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void empty() noexcept
Empties the container.
constexpr bool is_empty() const noexcept
Checks if the container is empty.
void swap(Array &s) noexcept
Swap this with s
T & get_last()
Return a modifiable reference to the last element.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
Default distance accessor for arc weights.
Doubly-linked list (defined in tpl_dynList.H).
T & append(const T &item)
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Graph_Node< Node_Info > Node
The graph type.
Graph_Arc< Arc_Info > Arc
The node class type.
Filtered iterator on the nodes of a graph.
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.
Array< size_t > positions_
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.
Node_Index(const size_t n)
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.
Exact_Sum< Cost_Type > difference_
size_t length
Zero until the first cycle is offered.
Exact_Sum< Cost_Type > candidate_
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.
Exact_Sum< Cost_Type > best_
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.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
bool is_digraph() const noexcept
Return true if the graph this is directed.
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
constexpr size_t size() const noexcept
Returns the number of entries in the table.
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)
DynArray< Graph::Arc * > arcs
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
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.
std::decay_t< typename HeadC::Item_Type > T
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
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.
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.
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...
Exact_Sum< Cost_Type > difference_
void store(const Cost_Type &c, const size_t *candidate, const size_t length)
Exact_Sum< Cost_Type > exact_best_
Best_Cycle(const Indexed_Graph< GT, Cost_Type > &ig, const size_t L)
Prepare the rounding filter for cycles of at most L arcs.
Exact_Sum< Cost_Type > exact_candidate_
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)
Array< size_t > st_nodes
Node stack.
Positional snapshot of a graph: nodes by position and the arcs accepted by the arc filter,...
Array< typename GT::Node * > nodes
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 > start
n + 1 offsets.
Array< size_t > arc
Index of the arc in Indexed_Graph::arcs.
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)
Dynamic array container with automatic resizing.
Generic graph and digraph implementations.