38#include <gtest/gtest.h>
64void insert_arc_by_value(
Grafo& g,
int src_val,
int tgt_val,
int weight)
69 for (Grafo::Node_Iterator it(g); it.has_curr(); it.next_ne()) {
70 auto n = it.get_curr();
71 if (n->get_info() == src_val) src = n;
72 if (n->get_info() == tgt_val) tgt = n;
76 g.insert_arc(src, tgt, weight);
82TEST(FloydBasicGraph, computes_correct_distances)
85 auto n0 = g.insert_node(0);
86 auto n1 = g.insert_node(1);
87 auto n2 = g.insert_node(2);
90 insert_arc_by_value(g, 0, 1, 1);
91 insert_arc_by_value(g, 1, 2, 2);
92 insert_arc_by_value(g, 0, 2, 5);
105 EXPECT_EQ(dist(i0, i0), 0);
106 EXPECT_EQ(dist(i1, i1), 0);
107 EXPECT_EQ(dist(i2, i2), 0);
110 EXPECT_EQ(dist(i0, i1), 1);
113 EXPECT_EQ(dist(i0, i2), 3);
116 EXPECT_EQ(dist(i1, i2), 2);
120TEST(FloydBasicGraph, handles_unreachable_nodes)
123 auto n0 = g.insert_node(0);
124 auto n1 = g.insert_node(1);
130 const int Inf = numeric_limits<int>::max();
136 EXPECT_EQ(dist(i0, i1), Inf);
137 EXPECT_EQ(dist(i1, i0), Inf);
145TEST(FloydNegativeWeights, handles_negative_weights_without_cycles)
148 auto n0 = g.insert_node(0);
149 auto n1 = g.insert_node(1);
150 auto n2 = g.insert_node(2);
153 g.insert_arc(n0, n1, -1);
154 g.insert_arc(n1, n2, 2);
155 g.insert_arc(n0, n2, 3);
169 EXPECT_EQ(dist(i0, i1), -1);
172 EXPECT_EQ(dist(i0, i2), 1);
176TEST(FloydNegativeCycle, detects_negative_cycles)
184 insert_arc_by_value(g, 0, 1, 1);
185 insert_arc_by_value(g, 1, 2, -1);
186 insert_arc_by_value(g, 2, 0, -1);
194TEST(FloydIndexNode, finds_correct_indices)
201 insert_arc_by_value(g, 10, 20, 1);
202 insert_arc_by_value(g, 20, 30, 1);
209 for (
size_t i = 0; i <
nodes.size(); ++i) {
211 EXPECT_EQ(floyd.
index_node(node),
static_cast<long>(i));
216TEST(FloydIndexNode, throws_on_null_pointer)
223 EXPECT_THROW(floyd.
index_node(
nullptr), std::invalid_argument);
227TEST(FloydPathReconstruction, throws_on_invalid_indices)
232 insert_arc_by_value(g, 0, 1, 1);
235 const long n = g.get_num_nodes();
237 EXPECT_THROW(floyd.
get_min_path(-1L, 0L), std::out_of_range);
238 EXPECT_THROW(floyd.
get_min_path(0L, n), std::out_of_range);
239 EXPECT_THROW(floyd.
get_min_path(n, 0L), std::out_of_range);
243TEST(FloydPathReconstruction, returns_valid_path)
246 auto n0 = g.insert_node(0);
247 auto n1 = g.insert_node(1);
248 auto n2 = g.insert_node(2);
250 g.insert_arc(n0, n1, 1);
251 g.insert_arc(n1, n2, 2);
252 g.insert_arc(n0, n2, 5);
264 EXPECT_GE(path.size(), 2u);
267 EXPECT_EQ(path.get_first_node(), n0);
268 EXPECT_EQ(path.get_last_node(), n2);
272TEST(FloydPathReconstruction, handles_self_paths)
280 EXPECT_EQ(path.size(), 1u);
284TEST(FloydUtility, entry_formats_distances_correctly)
291 EXPECT_EQ(floyd.
entry(42),
"42");
292 EXPECT_EQ(floyd.
entry(numeric_limits<int>::max()),
"Inf");
293 EXPECT_EQ(floyd.
entry(-5),
"-5");
297TEST(FloydMatrices, path_matrix_has_correct_structure)
304 insert_arc_by_value(g, 0, 1, 1);
305 insert_arc_by_value(g, 1, 2, 1);
306 insert_arc_by_value(g, 0, 2, 5);
312 const int Inf = numeric_limits<int>::max();
313 const long n = g.get_num_nodes();
315 EXPECT_EQ(path_mat.rows(), n);
316 EXPECT_EQ(path_mat.cols(), n);
319 for (
long i = 0; i < n; ++i) {
320 for (
long j = 0; j < n; ++j) {
321 if (dist(i, j) == Inf) {
322 EXPECT_EQ(path_mat(i, j), -1);
327 long k = path_mat(i, j);
335TEST(FloydLargeGraph, handles_complete_graph)
339 vector<GNode*>
nodes;
341 for (
int i = 0; i <
N; ++i)
342 nodes.push_back(g.insert_node(i));
345 for (
int i = 0; i <
N; ++i)
346 for (
int j = 0; j <
N; ++j)
357 for (
int i = 0; i <
N; ++i)
358 EXPECT_EQ(dist(i, i), 0);
363 for (
int i = 0; i <
N; ++i)
364 for (
int j = 0; j <
N; ++j)
372TEST(FloydStress, handles_single_node_graph)
382 EXPECT_EQ(dist.rows(), 1);
383 EXPECT_EQ(dist.cols(), 1);
384 EXPECT_EQ(dist(0, 0), 0);
388 EXPECT_EQ(path.size(), 1u);
389 EXPECT_EQ(path.get_first_node()->get_info(), 42);
393TEST(FloydAccessors, node_accessors_behavior)
396 auto* n1 = g.insert_node(1);
397 auto* n2 = g.insert_node(2);
398 auto* n3 = g.insert_node(3);
405 EXPECT_EQ(&nodes_ref1, &nodes_ref2);
406 EXPECT_EQ(nodes_ref1.size(), 3u);
410 EXPECT_EQ(nodes_copy.size(), 3u);
414 EXPECT_EQ(nodes_val.size(), 3u);
417 for (
size_t i = 0; i < 3; ++i) {
418 EXPECT_EQ(nodes_ref1(i), nodes_copy(i));
419 EXPECT_EQ(nodes_ref1(i), nodes_val(i));
423 nodes_copy(0) =
nullptr;
427 EXPECT_EQ(nodes_ref1(floyd.
index_node(n1)), n1);
428 EXPECT_EQ(nodes_ref1(floyd.
index_node(n2)), n2);
429 EXPECT_EQ(nodes_ref1(floyd.
index_node(n3)), n3);
438template <
class GT,
class Distance,
class SA>
446std::vector<typename GT::Arc *> arcs_of(
const Path<GT> & path)
448 std::vector<typename GT::Arc *>
arcs;
457 for (
auto a : arcs_of(path))
458 total += a->get_info();
465std::map<typename GT::Node *, long> relaxed_distances(
GT & g,
468 std::map<typename GT::Node *, long> d{{s, 0}};
469 const int directions = g.
is_digraph() ? 1 : 2;
470 for (
bool changed =
true; changed; )
473 for (
typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
475 auto a = it.get_curr();
478 for (
int dir = 0; dir < directions; ++dir, std::swap(u, v))
479 if (d.contains(u)
and
480 (not d.contains(v) or d[u] + a->
get_info() < d[v]))
493void check_against_relaxation(
const unsigned seed)
496 std::uniform_int_distribution<int> pick(0, 7);
497 std::uniform_int_distribution<int> weight(0, 20);
499 std::vector<typename GT::Node *>
nodes;
500 for (
int i = 0; i < 8; ++i)
502 for (
int k = 0;
k < 24; ++
k)
509 auto d = relaxed_distances(g, s);
512 if (not d.contains(t))
514 EXPECT_EQ(dist_of(floyd, s, t), numeric_limits<int>::max())
518 EXPECT_EQ(dist_of(floyd, s, t), d[t]) <<
"seed " <<
seed;
522 EXPECT_EQ(cost_of(path), d[t]) <<
"seed " <<
seed;
531TEST(FloydParallelArcs, TakesTheLightest)
533 for (
const bool heavy_first : {
true,
false})
536 auto a = g.insert_node(0);
537 auto b = g.insert_node(1);
538 GArc * light =
nullptr;
541 g.insert_arc(a, b, 5);
542 light = g.insert_arc(a, b, 1);
546 light = g.insert_arc(a, b, 1);
547 g.insert_arc(a, b, 5);
551 EXPECT_EQ(dist_of(floyd, a, b), 1) << heavy_first;
553 std::vector<GArc *>{light}) << heavy_first;
559TEST(FloydUndirected, PathsGoBothWaysAlongTheArcs)
562 auto a = g.insert_node(0);
563 auto b = g.insert_node(1);
564 auto c = g.insert_node(2);
565 g.insert_arc(a, b, 3);
566 g.insert_arc(c, b, 4);
567 g.insert_arc(b, c, 9);
570 EXPECT_EQ(dist_of(floyd, a, c), 7);
571 EXPECT_EQ(dist_of(floyd, c, a), 7);
576 EXPECT_EQ(cost_of(path), 7);
581TEST(FloydUndirected, ANegativeArcIsANegativeCycle)
584 auto a = g.insert_node(0);
585 auto b = g.insert_node(1);
586 g.insert_arc(a, b, -1);
589 EXPECT_THROW(floyd.
get_min_path(a, b), std::domain_error);
595TEST(FloydNumeric, ADistanceBelowTheRangeThrows)
597 const int lowest = numeric_limits<int>::lowest();
600 auto a = g.insert_node(0);
601 auto b = g.insert_node(1);
602 g.insert_arc(a, b, lowest);
603 g.insert_arc(b, a, -1);
608 auto x =
h.insert_node(0);
609 auto y =
h.insert_node(1);
610 auto z =
h.insert_node(2);
611 h.insert_arc(x,
y, lowest / 2);
612 h.insert_arc(
y, z, lowest / 2);
613 h.insert_arc(z, x, -1);
617 auto c = u.insert_node(0);
618 auto d = u.insert_node(1);
619 u.insert_arc(c, d, lowest);
624TEST(FloydNumeric, ADistanceAtTheBottomOfTheRangeCounts)
626 const int lowest = numeric_limits<int>::lowest();
628 auto a = g.insert_node(0);
629 auto b = g.insert_node(1);
630 auto c = g.insert_node(2);
631 g.insert_arc(a, b, lowest / 2);
632 g.insert_arc(b, c, lowest / 2);
636 EXPECT_EQ(dist_of(floyd, a, c), lowest);
642TEST(FloydLoops, ANegativeLoopIsANegativeCycle)
645 auto a = g.insert_node(0);
646 auto b = g.insert_node(1);
647 g.insert_arc(a, b, 2);
648 g.insert_arc(a, a, -1);
653 auto c = u.insert_node(0);
654 auto d = u.insert_node(1);
655 u.insert_arc(c, d, 2);
656 u.insert_arc(d, d, -1);
661TEST(FloydLoops, APositiveLoopDoesNotCount)
664 auto a = g.insert_node(0);
665 auto b = g.insert_node(1);
666 g.insert_arc(a, a, 3);
667 g.insert_arc(a, b, 2);
670 EXPECT_EQ(dist_of(floyd, a, a), 0);
675TEST(FloydNegativeCycle, GetMinPathThrows)
678 auto a = g.insert_node(0);
679 auto b = g.insert_node(1);
680 g.insert_arc(a, a, -1);
681 g.insert_arc(a, b, 2);
684 EXPECT_THROW(floyd.
get_min_path(a, b), std::domain_error);
689TEST(FloydFilter, PathsUseOnlyTheArcsOfTheFilter)
692 auto a = g.insert_node(0);
693 auto b = g.insert_node(1);
694 GArc * hidden = g.insert_arc(a, b, 1);
695 GArc * shown = g.insert_arc(a, b, 5);
699 GArc * hidden =
nullptr;
700 bool operator()(
GArc * arc)
const noexcept {
return arc != hidden; }
706 EXPECT_EQ(arcs_of(floyd.
get_min_path(a, b)), std::vector<GArc *>{shown});
711 from_temporary(g, Hide{hidden});
712 EXPECT_EQ(arcs_of(from_temporary.get_min_path(a, b)),
713 std::vector<GArc *>{shown});
716TEST(FloydRandom, MatchesRelaxationWithParallelArcsAndLoops)
720 check_against_relaxation<Grafo>(
seed);
721 check_against_relaxation<UGrafo>(
seed);
733 using Distance_Type = int;
735 int operator()(
GArc * a)
const noexcept {
return factor * a->
get_info(); }
741 using Distance_Type = int;
743 explicit From_Base_Dist(
int b) noexcept : base(b) {}
744 int operator()(
GArc * a)
const noexcept {
return base - a->
get_info(); }
750 using Distance_Type = int;
751 int operator()(
GArc * a)
noexcept {
return a->
get_info(); }
759TEST(FloydDistance, UsesTheDistanceItWasGiven)
762 auto a = g.insert_node(0);
763 auto b = g.insert_node(1);
764 auto c = g.insert_node(2);
765 g.insert_arc(a, b, 1);
766 GArc * heavy = g.insert_arc(a, b, 5);
767 GArc * bc = g.insert_arc(b, c, 2);
771 EXPECT_EQ(dist_of(floyd, a, b), -5);
772 EXPECT_EQ(dist_of(floyd, a, c), -7);
774 (std::vector<GArc *>{heavy, bc}));
778TEST(FloydDistance, TakesADistanceWithoutADefaultConstructor)
781 auto a = g.insert_node(0);
782 auto b = g.insert_node(1);
783 GArc * heavy = g.insert_arc(a, b, 9);
784 GArc * light = g.insert_arc(a, b, 4);
787 EXPECT_EQ(dist_of(floyd, a, b), 1);
788 EXPECT_EQ(arcs_of(floyd.
get_min_path(a, b)), std::vector<GArc *>{heavy});
792 GArc * hidden =
nullptr;
793 bool operator()(
GArc * arc)
const noexcept {
return arc != hidden; }
797 filtered(g, From_Base_Dist(10), Hide{heavy});
798 EXPECT_EQ(dist_of(filtered, a, b), 6);
799 EXPECT_EQ(arcs_of(filtered.get_min_path(a, b)), std::vector<GArc *>{light});
805TEST(FloydDistance, TakesACallOperatorThatIsNotConst)
808 auto a = g.insert_node(0);
809 auto b = g.insert_node(1);
810 g.insert_arc(a, b, 5);
811 GArc * light = g.insert_arc(a, b, 1);
814 EXPECT_EQ(dist_of(floyd, a, b), 1);
815 EXPECT_EQ(arcs_of(floyd.
get_min_path(a, b)), std::vector<GArc *>{light});
824 using Distance_Type = int;
826 int operator()(
GArc * a)
noexcept
838 using Distance_Type = int;
841 explicit Copied_Dist(
long * c) noexcept : copies(c) {}
842 Copied_Dist(
const Copied_Dist & d) noexcept : copies(d.copies) { ++*copies; }
843 Copied_Dist & operator = (
const Copied_Dist &) =
default;
845 int operator()(
GArc * a)
const noexcept requires Const
850 int operator()(
GArc * a)
noexcept requires (not Const)
861TEST(FloydDistance, ConcurrentPathsDoNotShareTheDistance)
864 auto a = g.insert_node(0);
865 auto b = g.insert_node(1);
866 auto c = g.insert_node(2);
867 GArc * ab = g.insert_arc(a, b, 1);
868 g.insert_arc(a, b, 5);
869 g.insert_arc(b, c, 7);
870 GArc * bc = g.insert_arc(b, c, 2);
873 const std::vector<GArc *>
expected = {ab, bc};
874 long wrong[2] = {0, 0};
875 auto work = [&floyd, &
expected, a, c](
long & mistakes)
877 for (
int i = 0; i < 2000; ++i)
881 std::thread first(work, std::ref(wrong[0]));
882 std::thread second(work, std::ref(wrong[1]));
885 EXPECT_EQ(wrong[0], 0);
886 EXPECT_EQ(wrong[1], 0);
891TEST(FloydDistance, GetMinPathCopiesOnlyADistanceThatItMayChange)
894 auto a = g.insert_node(0);
895 auto b = g.insert_node(1);
896 g.insert_arc(a, b, 5);
897 GArc * light = g.insert_arc(a, b, 1);
901 with_const(g, Copied_Dist<true>(&copies));
902 long before = copies;
903 EXPECT_EQ(arcs_of(with_const.
get_min_path(a, b)), std::vector<GArc *>{light});
904 EXPECT_EQ(copies, before);
907 without_const(g, Copied_Dist<false>(&copies));
910 std::vector<GArc *>{light});
911 EXPECT_EQ(copies, before + 1);
916TEST(FloydDistance, EmptyBracesAreTheFilter)
919 auto a = g.insert_node(0);
920 auto b = g.insert_node(1);
921 g.insert_arc(a, b, 3);
924 EXPECT_EQ(dist_of(floyd, a, b), 3);
927 EXPECT_EQ(dist_of(scaled, a, b), 3);
932TEST(FloydDistance, TheClassIsDeducedFromTheDistance)
935 auto a = g.insert_node(0);
936 auto b = g.insert_node(1);
937 g.insert_arc(a, b, 3);
940 static_assert(std::is_same_v<
decltype(floyd),
942 EXPECT_EQ(dist_of(floyd, a, b), 6);
945 static_assert(std::is_same_v<
decltype(both),
947 EXPECT_EQ(dist_of(both, a, b), 6);
951 static_assert(std::is_same_v<
decltype(filtered),
953 EXPECT_EQ(dist_of(filtered, a, b), 3);
966 std::vector<typename G::Node *> insert_nodes(
G & g,
long n)
968 std::vector<typename G::Node *> v;
969 for (
long i = 0; i < n; ++i)
977 std::vector<typename G::Node *> complete_of_minus_one(
G & g,
long n)
979 auto v = insert_nodes(g, n);
980 for (
long i = 0; i < n; ++i)
981 for (
long j = 0; j < n; ++j)
991 std::vector<typename G::Node *> ring_with_one_negative_arc(
G & g,
long n)
993 auto v = insert_nodes(g, n);
994 for (
long i = 0; i < n; ++i)
1005 std::vector<typename G::Node *> path_with_one_negative_arc(
G & g,
long n)
1007 auto v = insert_nodes(g, n);
1008 for (
long i = 0; i + 1 < n; ++i)
1019TEST(FloydNegativeCycle, ACompleteDigraphOfNegativeArcs)
1022 const auto v = complete_of_minus_one(g, 32);
1025 EXPECT_THROW(floyd.
get_min_path(v.front(), v.back()), std::domain_error);
1028 complete_of_minus_one(
h, 40);
1035TEST(FloydNegativeCycle, OneNegativeArcInALargeGraph)
1037 for (
long n : {64L, 100L, 256L})
1039 SCOPED_TRACE(testing::Message() << n <<
" nodes");
1041 ring_with_one_negative_arc(g, n);
1045 ring_with_one_negative_arc(
h, n);
1049 path_with_one_negative_arc(u, n);
1053 path_with_one_negative_arc(lu, n);
1061TEST(FloydLoops, ALoopAtTheBottomOfTheRangeIsANegativeCycle)
1064 auto a = g.insert_node(0);
1065 g.insert_arc(a, a, numeric_limits<int>::lowest());
Floyd-Warshall algorithm for all-pairs shortest paths.
Generic directed graph (digraph) wrapper template.
typename BaseGraph::Arc Arc
typename BaseGraph::Node Node
Compute the all-pairs shortest path distance matrix and the path reconstruction matrix for a graph g ...
DynArray< Node * > get_nodes() const
Get an owning copy of the graph nodes array.
DynArray< Node * > get_nodes_copy() const
Get an owning copy of the graph nodes array.
Path< GT > get_min_path(const long src_idx, const long tgt_idx) const
Reconstruct the shortest path between two nodes by matrix indices.
const DynMatrix< Distance_Type > & get_dist_mat() const noexcept
Get the distance matrix.
Node * select_node(long i) const noexcept
Get the graph node at a given matrix index.
constexpr bool has_negative_cycle() const noexcept
Check if the graph contains a negative cycle.
std::string entry(const Distance_Type &e) const
Convert a distance value to string representation.
const DynArray< Node * > & get_nodes_ref() const noexcept
Get the array of graph nodes as a constant reference.
const DynMatrix< long > & get_path_mat() const noexcept
Get the path reconstruction matrix.
long index_node(Node *p) const
Return the adjacency-matrix index corresponding to node p.
Graph implemented with double-linked adjacency lists.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
typename Arc::Arc_Type Arc_Type
The type of data stored in the arc.
Number Theoretic Transform over Z / MOD Z.
Node * get_first_node() const
Return the first node of path; throws overflow_error if 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.
Minimal std::expected-style result type for C++20.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
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)
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
Default filter for filtered iterators on arcs.
Arc of graph implemented with double-linked adjacency lists.
Utility algorithms and operations for graphs.