Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
short_negative_cycle_test.cc
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
35// Keep first: the public header must be self-contained.
36# include <Negative_Cycles.H>
37# include <gtest/gtest.h>
38# include <algorithm>
39# include <cmath>
40# include <functional>
41# include <limits>
42# include <random>
43# include <set>
44# include <tuple>
45# include <vector>
47
48using namespace Aleph;
49using namespace Negative_Cycles_Test_Support;
50
51namespace
52{
54 template <class GT, typename Cost>
55 void check_witness(const GT & g, const Short_Cycle_Result<GT, Cost> & r)
56 {
57 ASSERT_TRUE(r.has_cycle);
58 ASSERT_GE(r.length, 1u);
59 ASSERT_LE(r.length, 3u);
60 ASSERT_EQ(r.cycle_nodes.size(), r.length + 1);
61 ASSERT_EQ(r.cycle_arcs.size(), r.length);
62 std::set<typename GT::Node *> seen;
63 auto ni = r.cycle_nodes.get_it();
64 auto * first = ni.get_curr();
65 auto * current = first;
66 for (auto ai = r.cycle_arcs.get_it(); ai.has_curr(); ai.next_ne())
67 {
68 ASSERT_TRUE(seen.insert(current).second);
69 ASSERT_EQ(g.get_src_node(ai.get_curr()), current);
70 ni.next_ne();
71 ASSERT_TRUE(ni.has_curr());
72 current = ni.get_curr();
73 ASSERT_EQ(g.get_tgt_node(ai.get_curr()), current);
74 }
75 ASSERT_EQ(current, first);
76 ni.next_ne();
77 ASSERT_FALSE(ni.has_curr());
78 }
79
80 struct Optimum
81 {
82 bool exists = false;
83 long long cost = 0;
84 size_t length = 0;
85 };
86
90 Optimum exhaustive(const size_t n, const std::vector<Edge_Def> & edges, const size_t bound)
91 {
92 Optimum best;
93 std::vector<bool> seen(n, false);
94 std::function<void(size_t, size_t, long long, size_t)> visit =
95 [&](const size_t start, const size_t u, const long long cost, const size_t length)
96 {
97 if (length == bound)
98 return;
99 for (const auto & [a, v, w] : edges)
100 if (a == u)
101 {
102 if (v == start)
103 {
104 if (not best.exists or cost + w < best.cost
105 or (cost + w == best.cost and length + 1 < best.length))
106 best = {true, cost + w, length + 1};
107 }
108 else if (not seen[v])
109 {
110 seen[v] = true;
111 visit(start, v, cost + w, length + 1);
112 seen[v] = false;
113 }
114 }
115 };
116 for (size_t s = 0; s < n; ++s)
117 {
118 seen[s] = true;
119 visit(s, s, 0, 0);
120 seen[s] = false;
121 }
122 return best;
123 }
124}
125
127{
128 for (const size_t n : {0u, 5u})
129 {
130 auto b = build_graph(n, n == 0 ? std::vector<Edge_Def>{}
131 : std::vector<Edge_Def>{{0, 1, -5}, {1, 2, -4}, {3, 4, 1}});
132 for (size_t length = 0; length <= 3; ++length)
133 {
134 const auto r = most_negative_cycle_up_to_3(b.g, length);
135 EXPECT_FALSE(r.has_cycle);
136 EXPECT_FALSE(r.is_negative());
137 EXPECT_EQ(r.length, 0u);
138 EXPECT_TRUE(r.cycle_nodes.is_empty());
139 EXPECT_TRUE(r.cycle_arcs.is_empty());
140 }
141 }
142}
143
145{
146 auto b = build_graph(4, {{0, 0, 1}, {0, 1, 0}, {1, 0, -3},
147 {1, 2, 0}, {2, 0, -5}, {2, 3, -10}, {3, 0, -10}});
148 for (size_t length = 1; length <= 3; ++length)
149 {
150 const auto r = most_negative_cycle_up_to_3(b.g, length);
151 check_witness(b.g, r);
152 EXPECT_EQ(r.length, length);
153 EXPECT_EQ(r.total_cost, length == 1 ? 1 : length == 2 ? -3 : -5);
154 }
155 EXPECT_EQ(most_negative_cycle_up_to_3(b.g).total_cost, -5);
156 auto ring = build_graph(4, {{0, 1, -1}, {1, 2, -1}, {2, 3, -1}, {3, 0, -1}});
158}
159
161{
162 // Each best length-three relaxed walk costs -7: a -3 pair plus an
163 // interior -4 loop. It hides the simple -6 triangle from the DP.
164 auto b = build_graph(3, {{0, 0, -4}, {1, 1, -4}, {2, 2, -4},
165 {0, 1, -2}, {1, 2, -2}, {2, 0, -2},
166 {1, 0, -1}, {2, 1, -1}, {0, 2, -1}});
167 const auto r = most_negative_cycle_up_to_3(b.g);
168 ASSERT_TRUE(r.has_cycle);
169 EXPECT_EQ(r.total_cost, -6);
170 EXPECT_EQ(r.length, 3u);
171 check_witness(b.g, r);
172 const auto relaxed = most_negative_cycle_bounded(b.g, 3);
173 EXPECT_EQ(relaxed.total_cost, -4);
174 EXPECT_FALSE(relaxed.is_exact);
175}
176
178{
179 auto b = build_graph(1, {{0, 0, -1}});
180 int reads = 0, filters = 0;
182 Counting_Filter{&filters}).has_cycle);
184 Counting_Filter{&filters}), std::invalid_argument);
185 EXPECT_THROW(most_negative_cycle_up_to_3(b.g, SIZE_MAX), std::invalid_argument);
186 EXPECT_EQ(reads, 0);
187 EXPECT_EQ(filters, 0);
188 UGraph undirected;
190 EXPECT_THROW(most_negative_cycle_up_to_3(undirected), std::domain_error);
191}
192
194{
195 auto b = build_graph(3, {{0, 1, 10}, {0, 1, -2}, {0, 1, -2},
196 {1, 2, -1}, {2, 0, 0}});
197 const auto r = most_negative_cycle_up_to_3(b.g);
198 check_witness(b.g, r);
199 EXPECT_EQ(r.total_cost, -3);
200 EXPECT_EQ(r.cycle_arcs.get_first(), b.arcs[1]);
201 const auto hidden = most_negative_cycle_up_to_3(b.g, 3, Dft_Dist<Graph>(), Hide_Arc{b.arcs[1]});
202 EXPECT_EQ(hidden.total_cost, -3);
203 EXPECT_EQ(hidden.cycle_arcs.get_first(), b.arcs[2]);
204}
205
207{
208 auto b = build_graph(6, {{0, 1, 0}, {1, 2, 0}, {2, 0, -3},
209 {3, 4, 0}, {4, 3, -3}, {5, 5, -3}});
210 EXPECT_EQ(most_negative_cycle_up_to_3(b.g).length, 1u);
211 const auto r = most_negative_cycle_up_to_3(b.g, 3, Dft_Dist<Graph>(), Hide_Arc{b.arcs[5]});
212 EXPECT_EQ(r.length, 2u);
213 EXPECT_EQ(r.total_cost, -3);
214}
215
217{
218 const double huge = std::ldexp(1.0, 100);
220 {{0, 1, huge}, {1, 2, -1}, {2, 0, -huge}, {3, 3, -0.5}});
221 const auto r = most_negative_cycle_up_to_3(b.g);
222 check_witness(b.g, r);
223 EXPECT_EQ(r.length, 3u);
224 EXPECT_EQ(r.total_cost, -1);
225 EXPECT_TRUE(r.is_negative());
226}
227
229{
230 // 2^54 + 6 ties to even at 2^54 + 8, so the triangle's plain sum is 0 while
231 // its exact cost is -2: a two-unit misordering against a loop just above
232 // -2. Large cancellations would hide a filter that is too tight; this case
233 // fails once the rounding bound is about 32 times too small.
234 const double big = std::ldexp(1.0, 54);
235 const double loop = std::nextafter(-2.0, 0.0);
236 ASSERT_EQ(static_cast<double>(big + 6.0) + -(big + 8.0), 0.0); // the cast drops excess precision
238 {{0, 1, big}, {1, 2, 6.0}, {2, 0, -(big + 8.0)}, {3, 3, loop}});
239 const auto r = most_negative_cycle_up_to_3(b.g);
240 check_witness(b.g, r);
241 EXPECT_EQ(r.length, 3u);
242 EXPECT_EQ(r.total_cost, -2.0);
243}
244
246{
247 // Both totals round to -1, but the triangle is strictly cheaper.
248 const double tiny = std::ldexp(1.0, -100);
250 {{0, 1, -1}, {1, 2, -tiny}, {2, 0, 0}, {3, 3, -1}});
251 const auto r = most_negative_cycle_up_to_3(b.g);
252 EXPECT_EQ(r.total_cost, -1);
253 EXPECT_EQ(r.length, 3u);
254}
255
257{
258 const double m = std::numeric_limits<double>::max();
259 auto b = build_graph_generic<Float_Graph, double>(2, {{0, 0, m}, {1, 1, -m}});
260 for (size_t bound = 1; bound <= 3; ++bound)
261 EXPECT_EQ(most_negative_cycle_up_to_3(b.g, bound).total_cost, -m);
262}
263
265{
266 const long long m = std::numeric_limits<long long>::max();
267 auto one = build_graph(1, {{0, 0, m}});
268 EXPECT_EQ(most_negative_cycle_up_to_3(one.g).total_cost, m);
269 auto cycle = build_graph(2, {{0, 1, m}, {1, 0, 1}});
270 EXPECT_THROW(most_negative_cycle_up_to_3(cycle.g), std::overflow_error);
271 auto dag = build_graph(3, {{0, 1, m}, {1, 2, 1}});
273}
274
276{
277 // Independent audits of D4, D4-1. Only the total of the reported cycle
278 // has to fit the cost type. A triangle whose partial sum leaves it in
279 // cycle order is ranked by its total; one above the type is skipped
280 // instead of aborting the search for the -1 loop.
281 const long long m = std::numeric_limits<long long>::max();
282 auto ints = build_graph(4, {{0, 1, m}, {1, 2, 1}, {2, 0, -m}, {3, 3, -1}});
283 const auto ri = most_negative_cycle_up_to_3(ints.g);
285 EXPECT_EQ(ri.total_cost, -1);
286 EXPECT_EQ(ri.length, 1u);
287 auto above = build_graph(4, {{0, 1, m}, {1, 2, m}, {2, 0, 1}, {3, 3, -1}});
289
290 // Alone, the triangle of total 1 is the answer, and one below the type
291 // would be the best cycle, which has no representable cost.
292 auto alone = build_graph(3, {{0, 1, m}, {1, 2, 1}, {2, 0, -m}});
294 auto below = build_graph(3, {{0, 1, -m}, {1, 0, -m}, {2, 2, -1}});
295 EXPECT_THROW(most_negative_cycle_up_to_3(below.g), std::overflow_error);
296
297 // Floating point: DBL_MAX + DBL_MAX - DBL_MAX overflowed in cycle order.
298 const double d = std::numeric_limits<double>::max();
300 {{0, 1, d}, {1, 2, d}, {2, 0, -d}, {3, 3, -1}});
302 auto lone = build_graph_generic<Float_Graph, double>(3, {{0, 1, d}, {1, 2, d}, {2, 0, -d}});
303 const auto rl = most_negative_cycle_up_to_3(lone.g);
304 EXPECT_EQ(rl.total_cost, d);
305 EXPECT_EQ(rl.length, 3u);
306 auto infinite = build_graph_generic<Float_Graph, double>(3, {{0, 1, d}, {1, 2, d}, {2, 0, d}});
308}
309
311{
312 // Final independent review of the branch, a sibling of F1. The plain sums
313 // of the triangle DBL_MAX, 2^969, 2^969 round to DBL_MAX, but its exact
314 // total, DBL_MAX + 2^970, rounds to infinity: the exact sum overflowed and
315 // the search threw instead of skipping the candidate, as it skips those
316 // whose plain sum overflows. The triangle is offered first (no loops or
317 // pairs, lowest nodes).
318 const double d = std::numeric_limits<double>::max();
320 6, {{0, 1, d}, {1, 2, 0x1p969}, {2, 0, 0x1p969}, {3, 4, -1}, {4, 5, -1}, {5, 3, -1}});
321 const auto r = most_negative_cycle_up_to_3(b.g);
322 check_witness(b.g, r);
323 EXPECT_EQ(r.total_cost, -3);
324 EXPECT_EQ(r.length, 3u);
325
326 // Alone, it is the best cycle, and its total does not fit.
327 auto alone = build_graph_generic<Float_Graph, double>(3, {{0, 1, d}, {1, 2, 0x1p969}, {2, 0, 0x1p969}});
328 EXPECT_THROW(most_negative_cycle_up_to_3(alone.g), std::domain_error);
329}
330
332{
333 for (const double invalid : {std::numeric_limits<double>::infinity(),
334 std::numeric_limits<double>::quiet_NaN()})
335 {
336 auto b = build_graph_generic<Float_Graph, double>(2, {{0, 0, -1}, {0, 1, invalid}});
337 EXPECT_THROW(most_negative_cycle_up_to_3(b.g), std::domain_error);
339 }
340}
341
343{
344 auto b = build_graph(4, {{0, 1, -1}, {0, 1, 5}, {1, 2, 0}, {2, 0, 0}, {3, 3, -2}});
346 state.plant(b);
347 for (size_t bound = 1; bound <= 3; ++bound)
348 {
349 int reads = 0;
350 const auto r = most_negative_cycle_up_to_3(b.g, bound, Counting_Dist{&reads}, Hide_Arc{b.arcs[1]});
351 EXPECT_TRUE(r.has_cycle);
352 EXPECT_EQ(reads, 4);
353 EXPECT_TRUE(state.intact(b));
354 }
355}
356
358{
359 auto a = build_graph_generic<Arr_Digraph, long long>(3, {{0, 1, -3}, {1, 2, 1}, {2, 0, 1}});
360 const auto r = most_negative_cycle_up_to_3(a.g);
361 check_witness(a.g, r);
362 EXPECT_EQ(r.total_cost, -1);
364 auto b = build_graph_generic<U, unsigned long long>(3, {{0, 1, 2}, {1, 2, 3}, {2, 0, 1}});
365 EXPECT_EQ(most_negative_cycle_up_to_3(b.g).total_cost, 6u);
366}
367
369{
370 std::mt19937_64 rng(0xD420261002ULL);
371 for (size_t trial = 0; trial < 3000; ++trial)
372 {
373 const size_t n = 1 + rng() % 8, m = rng() % (n * n + 4);
374 std::vector<Edge_Def> edges;
375 for (size_t i = 0; i < m; ++i)
376 {
377 const size_t u = rng() % n, v = rng() % n;
378 const long long w = static_cast<long long>(rng() % 17) - 8;
379 edges.emplace_back(u, v, w);
380 }
381 auto b = build_graph(n, edges);
382 for (size_t bound = 1; bound <= 3; ++bound)
383 {
384 const auto expected = exhaustive(n, edges, bound);
385 const auto r = most_negative_cycle_up_to_3(b.g, bound);
386 const auto dp = most_negative_cycle_bounded(b.g, bound);
387 ASSERT_EQ(r.has_cycle, expected.exists) << trial << ":" << bound;
388 ASSERT_EQ(r.has_cycle, dp.has_cycle) << trial << ":" << bound;
389 if (not r.has_cycle)
390 continue;
391 ASSERT_EQ(r.total_cost, expected.cost) << trial << ":" << bound;
392 ASSERT_EQ(r.length, expected.length) << trial << ":" << bound;
393 ASSERT_LE(r.total_cost, dp.total_cost) << trial << ":" << bound;
394 if (dp.is_exact)
395 ASSERT_EQ(r.total_cost, dp.total_cost) << trial << ":" << bound;
396 check_witness(b.g, r);
397 }
398 }
399}
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
long double w
Definition btreepic.C:153
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Minimal std::expected-style result type for C++20.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
static mt19937 rng
bool has_cycle(const GT &g)
Return true if an undirected graph has at least one cycle.
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...
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.
decltype(auto) current(It &it) noexcept(current_is_noexcept< It >)
Current item of an iterator that is positioned on one.
Definition ah-dry.H:233
Main namespace for Aleph-w library functions.
bool exists(Container &container, Operation &operation)
Return true if at least one element satisfies a predicate.
and
Check uniqueness with explicit hash + equality functors.
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
Graph types and probe helpers shared by negative_cycles_test.cc and bounded_negative_cycle_test....
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Exact optimum returned by most_negative_cycle_up_to_3().
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Gsl_Compatible_Rng r