13#include <gtest/gtest.h>
29TEST(BellmanFordTest, SimpleGraphNoNegativeCycles) {
47 ASSERT_FALSE(has_negative_cycle);
51TEST(BellmanFordTest, GraphWithNegativeCycle) {
66 ASSERT_TRUE(has_negative_cycle);
70TEST(BellmanFordTest, SpanningTreePainting) {
87 ASSERT_FALSE(negative_cycle);
98 ASSERT_EQ(painted_arcs, 3);
102TEST(BellmanFordTest, FasterVersion) {
125 ASSERT_FALSE(negative_cycle);
129TEST(BellmanFordTest, NegativeCycleDetectionFull) {
150TEST(BellmanFordTest, SearchNegativeCycleWithParams) {
167 size_t iterations = get<1>(result);
170 ASSERT_GT(iterations, 0u);
174TEST(BellmanFordTest, TrivialGraphNoNegativeCycles) {
182 ASSERT_FALSE(has_negative_cycle);
186TEST(BellmanFordTest, GraphWithZeroWeights) {
201 ASSERT_FALSE(has_negative_cycle);
205TEST(BellmanFordTest, DisconnectedGraph) {
222 ASSERT_FALSE(has_negative_cycle);
226TEST(BellmanFordTest, NegativeWeightsNoCycle) {
242 ASSERT_FALSE(has_negative_cycle);
246TEST(BellmanFordTest, LargeGraphNoNegativeCycle) {
250 std::vector<Node*>
nodes;
257 for (
int i = 0; i <
num_nodes - 1; ++i) {
262 for (
int i = 0; i <
num_nodes - 5; i += 5) {
269 ASSERT_FALSE(has_negative_cycle);
273TEST(BellmanFordTest, ComplexNegativeCycle) {
295TEST(BellmanFordTest, NegativeCycleWithOutputParameter) {
315TEST(BellmanFordTest, SearchNegativeCycleNoStartNode) {
338TEST(BellmanFordTest, NegativeCycleFunctor) {
358TEST(BellmanFordTest, NegativeSelfLoop) {
370 ASSERT_TRUE(has_negative_cycle);
374TEST(BellmanFordTest, AllNegativeWeightsNoCycle) {
390 ASSERT_FALSE(has_negative_cycle);
394TEST(BellmanFordTest, NullptrValidation) {
403 bool caught_exception =
false;
406 }
catch (
const std::domain_error&) {
407 caught_exception =
true;
409 ASSERT_TRUE(caught_exception);
411 caught_exception =
false;
414 }
catch (
const std::domain_error&) {
415 caught_exception =
true;
417 ASSERT_TRUE(caught_exception);
419 caught_exception =
false;
422 }
catch (
const std::domain_error&) {
423 caught_exception =
true;
425 ASSERT_TRUE(caught_exception);
429TEST(BellmanFordTest, CompletelyEmptyGraph) {
442TEST(BellmanFordTest, BuildTreeFromSpanningTree) {
470TEST(BellmanFordTest, ExtractMinSpanningTree) {
490 int non_null_arcs = 0;
491 for (
size_t i = 0; i < tree_arcs.
size(); ++i) {
492 if (tree_arcs(i) !=
nullptr) {
497 ASSERT_EQ(non_null_arcs, 3);
501TEST(BellmanFordTest, ComputeNodesWeightsJohnson) {
521TEST(BellmanFordTest, ComputeNodesWeightsWithNegativeCycle) {
534 bool caught_exception =
false;
537 }
catch (
const std::domain_error&) {
538 caught_exception =
true;
541 ASSERT_TRUE(caught_exception);
545TEST(BellmanFordTest, HasNegativeCycleNoStartNode) {
563TEST(BellmanFordTest, NegativeCycleNoParams) {
583TEST(BellmanFordTest, GetMinPath) {
604 ASSERT_EQ(distance, 4);
608 size_t path_length = 0;
612 ASSERT_EQ(path_length, 4);
616TEST(BellmanFordTest, GetMinPathToAllNodes) {
642TEST(BellmanFordTest, ExtractMinSpanningTreeValidation) {
659 size_t valid_arcs = 0;
660 for (
size_t i = 0; i <
arcs.size(); ++i)
661 if (
arcs(i) !=
nullptr)
664 ASSERT_EQ(valid_arcs, 2);
667 bool found_a01 =
false;
668 bool found_a12 =
false;
669 for (
size_t i = 0; i <
arcs.size(); ++i) {
670 if (
arcs(i) == a01) found_a01 =
true;
671 if (
arcs(i) == a12) found_a12 =
true;
674 ASSERT_TRUE(found_a01);
675 ASSERT_TRUE(found_a12);
679TEST(BellmanFordTest, BuildTreeWithMapping) {
703 bool found_0 =
false, found_1 =
false, found_2 =
false;
704 for (
typename GT::Node_Iterator it(tree); it.has_curr(); it.next()) {
705 auto node = it.get_curr();
706 int info = node->get_info();
707 if (info == 0) found_0 =
true;
708 if (info == 1) found_1 =
true;
709 if (info == 2) found_2 =
true;
712 ASSERT_TRUE(found_0);
713 ASSERT_TRUE(found_1);
714 ASSERT_TRUE(found_2);
718TEST(BellmanFordTest, ComputeNodesWeightsValues) {
732 ASSERT_EQ(weights.size(), 3);
736 for (
auto it = weights.get_it(); it.has_curr(); it.next()) {
737 auto &
pair = it.get_curr();
739 ASSERT_GE(
pair.second, std::numeric_limits<int>::min());
744TEST(BellmanFordTest, NegativeCycleFunctorVariant1) {
765TEST(BellmanFordTest, NegativeCycleFunctorWithStartNode) {
786TEST(BellmanFordTest, SearchNegativeCycleWithDifferentItFactors) {
801 ASSERT_FALSE(path1.is_empty());
802 ASSERT_GT(iter1, 0u);
806 ASSERT_FALSE(path2.is_empty());
807 ASSERT_GT(iter2, 0u);
811TEST(BellmanFordTest, EmptyGraphEdgeCase) {
821TEST(BellmanFordTest, LargeGraphPerformance) {
824 const size_t N = 100;
827 std::vector<Node*>
nodes;
828 for (
size_t i = 0; i <
N; ++i)
832 for (
size_t i = 0; i <
N - 1; ++i)
838 ASSERT_FALSE(negative_cycle);
844 ASSERT_EQ(distance,
N - 1);
848TEST(BellmanFordTest, StateGetters) {
871TEST(BellmanFordTest, GetMinPathWithoutPainting) {
884 }
catch (
const std::domain_error&) {
891TEST(BellmanFordTest, NegativeCyclePathValidity) {
909 size_t cycle_length = 0;
913 ASSERT_GE(cycle_length, 2u);
917TEST(BellmanFordTest, SingleNodePositiveSelfLoop) {
926 ASSERT_FALSE(has_neg_cycle);
930TEST(BellmanFordTest, CycleClosedByTheCheckingPassIsReturned) {
935 for (
const bool loop : {
false,
true})
953 ASSERT_FALSE(cycle.
is_empty()) << (loop ?
"loop" :
"2-cycle");
962TEST(BellmanFordTest, FasterVersionWithNegativeCycle) {
976 ASSERT_TRUE(has_neg_cycle);
980TEST(BellmanFordTest, SearchNegativeCycleDoubleOverload) {
996 ASSERT_FALSE(path.is_empty());
1000TEST(BellmanFordTest, SearchNegativeCycleNoParamsVariant) {
1020TEST(BellmanFordTest, BuildTreeWithoutPriorPainting) {
1030 bool caught =
false;
1033 }
catch (
const std::domain_error&) {
1036 ASSERT_TRUE(caught);
1040TEST(BellmanFordTest, MultiplePaintCalls) {
1060 ASSERT_EQ(dist1, 3);
1074 ASSERT_EQ(
dist2, 5);
1078TEST(BellmanFordTest, FunctorDifferentSignatures) {
1094 Path<GT> path1 = detector(g, n0, dist, sa);
1098 Path<GT> path2 = detector(g, dist, sa);
1107TEST(BellmanFordTest, StronglyConnectedWithNegativeCycle) {
1128 ASSERT_TRUE(has_neg);
1132TEST(BellmanFordTest, VeryLongChainPerformance) {
1135 const size_t N = 500;
1137 std::vector<Node*>
nodes;
1138 for (
size_t i = 0; i <
N; ++i)
1141 for (
size_t i = 0; i <
N - 1; ++i)
1147 ASSERT_FALSE(neg_cycle);
1152 ASSERT_EQ(dist,
static_cast<int>(
N - 1));
1156TEST(BellmanFordTest, BidirectionalEdges) {
1168 ASSERT_FALSE(neg_cycle);
1177TEST(BellmanFordTest, UnreachableNode) {
1191 bool caught =
false;
1194 }
catch (
const std::domain_error&) {
1198 ASSERT_TRUE(caught);
1205 const size_t N = 20;
1207 std::vector<Node*>
nodes;
1208 for (
size_t i = 0; i <
N; ++i)
1212 for (
size_t i = 0; i <
N; ++i)
1213 for (
size_t j = 0; j <
N; ++j)
1220 ASSERT_FALSE(neg_cycle);
1224TEST(BellmanFordTest, GetDistance) {
1241 ASSERT_EQ(dist_n3, 6);
1245 ASSERT_EQ(dist_n1, 1);
1249 ASSERT_EQ(dist_n0, 0);
1253TEST(BellmanFordTest, GetDistanceWithoutPainting) {
1262 bool caught =
false;
1265 }
catch (
const std::domain_error&) {
1268 ASSERT_TRUE(caught);
1272TEST(BellmanFordTest, GetDistanceUnreachableNode) {
1284 bool caught =
false;
1287 }
catch (
const std::domain_error&) {
1290 ASSERT_TRUE(caught);
1294TEST(BellmanFordTest, ExtractMinSpanningTreeWithoutPainting) {
1303 bool caught =
false;
1306 }
catch (
const std::domain_error&) {
1309 ASSERT_TRUE(caught);
1313TEST(BellmanFordTest, GetDistanceNullNode) {
1323 bool caught =
false;
1326 }
catch (
const std::domain_error&) {
1329 ASSERT_TRUE(caught);
1333TEST(BellmanFordTest, GetDistanceConsistentWithGetMinPath) {
1350 for (
Node* target : {n1, n2, n3}) {
1354 ASSERT_EQ(path_dist, direct_dist);
1360TEST(BellmanFordTest, ParallelArcsChoosesMinimum) {
1376 GTEST_SKIP() <<
"Graph type does not support parallel arcs (multigraph)";
1381 EXPECT_FALSE(has_neg);
1391TEST(BellmanFordTest, ParallelArcsNegativeWeights) {
1404 GTEST_SKIP() <<
"Graph type does not support parallel arcs (multigraph)";
1409 EXPECT_FALSE(has_neg);
1419TEST(BellmanFordTest, ComplexMultigraph) {
1439 GTEST_SKIP() <<
"Graph type does not support parallel arcs (multigraph)";
1444 EXPECT_FALSE(has_neg);
1454TEST(BellmanFordTest, ParallelArcsNegativeCycle) {
1465 GTEST_SKIP() <<
"Graph type does not support parallel arcs (multigraph)";
1472 EXPECT_TRUE(has_neg);
1487TEST(BellmanFordTest, GetMinPathUsesTheDistanceItWasGiven) {
1497 ASSERT_FALSE(bf.paint_spanning_tree(n0));
1500 EXPECT_EQ(bf.get_min_path(n2, path), 21);
1508TEST(BellmanFordTest, ANegativeCycleBeyondMaxThrowsFromTheStart) {
1509 constexpr int M = std::numeric_limits<int>::max();
1518 EXPECT_THROW(
Bellman_Ford<GT>(g).has_negative_cycle(c), std::overflow_error);
1519 EXPECT_THROW(
Bellman_Ford<GT>(g).test_negative_cycle(c), std::overflow_error);
1521 EXPECT_THROW(
Bellman_Ford<GT>(g).test_negative_cycle(c, cycle), std::overflow_error);
1522 EXPECT_THROW(
Bellman_Ford<GT>(g).search_negative_cycle(c), std::overflow_error);
1523 EXPECT_THROW(
Bellman_Ford<GT>(g).search_negative_cycle(c, 0.5, 1), std::overflow_error);
1524 EXPECT_THROW(
Bellman_Ford<GT>(g).paint_spanning_tree(c), std::overflow_error);
1525 EXPECT_THROW(
Bellman_Ford<GT>(g).faster_paint_spanning_tree(c), std::overflow_error);
1553TEST(BellmanFordTest, ATolerantDistanceTakesNoCycleWithinItsTolerance)
1556 auto a = g.insert_node(0);
1557 auto b = g.insert_node(1);
1558 g.insert_arc(a, b, 1.0);
1559 auto ba = g.insert_arc(b, a, -1.0 - 1e-14);
1563 EXPECT_FALSE(Tolerant_BF(g,
Tolerant_Dist(1e-12)).has_negative_cycle(a));
1564 EXPECT_TRUE(Tolerant_BF(g,
Tolerant_Dist(1e-12)).search_negative_cycle(a).is_empty());
1565 EXPECT_FALSE(Tolerant_BF(g,
Tolerant_Dist(1e-12)).has_negative_cycle());
1568 ba->get_info() = -1.1;
1569 EXPECT_TRUE(Tolerant_BF(g,
Tolerant_Dist(1e-12)).has_negative_cycle(a));
1570 EXPECT_FALSE(Tolerant_BF(g,
Tolerant_Dist(1e-12)).search_negative_cycle(a).is_empty());
1592TEST(BellmanFordTest, AnUnsignedToleranceDoesNotWrapAround)
1595 for (
const unsigned w : {0u, 1u})
1596 for (
const unsigned tol : {1u, 5u})
1597 for (
const bool faster : {
false,
true})
1600 auto a = g.insert_node(0);
1601 auto b = g.insert_node(1);
1602 g.insert_arc(a, b,
w);
1603 g.insert_arc(b, a,
w);
1606 EXPECT_FALSE(UBF(g, d).has_negative_cycle(a));
1607 EXPECT_FALSE(UBF(g, d).has_negative_cycle());
1609 ASSERT_FALSE(faster ? bf.faster_paint_spanning_tree(a) : bf.paint_spanning_tree(a));
1610 EXPECT_EQ(bf.get_distance(b),
w);
1616TEST(BellmanFordTest, AnIntegerToleranceLeavesNoNodeWithoutADistance)
1620 constexpr int max = std::numeric_limits<int>::max();
1621 for (
const bool faster : {
false,
true})
1629 ASSERT_FALSE(faster ? bf.faster_paint_spanning_tree(a) : bf.paint_spanning_tree(a));
1630 EXPECT_EQ(bf.get_distance(b),
max - 1);
1637TEST(BellmanFordTest, ASignedToleranceDoesNotOverflow)
1641 constexpr int lowest = std::numeric_limits<int>::lowest();
1644 for (
const bool faster : {
false,
true})
1652 EXPECT_FALSE(IBF(g, d).has_negative_cycle(a));
1653 EXPECT_FALSE(IBF(g, d).has_negative_cycle());
1655 ASSERT_FALSE(faster ? bf.faster_paint_spanning_tree(a) : bf.paint_spanning_tree(a));
1656 EXPECT_EQ(bf.get_distance(b), lowest + 1);
1663 ::testing::InitGoogleTest(&argc, argv);
1664 return RUN_ALL_TESTS();
Bellman-Ford algorithm for single-source shortest paths.
WeightedDigraph::Node Node
Bellman-Ford algorithm for shortest paths with negative weights.
Distance_Type get_distance(typename GT::Node *node)
Get the accumulated distance to a node from a previously painted tree.
DynArray< Arc * > extract_min_spanning_tree()
Extract the shortest paths tree in a compressed form.
bool has_computation() const noexcept
Check if a shortest-path tree has been computed or painted.
bool faster_paint_spanning_tree(Node *start)
Faster shortest paths tree painting from a start node.
DynMapTree< Node *, Distance_Type > compute_nodes_weights()
Returns a mapping with the shortest distances to each node obtained after executing the Bellman-Ford ...
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
bool is_painted() const noexcept
Check if a shortest-path tree has been painted.
std::tuple< Path< GT >, size_t > search_negative_cycle(Node *start, double it_factor, const size_t step)
Searches a negative cycle using the faster version of Bellman-Ford algorithm and iteratively searchin...
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extract the shortest path to a node from a previously painted tree.
const GT & get_graph() const noexcept
Get reference to the graph.
Node * get_start_node() const noexcept
Get the start node of the last computation.
Path< GT > test_negative_cycle(Node *start)
Search a negative cycle on all possible paths starting from start node.
void build_tree(GT &tree, bool with_map=true)
Extract from the graph a previously painted shortest paths tree.
Default distance accessor for arc weights.
GT::Arc_Type Distance_Type
Generic directed graph (digraph) wrapper template.
typename BaseGraph::Arc Arc
typename BaseGraph::Node Node
size_t size() const noexcept
Return the current dimension of array.
void next()
Advances the iterator to the next filtered element.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Number Theoretic Transform over Z / MOD Z.
Iterator on nodes and arcs of a path.
bool has_current_node() const noexcept
Return true if the iterator has a current node.
bool is_cycle() const
Return true if this is a cycle; throws if path is empty.
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
bool is_empty() const noexcept
Return true if the path is empty.
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
void for_each_arc(Operation op=Operation()) const
Execute an operation on each arc of path.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
static Geom_Number dist2(const Point &a, const Point &b)
__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
bool has_cycle(const GT &g)
Return true if an undirected graph has at least one cycle.
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
Main namespace for Aleph-w library functions.
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Filtered iterator on all the arcs of a graph.
Detects if a negative cycle exists and eventually computes it.
Default filter for filtered iterators on arcs.
Arc of graph implemented with double-linked adjacency lists.
int operator()(Arc *a) const
double tolerance() const noexcept
Tolerant_Int_Dist()=default
Distance_Type tolerance() const noexcept
Tolerant_Int_Dist(Distance_Type t)
typename Dft_Dist< G >::Distance_Type Distance_Type
Generic graph and digraph implementations.