78#ifndef MIN_MEAN_CYCLE_H
79#define MIN_MEAN_CYCLE_H
98#if defined(__SIZEOF_INT128__) and not defined(_MSC_VER)
99#define ALEPH_KARP_INT128 1
101#define ALEPH_KARP_INT128 0
111template <AlephGraph GT,
typename Cost_Type>
115 long double minimum_mean = std::numeric_limits<long double>::infinity();
136 long double minimum_mean = std::numeric_limits<long double>::infinity();
139namespace min_mean_cycle_detail {
142__extension__
typedef __int128 karp_int128_t;
144__extension__
typedef unsigned __int128 karp_uint128_t;
152template <AlephGraph GT,
typename Cost_Type>
166template <
typename Cost_Type>
169 if constexpr (std::is_floating_point_v<Cost_Type>)
183template <AlephGraph GT, ArcDistance<GT> Distance, ArcFilter<GT> SA>
192 static_assert(std::is_arithmetic_v<Cost_Type>,
193 "Karp minimum mean cycle requires arithmetic arc costs");
201 Node *node = it.get_curr_ne();
203 node_to_idx.
insert(node, idx);
208 for (
size_t i = 0; i < n; ++i)
213 Arc *arc = it.get_curr_ne();
214 const Cost_Type
w = distance(arc);
215 if constexpr (std::is_floating_point_v<Cost_Type>)
217 <<
"Karp minimum mean cycle requires finite arc weights";
221 incoming[tgt_idx].
append(Incoming{src_idx, arc,
w});
232template <AlephGraph GT,
typename Cost_Type>
236 long double minimum_mean = std::numeric_limits<long double>::infinity();
247 bool exact_mean =
false;
248 karp_int128_t mean_num = 0;
266template <AlephGraph GT,
typename Cost_Type>
271 if (a.exact_mean
and b.exact_mean)
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);
278 return a.minimum_mean < b.minimum_mean ? -1 : (b.minimum_mean < a.minimum_mean ? 1 : 0);
294template <
typename Acc>
295[[nodiscard]]
bool mean_less(
const Acc c1,
const size_t l1,
const Acc c2,
const size_t l2)
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);
302 return static_cast<long double>(c1) /
static_cast<long double>(
l1) <
303 static_cast<long double>(c2) /
static_cast<long double>(
l2);
329template <
bool With_Witness,
typename Acc,
bool Checked,
bool Exact_Difference,
AlephGraph GT,
333 const Acc inf,
const char *fn)
337 const size_t n = incoming.size();
338 const auto state_of = [n](
const size_t k,
const size_t v)
352 long double published = std::numeric_limits<long double>::infinity();
353 size_t best_vertex = n;
355 constexpr bool exact_ratios =
356 not std::is_floating_point_v<Acc>
and (Exact_Difference or
sizeof(Acc) <=
sizeof(
long long));
362 constexpr long double minus_inf = -std::numeric_limits<long double>::infinity();
364 for (
size_t k = 0;
k < n; ++
k)
365 for (
size_t v = 0; v < n; ++v)
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)
373 if constexpr (Exact_Difference)
374 num =
static_cast<long double>(dnv - dkv);
376 num =
static_cast<long double>(dnv) -
static_cast<long double>(dkv);
377 const long double ratio = num /
static_cast<long double>(n -
k);
381 for (
size_t v = 0; v < n; ++v)
382 if (top(v) != minus_inf
and top(v) < published)
388 if (best_vertex == n)
399 karp_int128_t num = 0;
402 const auto ratio_less = [](
const Ratio &a,
const Ratio &b) ->
bool
404 return a.num *
static_cast<karp_int128_t
>(b.den) < b.num *
static_cast<karp_int128_t
>(a.den);
408 const auto exact_ratio = [&](
const size_t v, Ratio &
r,
const Ratio *bound) ->
bool
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)
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))
419 if (bound !=
nullptr and not ratio_less(
r, *bound))
434 if constexpr (exact_ratios)
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))))
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);
453 std::fabs(published) * nn < std::ldexp(1.0L, std::numeric_limits<long double>::digits - 5))
454 (
void) exact_ratio(best_vertex, best,
nullptr);
458 for (
size_t i = 0; i < candidates.
size(); ++i)
459 if (Ratio
r; exact_ratio(candidates(i),
r, best_vertex == n ?
nullptr : &best))
462 best_vertex = candidates(i);
466 result.exact_mean =
true;
467 result.mean_num = best.num;
468 result.mean_den = best.den;
471 if constexpr (With_Witness)
473 constexpr size_t none = std::numeric_limits<size_t>::max();
474 const auto add = [](
const Acc a,
const Cost_Type
w) -> Acc
476 if constexpr (Checked)
479 return a +
static_cast<Acc
>(
w);
483 const auto fits = [](
const Acc c) ->
bool
485 if constexpr (std::is_same_v<Acc, Cost_Type>)
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()));
504 const auto extract = [&](
const size_t vertex, Witness &
w) ->
bool
508 reverse_walk_nodes.
reserve(n + 1);
512 size_t curr = vertex;
513 reverse_walk_nodes.
append(curr);
515 for (
size_t k = n;
k > 0; --
k)
517 const size_t pos =
pred[state_of(
k, curr)];
521 const Incoming &in = incoming[curr][pos];
522 reverse_walk_arcs.
append(&in);
524 reverse_walk_nodes.
append(curr);
527 if (reverse_walk_nodes.
size() < 2)
532 for (
size_t i = reverse_walk_nodes.
size(); i > 0; --i)
533 walk_nodes.
append(reverse_walk_nodes[i - 1]);
537 for (
size_t i = reverse_walk_arcs.
size(); i > 0; --i)
538 walk_arcs.
append(reverse_walk_arcs[i - 1]);
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)
561 const size_t x = walk_nodes[i + 1];
563 stack_arcs.
append(walk_arcs[i]);
564 if (depth[x] ==
none)
566 depth[x] = stack_nodes.
size();
571 const size_t j = depth[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)
576 cycle_cost = add(cycle_cost, stack_arcs[t]->weight);
578 cycle_cost,
"Karp minimum mean cycle witness accumulation became non-finite");
581 bool better = not found_cycle or
mean_less(cycle_cost, len,
w.cost,
w.length);
583 if constexpr (exact_ratios)
584 if (not better
and not fits(
w.cost)
and fits(cycle_cost)
and
595 w.nodes.reserve(len + 1);
597 for (
size_t t = j; t < stack_arcs.
size(); ++t)
599 w.nodes.append(stack_nodes[t]);
600 w.arcs.append(stack_arcs[t]);
605 while (stack_nodes.
size() > j + 1)
610 while (stack_arcs.
size() > j)
618 if (not extract(best_vertex, witness))
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)
627 const size_t v = candidates(i);
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))
633 witness = std::move(other);
639 if (not fits(witness.cost))
649 for (
size_t t = 0; t < witness.arcs.size(); ++t)
678template <
bool With_Witness,
typename Acc,
bool Checked,
bool Exact_Difference,
AlephGraph GT,
681 const Acc inf,
const char *fn)
685 const auto add = [](
const Acc a,
const Cost_Type
w) -> Acc
687 if constexpr (Checked)
690 return a +
static_cast<Acc
>(
w);
694 const size_t n = incoming.size();
698 const size_t total_states = (n + 1) * n;
699 constexpr size_t none = std::numeric_limits<size_t>::max();
704 if constexpr (With_Witness)
707 const auto state_of = [n](
const size_t k,
const size_t v)
712 for (
size_t v = 0; v < n; ++v)
713 dp[state_of(0, v)] = Acc{0};
715 for (
size_t k = 1;
k <= n; ++
k)
716 for (
size_t v = 0; v < n; ++v)
719 size_t best_pos =
none;
722 for (
size_t pos = 0; pos < in_v.
size(); ++pos)
724 const Incoming &in = in_v[pos];
725 const Acc prev = dp[state_of(
k - 1, in.src_idx)];
729 const Acc cand = add(prev, in.weight);
731 "Karp minimum mean cycle accumulation became non-finite");
733 if (best_pos ==
none or cand < best or
734 (cand == best
and in.src_idx < in_v[best_pos].src_idx))
741 dp[state_of(
k, v)] = best;
742 if constexpr (With_Witness)
743 pred[state_of(
k, v)] = best_pos;
746 return karp_answer<With_Witness, Acc, Checked, Exact_Difference>(incoming, dp,
pred, inf, fn);
768template <AlephGraph GT,
typename Cost_Type>
771 if constexpr (std::is_integral_v<Cost_Type>
and
772 std::numeric_limits<Cost_Type>::max() <= std::numeric_limits<long long>::max())
774 constexpr long long ll_max = std::numeric_limits<long long>::max();
775 unsigned long long max_abs = 0;
776 for (
size_t v = 0; v < incoming.size(); ++v)
777 for (
size_t pos = 0; pos < incoming[v].size(); ++pos)
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);
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)
815template <
bool With_Witness,
typename Cost_Type>
818 constexpr size_t max = std::numeric_limits<size_t>::max();
824 if (n >
max - 1 or n + 1 >
max / n)
827 const size_t entries = (n + 1) * n;
829 while (reserved < entries)
831 if (reserved >
max / 2)
836 size_t sum_bytes =
sizeof(Cost_Type);
838 sum_bytes =
sizeof(
long long);
841 sum_bytes =
sizeof(karp_int128_t);
843 const size_t per_entry = sum_bytes + (With_Witness ?
sizeof(size_t) : 0);
844 if (reserved >
max / per_entry)
846 bytes = reserved * per_entry;
896template <
bool With_Witness, AlephGraph GT,
typename Cost_Type>
902 const bool fits = karp_table_bytes<With_Witness, Cost_Type>(incoming.size(), sums, bytes);
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())
911 constexpr long long ll_max = std::numeric_limits<long long>::max();
913 return karp_table<With_Witness, long long, false, false>(incoming, ll_max, fn);
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);
920 return karp_table<With_Witness, long long, true, false>(incoming, ll_max, fn);
924 return karp_table<With_Witness, Cost_Type, true, false>(
925 incoming, std::numeric_limits<Cost_Type>::max(), fn);
964template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
976 min_mean_cycle_detail::karp_solve<true, GT, Cost_Type>(incoming,
"karp_minimum_mean_cycle");
979 if (not answer.has_cycle)
982 <<
"karp_minimum_mean_cycle(): the cost of the witness cycle does not fit the cost type";
989 for (
size_t i = 0; i < answer.cycle_nodes.size(); ++i)
991 for (
size_t i = 0; i < answer.cycle_arcs.size(); ++i)
1022template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1030 <<
"karp_minimum_mean_cycle_value(): graph must be directed";
1034 const auto answer = min_mean_cycle_detail::karp_solve<false, GT, Cost_Type>(
1035 incoming,
"karp_minimum_mean_cycle_value");
1047template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1051 return karp_minimum_mean_cycle_value<GT, Distance, SA>(g, std::move(distance), std::move(sa));
1058template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1062 return karp_minimum_mean_cycle<GT, Distance, SA>(g, std::move(distance), std::move(sa));
1069template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1084 return karp_minimum_mean_cycle<GT, Distance, SA>(g,
distance_,
sa_);
1092template <AlephGraph GT, ArcDistance<GT> Distance = Dft_Dist<GT>, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
1107 return karp_minimum_mean_cycle_value<GT, Distance, SA>(g,
distance_,
sa_);
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_runtime_error_if(C)
Throws std::runtime_error 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
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
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.
Doubly-linked list (defined in tpl_dynList.H).
T & append(const T &item)
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())
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.
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.
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
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)
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
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.
Common utilities and base class for shortest path algorithms.
Filtered iterator on all the arcs of a graph.
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.
Dynamic array container with automatic resizing.
Dynamic key-value map based on balanced binary search trees.