Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Min_Mean_Cycle.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
78#ifndef MIN_MEAN_CYCLE_H
79#define MIN_MEAN_CYCLE_H
80
81#include <ah-graph-concepts.H>
82
83#include <cmath>
84#include <cstddef>
85#include <limits>
86#include <type_traits>
87#include <utility>
88
89#include <ah-errors.H>
91#include <htlist.H>
92#include <tpl_array.H>
93#include <tpl_dynMapTree.H>
94
98#if defined(__SIZEOF_INT128__) and not defined(_MSC_VER)
99#define ALEPH_KARP_INT128 1
100#else
101#define ALEPH_KARP_INT128 0
102#endif
103
104namespace Aleph {
111template <AlephGraph GT, typename Cost_Type>
113{
114 bool has_cycle = false;
115 long double minimum_mean = std::numeric_limits<long double>::infinity();
117 nullptr;
118
119 Cost_Type cycle_total_cost = Cost_Type{0};
120 size_t cycle_length = 0;
121
124};
125
134{
135 bool has_cycle = false;
136 long double minimum_mean = std::numeric_limits<long double>::infinity();
137};
138
139namespace min_mean_cycle_detail {
140#if ALEPH_KARP_INT128
142__extension__ typedef __int128 karp_int128_t;
144__extension__ typedef unsigned __int128 karp_uint128_t;
145#endif
146
152template <AlephGraph GT, typename Cost_Type>
154{
155 size_t src_idx = 0;
156 typename GT::Arc *arc = nullptr;
157 Cost_Type weight = Cost_Type{0};
158};
159
166template <typename Cost_Type>
167void validate_finite_accumulator(const Cost_Type &value, const char *context)
168{
169 if constexpr (std::is_floating_point_v<Cost_Type>)
170 ah_domain_error_if(not std::isfinite(value)) << context;
171}
172
183template <AlephGraph GT, ArcDistance<GT> Distance, ArcFilter<GT> SA>
185 const GT &g, Distance &distance, SA &sa, Array<typename GT::Node *> &nodes)
186{
187 using Node = typename GT::Node;
188 using Arc = typename GT::Arc;
189 using Cost_Type = typename Distance::Distance_Type;
190 using Incoming = Incoming_Arc<GT, Cost_Type>;
191
192 static_assert(std::is_arithmetic_v<Cost_Type>,
193 "Karp minimum mean cycle requires arithmetic arc costs");
194
195 const size_t n = g.get_num_nodes();
196 nodes.reserve(n);
197 DynMapTree<Node *, size_t> node_to_idx;
198 size_t idx = 0;
199 for (Node_Iterator<GT> it(g); it.has_curr(); it.next_ne(), ++idx)
200 {
201 Node *node = it.get_curr_ne();
202 nodes.append(node);
203 node_to_idx.insert(node, idx);
204 }
205
206 Array<Array<Incoming>> incoming;
207 incoming.reserve(n);
208 for (size_t i = 0; i < n; ++i)
209 incoming.append(Array<Incoming>());
210
211 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
212 {
213 Arc *arc = it.get_curr_ne();
214 const Cost_Type w = distance(arc);
215 if constexpr (std::is_floating_point_v<Cost_Type>)
216 ah_domain_error_if(not std::isfinite(w))
217 << "Karp minimum mean cycle requires finite arc weights";
218
219 const size_t src_idx = node_to_idx.find(g.get_src_node(arc));
220 const size_t tgt_idx = node_to_idx.find(g.get_tgt_node(arc));
221 incoming[tgt_idx].append(Incoming{src_idx, arc, w});
222 }
223
224 return incoming;
225}
226
232template <AlephGraph GT, typename Cost_Type>
234{
235 bool has_cycle = false;
236 long double minimum_mean = std::numeric_limits<long double>::infinity();
237 size_t witness = 0;
238 Cost_Type cycle_total_cost = Cost_Type{0};
245 bool witness_fits = true;
246#if ALEPH_KARP_INT128
247 bool exact_mean = false;
248 karp_int128_t mean_num = 0;
249 size_t mean_den = 1;
250#endif
251};
252
266template <AlephGraph GT, typename Cost_Type>
267[[nodiscard]] int mean_order(const Karp_Answer<GT, Cost_Type> &a,
268 const Karp_Answer<GT, Cost_Type> &b) noexcept
269{
270#if ALEPH_KARP_INT128
271 if (a.exact_mean and b.exact_mean)
272 {
273 const karp_int128_t l = a.mean_num * static_cast<karp_int128_t>(b.mean_den);
274 const karp_int128_t r = b.mean_num * static_cast<karp_int128_t>(a.mean_den);
275 return l < r ? -1 : (r < l ? 1 : 0);
276 }
277#endif
278 return a.minimum_mean < b.minimum_mean ? -1 : (b.minimum_mean < a.minimum_mean ? 1 : 0);
279}
280
294template <typename Acc>
295[[nodiscard]] bool mean_less(const Acc c1, const size_t l1, const Acc c2, const size_t l2)
296{
297#if ALEPH_KARP_INT128
298 if constexpr (not std::is_floating_point_v<Acc>)
299 return static_cast<karp_int128_t>(c1) * static_cast<karp_int128_t>(l2) <
300 static_cast<karp_int128_t>(c2) * static_cast<karp_int128_t>(l1);
301#endif
302 return static_cast<long double>(c1) / static_cast<long double>(l1) <
303 static_cast<long double>(c2) / static_cast<long double>(l2);
304}
305
329template <bool With_Witness, typename Acc, bool Checked, bool Exact_Difference, AlephGraph GT,
330 typename Cost_Type>
332 const Array<Acc> &dp, const Array<size_t> &pred,
333 const Acc inf, const char *fn)
334{
335 using Incoming = Incoming_Arc<GT, Cost_Type>;
337 const size_t n = incoming.size();
338 const auto state_of = [n](const size_t k, const size_t v)
339 {
340 return k * n + v;
341 };
342
343 // Karp's minimum mean is min over v of max over k of
344 // (D_n(v) - D_k(v)) / (n - k). The published mean is that minimax over
345 // the rounded ratios, as the value-only call and earlier versions
346 // compute it. Two different means can round to the same long double,
347 // though, and the vertex decides which cycles the witness can take, so
348 // for integral sums where 128-bit integers exist the vertex is chosen
349 // with exact ratios (cross products) among the candidates whose rounded
350 // value is within rounding of the minimum: usually the few nodes of the
351 // best cycles, not all of them.
352 long double published = std::numeric_limits<long double>::infinity();
353 size_t best_vertex = n;
354#if ALEPH_KARP_INT128
355 constexpr bool exact_ratios =
356 not std::is_floating_point_v<Acc> and (Exact_Difference or sizeof(Acc) <= sizeof(long long));
357#endif
358 // top(v): the max over k of the rounded ratios of v, -infinity if it has
359 // none. The table is read row by row (k outer), contiguously, keeping the
360 // first max of each vertex as k grows: reading a column at a time would
361 // miss the cache at every state.
362 constexpr long double minus_inf = -std::numeric_limits<long double>::infinity();
363 Array<long double> top(n, minus_inf);
364 for (size_t k = 0; k < n; ++k)
365 for (size_t v = 0; v < n; ++v)
366 {
367 const Acc dnv = dp[state_of(n, v)];
368 const Acc dkv = dp[state_of(k, v)];
369 if (dnv == inf or dkv == inf)
370 continue;
371
372 long double num;
373 if constexpr (Exact_Difference)
374 num = static_cast<long double>(dnv - dkv);
375 else
376 num = static_cast<long double>(dnv) - static_cast<long double>(dkv);
377 const long double ratio = num / static_cast<long double>(n - k);
378 if (ratio > top(v))
379 top(v) = ratio;
380 }
381 for (size_t v = 0; v < n; ++v)
382 if (top(v) != minus_inf and top(v) < published)
383 {
384 published = top(v);
385 best_vertex = v;
386 }
387
388 if (best_vertex == n)
389 return result;
390
391 result.has_cycle = true;
392 result.minimum_mean = published;
393 result.witness = best_vertex;
394
395#if ALEPH_KARP_INT128
396 // The exact max over k of the ratios of v, the first one among equals.
397 struct Ratio
398 {
399 karp_int128_t num = 0;
400 size_t den = 1;
401 };
402 const auto ratio_less = [](const Ratio &a, const Ratio &b) -> bool
403 {
404 return a.num * static_cast<karp_int128_t>(b.den) < b.num * static_cast<karp_int128_t>(a.den);
405 };
406 // With a `bound`, it stops as soon as the max reaches it: v is then not
407 // below the bound, which is all its caller needs, and false is returned.
408 const auto exact_ratio = [&](const size_t v, Ratio &r, const Ratio *bound) -> bool
409 {
410 const Acc dnv = dp[state_of(n, v)];
411 bool has_ratio = false;
412 for (size_t k = 0; k < n; ++k)
413 if (const Acc dkv = dp[state_of(k, v)]; dkv != inf)
414 {
415 const Ratio c{static_cast<karp_int128_t>(dnv) - static_cast<karp_int128_t>(dkv), n - k};
416 if (not has_ratio or ratio_less(r, c))
417 {
418 r = c;
419 if (bound != nullptr and not ratio_less(r, *bound))
420 return false;
421 }
422 has_ratio = true;
423 }
424 return true;
425 };
426
427 // Candidates: vertices whose rounded value may round an exact minimum.
428 // Each rounded ratio is within two roundings of the exact one when the
429 // difference of sums reaches long double exactly (128-bit sums, or a long
430 // double that holds 64-bit integers); otherwise every vertex is a
431 // candidate.
432 Array<size_t> candidates;
433 Ratio best;
434 if constexpr (exact_ratios)
435 {
436 constexpr bool relative = Exact_Difference or std::numeric_limits<long double>::digits >= 64;
437 constexpr long double slack = 8 * std::numeric_limits<long double>::epsilon();
438 for (size_t v = 0; v < n; ++v)
439 if (top(v) != minus_inf and
440 (not relative or top(v) - published <= slack * (std::fabs(top(v)) + std::fabs(published))))
441 candidates.append(v);
442
443 // With one rounding per ratio (a long double that holds the 64-bit
444 // differences exactly), two different ratios with denominators at
445 // most n differ by 1/n^2 at least, far more than their rounding when
446 // |minimum| n^2 is below 2^(digits - 5). The rounded order near the
447 // minimum is then the exact one, and equal ratios round alike: the
448 // rounded choice stands, and only its ratio is needed. That avoids
449 // reading the columns of the table, a cache miss each, of every tie.
450 constexpr bool single = not Exact_Difference and std::numeric_limits<long double>::digits >= 64;
451 const long double nn = static_cast<long double>(n) * static_cast<long double>(n);
452 if (single and
453 std::fabs(published) * nn < std::ldexp(1.0L, std::numeric_limits<long double>::digits - 5))
454 (void) exact_ratio(best_vertex, best, nullptr);
455 else
456 {
457 best_vertex = n;
458 for (size_t i = 0; i < candidates.size(); ++i)
459 if (Ratio r; exact_ratio(candidates(i), r, best_vertex == n ? nullptr : &best))
460 {
461 best = r;
462 best_vertex = candidates(i);
463 }
464 }
465 result.witness = best_vertex;
466 result.exact_mean = true;
467 result.mean_num = best.num;
468 result.mean_den = best.den;
469 }
470#endif
471 if constexpr (With_Witness)
472 {
473 constexpr size_t none = std::numeric_limits<size_t>::max();
474 const auto add = [](const Acc a, const Cost_Type w) -> Acc
475 {
476 if constexpr (Checked)
477 return shortest_path_detail::checked_add(a, static_cast<Acc>(w));
478 else
479 return a + static_cast<Acc>(w);
480 };
481
482 // Whether a sum fits `Cost_Type`, the type of the reported cost.
483 const auto fits = [](const Acc c) -> bool
484 {
485 if constexpr (std::is_same_v<Acc, Cost_Type>)
486 {
487 (void) c;
488 return true;
489 }
490 else
491 return not (c > static_cast<Acc>(std::numeric_limits<Cost_Type>::max()) or
492 c < static_cast<Acc>(std::numeric_limits<Cost_Type>::lowest()));
493 };
494
495 struct Witness
496 {
497 Acc cost = Acc{0};
498 size_t length = 0;
501 };
502
503 // The best simple cycle of the n-step walk that ends at `vertex`.
504 const auto extract = [&](const size_t vertex, Witness &w) -> bool
505 {
506 // Extract the walk from the predecessor table.
507 Array<size_t> reverse_walk_nodes;
508 reverse_walk_nodes.reserve(n + 1);
509 Array<const Incoming *> reverse_walk_arcs;
510 reverse_walk_arcs.reserve(n);
511
512 size_t curr = vertex;
513 reverse_walk_nodes.append(curr);
514
515 for (size_t k = n; k > 0; --k)
516 {
517 const size_t pos = pred[state_of(k, curr)];
518 if (pos == none)
519 break;
520
521 const Incoming &in = incoming[curr][pos];
522 reverse_walk_arcs.append(&in);
523 curr = in.src_idx;
524 reverse_walk_nodes.append(curr);
525 }
526
527 if (reverse_walk_nodes.size() < 2)
528 return false;
529
530 Array<size_t> walk_nodes;
531 walk_nodes.reserve(reverse_walk_nodes.size());
532 for (size_t i = reverse_walk_nodes.size(); i > 0; --i)
533 walk_nodes.append(reverse_walk_nodes[i - 1]);
534
535 Array<const Incoming *> walk_arcs;
536 walk_arcs.reserve(reverse_walk_arcs.size());
537 for (size_t i = reverse_walk_arcs.size(); i > 0; --i)
538 walk_arcs.append(reverse_walk_arcs[i - 1]);
539
540 // Decompose the walk into simple cycles with a stack: when the
541 // walk reaches a node already on the stack, the nodes above it
542 // close a simple cycle, which is popped. The walk is then a simple
543 // path to the chosen vertex plus those cycles, and the argument of
544 // Karp's theorem shows that in exact arithmetic every one of them
545 // has the minimum mean, so the first one would do. Floating-point
546 // tables are rounded, so the best of them is kept: compared
547 // exactly for integral costs (cross-multiplied means), in long
548 // double otherwise. Among equal exact means, a cost that fits
549 // `Cost_Type` is preferred.
550 Array<size_t> stack_nodes;
551 stack_nodes.reserve(n + 1);
552 Array<const Incoming *> stack_arcs; // stack_arcs[t] leaves stack_nodes[t]
553 stack_arcs.reserve(n);
554 Array<size_t> depth(n, none); // position of a node on the stack
555
556 bool found_cycle = false;
557 stack_nodes.append(walk_nodes[0]);
558 depth[walk_nodes[0]] = 0;
559 for (size_t i = 0; i < walk_arcs.size(); ++i)
560 {
561 const size_t x = walk_nodes[i + 1];
562 ah_runtime_error_if(x >= n) << fn << "(): invalid witness node index";
563 stack_arcs.append(walk_arcs[i]);
564 if (depth[x] == none)
565 {
566 depth[x] = stack_nodes.size();
567 stack_nodes.append(x);
568 continue;
569 }
570
571 const size_t j = depth[x]; // the cycle is stack_nodes[j..] back to x
572 const size_t len = stack_arcs.size() - j;
573 Acc cycle_cost = Acc{0};
574 for (size_t t = j; t < stack_arcs.size(); ++t)
575 {
576 cycle_cost = add(cycle_cost, stack_arcs[t]->weight);
578 cycle_cost, "Karp minimum mean cycle witness accumulation became non-finite");
579 }
580
581 bool better = not found_cycle or mean_less(cycle_cost, len, w.cost, w.length);
582#if ALEPH_KARP_INT128
583 if constexpr (exact_ratios)
584 if (not better and not fits(w.cost) and fits(cycle_cost) and
585 not mean_less(w.cost, w.length, cycle_cost, len))
586 better = true;
587#endif
588 if (better)
589 {
590 found_cycle = true;
591 w.cost = cycle_cost;
592 w.length = len;
593 w.nodes = Array<size_t>();
594 w.arcs = Array<const Incoming *>();
595 w.nodes.reserve(len + 1);
596 w.arcs.reserve(len);
597 for (size_t t = j; t < stack_arcs.size(); ++t)
598 {
599 w.nodes.append(stack_nodes[t]);
600 w.arcs.append(stack_arcs[t]);
601 }
602 w.nodes.append(x);
603 }
604
605 while (stack_nodes.size() > j + 1)
606 {
607 depth[stack_nodes.get_last()] = none;
608 (void) stack_nodes.remove_last();
609 }
610 while (stack_arcs.size() > j)
611 (void) stack_arcs.remove_last();
612 }
613
614 return found_cycle;
615 };
616
617 Witness witness;
618 if (not extract(best_vertex, witness))
619 return result;
620
621#if ALEPH_KARP_INT128
622 // If its cost does not fit, another vertex of the same exact mean
623 // can end a walk with a minimum-mean cycle that does.
624 if constexpr (exact_ratios and not std::is_same_v<Acc, Cost_Type>)
625 for (size_t i = 0; not fits(witness.cost) and i < candidates.size(); ++i)
626 {
627 const size_t v = candidates(i);
628 Ratio r;
629 Witness other;
630 if (v != best_vertex and exact_ratio(v, r, nullptr) and not ratio_less(best, r) and
631 extract(v, other) and fits(other.cost))
632 {
633 witness = std::move(other);
634 result.witness = v;
635 }
636 }
637#endif
638
639 if (not fits(witness.cost))
640 {
641 result.witness_fits = false;
642 return result;
643 }
644
645 result.cycle_total_cost = static_cast<Cost_Type>(witness.cost);
646 result.cycle_nodes = std::move(witness.nodes);
647 result.cycle_arcs.reserve(witness.arcs.size());
648 result.cycle_weights.reserve(witness.arcs.size());
649 for (size_t t = 0; t < witness.arcs.size(); ++t)
650 {
651 result.cycle_arcs.append(witness.arcs[t]->arc);
652 result.cycle_weights.append(witness.arcs[t]->weight);
653 }
654 }
655
656 return result;
657}
658
678template <bool With_Witness, typename Acc, bool Checked, bool Exact_Difference, AlephGraph GT,
679 typename Cost_Type>
681 const Acc inf, const char *fn)
682{
683 using Incoming = Incoming_Arc<GT, Cost_Type>;
684
685 const auto add = [](const Acc a, const Cost_Type w) -> Acc
686 {
687 if constexpr (Checked)
688 return shortest_path_detail::checked_add(a, static_cast<Acc>(w));
689 else
690 return a + static_cast<Acc>(w);
691 };
692
694 const size_t n = incoming.size();
695 if (n == 0)
696 return result;
697
698 const size_t total_states = (n + 1) * n;
699 constexpr size_t none = std::numeric_limits<size_t>::max();
700
701 Array<Acc> dp(total_states, inf);
702 // Position, in `incoming[v]`, of the arc that reaches state (k, v).
704 if constexpr (With_Witness)
705 pred = Array<size_t>(total_states, none);
706
707 const auto state_of = [n](const size_t k, const size_t v)
708 {
709 return k * n + v;
710 };
711
712 for (size_t v = 0; v < n; ++v)
713 dp[state_of(0, v)] = Acc{0};
714
715 for (size_t k = 1; k <= n; ++k)
716 for (size_t v = 0; v < n; ++v)
717 {
718 Acc best = inf;
719 size_t best_pos = none;
720 const Array<Incoming> &in_v = incoming[v];
721
722 for (size_t pos = 0; pos < in_v.size(); ++pos)
723 {
724 const Incoming &in = in_v[pos];
725 const Acc prev = dp[state_of(k - 1, in.src_idx)];
726 if (prev == inf)
727 continue;
728
729 const Acc cand = add(prev, in.weight);
731 "Karp minimum mean cycle accumulation became non-finite");
732
733 if (best_pos == none or cand < best or
734 (cand == best and in.src_idx < in_v[best_pos].src_idx))
735 {
736 best = cand;
737 best_pos = pos;
738 }
739 }
740
741 dp[state_of(k, v)] = best;
742 if constexpr (With_Witness)
743 pred[state_of(k, v)] = best_pos;
744 }
745
746 return karp_answer<With_Witness, Acc, Checked, Exact_Difference>(incoming, dp, pred, inf, fn);
747}
748
750enum class Karp_Sums
751{
753 Long_Long,
755 Int128
756};
757
768template <AlephGraph GT, typename Cost_Type>
770{
771 if constexpr (std::is_integral_v<Cost_Type> and
772 std::numeric_limits<Cost_Type>::max() <= std::numeric_limits<long long>::max())
773 {
774 constexpr long long ll_max = std::numeric_limits<long long>::max();
775 unsigned long long max_abs = 0; // max |w|, LLONG_MIN included
776 for (size_t v = 0; v < incoming.size(); ++v)
777 for (size_t pos = 0; pos < incoming[v].size(); ++pos)
778 {
779 const long long w = static_cast<long long>(incoming[v][pos].weight);
780 const unsigned long long a = w < 0 ? 0ULL - static_cast<unsigned long long>(w)
781 : static_cast<unsigned long long>(w);
782 if (a > max_abs)
783 max_abs = a;
784 }
785
786 const unsigned long long n = incoming.size();
787 if (max_abs == 0 or n <= (static_cast<unsigned long long>(ll_max) - 1) / max_abs)
789#if ALEPH_KARP_INT128
790 return Karp_Sums::Int128;
791#else
793#endif
794 }
795 else
797}
798
815template <bool With_Witness, typename Cost_Type>
816[[nodiscard]] bool karp_table_bytes(const size_t n, const Karp_Sums sums, size_t &bytes) noexcept
817{
818 constexpr size_t max = std::numeric_limits<size_t>::max();
819 if (n == 0)
820 {
821 bytes = 0;
822 return true;
823 }
824 if (n > max - 1 or n + 1 > max / n)
825 return false;
826
827 const size_t entries = (n + 1) * n;
828 size_t reserved = 1;
829 while (reserved < entries)
830 {
831 if (reserved > max / 2)
832 return false;
833 reserved <<= 1;
834 }
835
836 size_t sum_bytes = sizeof(Cost_Type);
838 sum_bytes = sizeof(long long);
839#if ALEPH_KARP_INT128
840 else if (sums == Karp_Sums::Int128)
841 sum_bytes = sizeof(karp_int128_t);
842#endif
843 const size_t per_entry = sum_bytes + (With_Witness ? sizeof(size_t) : 0);
844 if (reserved > max / per_entry)
845 return false;
846 bytes = reserved * per_entry;
847 return true;
848}
849
896template <bool With_Witness, AlephGraph GT, typename Cost_Type>
898 const char *fn)
899{
900 const Karp_Sums sums = karp_sums(incoming);
901 size_t bytes = 0;
902 const bool fits = karp_table_bytes<With_Witness, Cost_Type>(incoming.size(), sums, bytes);
903 ah_overflow_error_if(not fits) << fn << "(): DP table size overflow";
904
905 if constexpr (std::is_floating_point_v<Cost_Type>)
906 return karp_table<With_Witness, Cost_Type, true, false>(
907 incoming, std::numeric_limits<Cost_Type>::infinity(), fn);
908 else if constexpr (std::is_integral_v<Cost_Type> and
909 std::numeric_limits<Cost_Type>::max() <= std::numeric_limits<long long>::max())
910 {
911 constexpr long long ll_max = std::numeric_limits<long long>::max();
912 if (sums == Karp_Sums::Long_Long)
913 return karp_table<With_Witness, long long, false, false>(incoming, ll_max, fn);
914#if ALEPH_KARP_INT128
915 // n * max|w| < 2^64 * 2^63: no sum, nor the difference of two, overflows.
916 constexpr karp_int128_t int128_max =
917 static_cast<karp_int128_t>(~static_cast<karp_uint128_t>(0) >> 1);
918 return karp_table<With_Witness, karp_int128_t, false, true>(incoming, int128_max, fn);
919#else
920 return karp_table<With_Witness, long long, true, false>(incoming, ll_max, fn);
921#endif
922 }
923 else
924 return karp_table<With_Witness, Cost_Type, true, false>(
925 incoming, std::numeric_limits<Cost_Type>::max(), fn);
926}
927} // namespace min_mean_cycle_detail
928
964template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
966 const GT &g, Distance distance = Distance(), SA sa = SA())
967{
968 using Node = typename GT::Node;
969 using Cost_Type = typename Distance::Distance_Type;
970
971 ah_domain_error_if(not g.is_digraph()) << "karp_minimum_mean_cycle(): graph must be directed";
972
974 const auto incoming = min_mean_cycle_detail::incoming_lists(g, distance, sa, nodes);
975 const auto answer =
976 min_mean_cycle_detail::karp_solve<true, GT, Cost_Type>(incoming, "karp_minimum_mean_cycle");
977
979 if (not answer.has_cycle)
980 return result;
981 ah_overflow_error_if(not answer.witness_fits)
982 << "karp_minimum_mean_cycle(): the cost of the witness cycle does not fit the cost type";
983
984 result.has_cycle = true;
985 result.minimum_mean = answer.minimum_mean;
986 result.witness_node = nodes[answer.witness];
987 result.cycle_total_cost = answer.cycle_total_cost;
988 result.cycle_length = answer.cycle_arcs.size();
989 for (size_t i = 0; i < answer.cycle_nodes.size(); ++i)
990 result.cycle_nodes.append(nodes[answer.cycle_nodes[i]]);
991 for (size_t i = 0; i < answer.cycle_arcs.size(); ++i)
992 result.cycle_arcs.append(answer.cycle_arcs[i]);
993
994 return result;
995}
996
1022template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1024 SA sa = SA())
1025{
1026 using Node = typename GT::Node;
1027 using Cost_Type = typename Distance::Distance_Type;
1028
1030 << "karp_minimum_mean_cycle_value(): graph must be directed";
1031
1033 const auto incoming = min_mean_cycle_detail::incoming_lists(g, distance, sa, nodes);
1034 const auto answer = min_mean_cycle_detail::karp_solve<false, GT, Cost_Type>(
1035 incoming, "karp_minimum_mean_cycle_value");
1036
1038 result.has_cycle = answer.has_cycle;
1039 result.minimum_mean = answer.minimum_mean;
1040 return result;
1041}
1042
1047template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1049 SA sa = SA())
1050{
1051 return karp_minimum_mean_cycle_value<GT, Distance, SA>(g, std::move(distance), std::move(sa));
1052}
1053
1058template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1060 const GT &g, Distance distance = Distance(), SA sa = SA())
1061{
1062 return karp_minimum_mean_cycle<GT, Distance, SA>(g, std::move(distance), std::move(sa));
1063}
1064
1069template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1071{
1074
1075public:
1076 Karp_Minimum_Mean_Cycle(Distance distance = Distance(), SA sa = SA())
1077 : distance_(std::move(distance)), sa_(std::move(sa))
1078 {
1079 // empty
1080 }
1081
1083 {
1084 return karp_minimum_mean_cycle<GT, Distance, SA>(g, distance_, sa_);
1085 }
1086};
1087
1092template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1094{
1097
1098public:
1100 : distance_(std::move(distance)), sa_(std::move(sa))
1101 {
1102 // empty
1103 }
1104
1106 {
1107 return karp_minimum_mean_cycle_value<GT, Distance, SA>(g, distance_, sa_);
1108 }
1109};
1110} // namespace Aleph
1111
1112#endif // MIN_MEAN_CYCLE_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_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
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
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
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
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Generic key-value map implemented on top of a binary search tree.
Pair * append(const Key &key, const Data &data)
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Data & find(const Key &key)
Find the value associated with key.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Functor wrapper for value-only minimum mean cycle.
Min_Mean_Cycle_Value_Result operator()(const GT &g) const
Karp_Minimum_Mean_Cycle_Value(Distance distance=Distance(), SA sa=SA())
Functor wrapper for Karp minimum mean cycle.
Min_Mean_Cycle_Result< GT, typename Distance::Distance_Type > operator()(const GT &g) const
Karp_Minimum_Mean_Cycle(Distance distance=Distance(), SA sa=SA())
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
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
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
A graph usable by the graph algorithms.
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Min_Mean_Cycle_Value_Result minimum_mean_cycle_value(const GT &g, Distance distance=Distance(), SA sa=SA())
Alias for karp_minimum_mean_cycle_value().
Min_Mean_Cycle_Result< GT, typename Distance::Distance_Type > minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA())
Alias for karp_minimum_mean_cycle().
Min_Mean_Cycle_Value_Result karp_minimum_mean_cycle_value(const GT &g, Distance distance=Distance(), SA sa=SA())
Compute only the minimum mean value (without witness walk).
Min_Mean_Cycle_Result< GT, typename Distance::Distance_Type > karp_minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA())
Compute minimum mean cycle by Karp's algorithm.
Singly linked list implementations with head-tail access.
Freq_Node * pred
Predecessor node in level-order traversal.
Karp_Sums karp_sums(const Array< Array< Incoming_Arc< GT, Cost_Type > > > &incoming)
Choose how the sums of Karp's table over incoming are kept.
Karp_Answer< GT, Cost_Type > karp_answer(const Array< Array< Incoming_Arc< GT, Cost_Type > > > &incoming, const Array< Acc > &dp, const Array< size_t > &pred, const Acc inf, const char *fn)
Karp's minimum mean, its vertex and the witness, from a filled table; see karp_table().
bool karp_table_bytes(const size_t n, const Karp_Sums sums, size_t &bytes) noexcept
Bytes that karp_solve() reserves for the tables of a graph of n nodes whose sums are kept as sums.
Karp_Answer< GT, Cost_Type > karp_table(const Array< Array< Incoming_Arc< GT, Cost_Type > > > &incoming, const Acc inf, const char *fn)
Karp's table, with sums kept in Acc; see karp_solve().
int mean_order(const Karp_Answer< GT, Cost_Type > &a, const Karp_Answer< GT, Cost_Type > &b) noexcept
Order of the minimum means of two answers: -1, 0 or 1.
Array< Array< Incoming_Arc< GT, typename Distance::Distance_Type > > > incoming_lists(const GT &g, Distance &distance, SA &sa, Array< typename GT::Node * > &nodes)
Build the incoming lists of the arcs of g accepted by sa, in arc-iteration order, reading each weight...
bool mean_less(const Acc c1, const size_t l1, const Acc c2, const size_t l2)
Whether the mean c1 / l1 is smaller than c2 / l2.
void validate_finite_accumulator(const Cost_Type &value, const char *context)
Throw std::domain_error with context if a floating-point value is not finite.
Karp_Answer< GT, Cost_Type > karp_solve(const Array< Array< Incoming_Arc< GT, Cost_Type > > > &incoming, const char *fn)
Karp's algorithm on a graph given by its incoming lists.
Karp_Sums
How karp_solve() keeps the sums of a table (see there).
@ Long_Long_Checked
long long, every addition checked (no 128-bit integers).
@ Int128
128-bit integers, which the bound keeps the sums inside.
@ Cost_Type_Checked
The cost type itself, every addition checked.
@ Long_Long
long long, which the bound keeps the sums inside.
T checked_add(const T &a, const T &b)
Safely add two distance values with overflow checking.
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
STL namespace.
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 minimum mean cycle computation.
size_t cycle_length
Number of arcs in witness cycle.
Cost_Type cycle_total_cost
Weight sum of witness cycle.
GT::Node * witness_node
Vertex Karp's walk ends at (not necessarily on the cycle).
bool has_cycle
True if at least one directed cycle exists.
DynList< typename GT::Node * > cycle_nodes
Witness simple cycle (first node repeated at end).
DynList< typename GT::Arc * > cycle_arcs
Witness arcs aligned with cycle_nodes.
Lightweight minimum-mean-cycle value result.
bool has_cycle
True if at least one directed cycle exists.
Arc entering a node, as Karp's table reads it.
size_t src_idx
Position of the source node.
Cost_Type weight
Its weight, read once.
GT::Arc * arc
The arc of the graph.
Answer of karp_solve(), in the node positions of its input.
bool has_cycle
True if at least one directed cycle exists.
Cost_Type cycle_total_cost
Weight sum of the witness.
bool witness_fits
False if no minimum-mean cycle the walks gave has a cost that fits Cost_Type; there is then no witnes...
size_t witness
Position of the vertex the walk ends at (if has_cycle).
Array< size_t > cycle_nodes
A simple cycle, by positions, the first one repeated at the end; may be empty.
Array< Cost_Type > cycle_weights
Their weights, as read.
Array< typename GT::Arc * > cycle_arcs
Witness arcs, aligned with cycle_nodes.
Distance accessor.
DynList< int > l1
DynList< int > l2
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Dynamic key-value map based on balanced binary search trees.
DynList< int > l