Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Floyd_Warshall.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
95# ifndef FLOYD_WARSHALL_H
96# define FLOYD_WARSHALL_H
97
98# include <ah-graph-concepts.H>
99
100# include <type_traits>
101# include <sstream>
102# include <iostream>
103# include <limits>
104# include <utility>
105# include <ahFunction.H>
106# include <ahSort.H>
107# include <tpl_indexArc.H>
108# include <tpl_dynMat.H>
109# include <tpl_graph.H>
110# include <tpl_graph_utils.H>
111# include <ah-errors.H>
112
113namespace Aleph
114{
164 template <AlephGraph GT,
165 ArcDistance<GT> Distance = Dft_Dist<GT>,
166 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
168 {
169 typedef typename GT::Node Node;
170 typedef typename GT::Arc Arc;
172
174 GT & g;
175 long n; // not const, so that a move leaves it at 0 in its source
177 bool negative_cycle = false;
180 SA sa;
181
183
184 // The distance with which get_min_path() measures the arcs: that of the
185 // solver, if its call operator is const; otherwise a copy, so that
186 // concurrent calls do not share its state
187 decltype(auto) path_distance() const
188 {
189 if constexpr (std::is_invocable_v<const Distance &, Arc *>)
190 return (distance);
191 else
192 return Distance(distance);
193 }
194
195 // Appends to path the lightest arc that sa shows from p to q: the one
196 // whose weight, as d measures it, is in the matrix
197 template <class D>
198 void append_lightest_arc(Path<GT> & path, Node *p, Node *q, D & d) const
199 {
200 Arc *lightest = nullptr;
201 for (Node_Arc_Iterator<GT, SA> it(p, sa); it.has_curr(); it.next_ne())
202 if (it.get_tgt_node_ne() == q and
203 (lightest == nullptr or d(it.get_current_arc_ne()) < d(lightest)))
204 lightest = it.get_current_arc_ne();
205
206 assert(lightest != nullptr);
207 if (g.is_digraph())
208 path.append_directed(lightest);
209 else
210 path.append(lightest);
211 }
212
213 // Whether a node reaches itself at a negative cost
215 {
216 for (long i = 0; i < n; ++i)
217 if (dist(i, i) < 0)
218 return true;
219 return false;
220 }
221
222 public:
230 [[nodiscard]] constexpr bool has_negative_cycle() const noexcept { return negative_cycle; }
231
241 [[nodiscard]] const DynMatrix<long> &get_path_mat() const noexcept { return path_mat; }
242
253 {
254 return dist;
255 }
256
274 [[nodiscard]] DynArray<Node *> get_nodes() const { return get_nodes_copy(); }
275
289 [[nodiscard]] const DynArray<Node *> & get_nodes_ref() const noexcept { return nodes; }
290
306 [[nodiscard]] DynArray<Node *> get_nodes_copy() const { return nodes; }
307
314 Node * select_node(long i) const noexcept { return nodes(i); }
315
317
324 long index_node(Node *p) const
325 {
326 ah_invalid_argument_if(p == nullptr) << "Node pointer cannot be null";
327 auto i = binary_search(nodes, p);
328 ah_domain_error_if(i < 0 or i >= static_cast<long>(nodes.size()) or
329 nodes(i) != p)
330 << "Floyd_All_Shortest_Paths::index_node() node not found";
331 return i;
332 }
333
334 public:
357 // The condition on D is an argument of the template, not a requires
358 // clause: Clang 14 leaves the clause out of the deduction guide that it
359 // makes from the constructor, and then `(g, sa)` would be ambiguous
360 template <class D,
361 std::enable_if_t<std::is_convertible_v<D, Distance>, int> = 0>
362 Floyd_All_Shortest_Paths(const GT & __g, D && __distance, SA __sa = SA())
363 : g(const_cast<GT &>(__g)), n(g.get_num_nodes()),
364 Inf(std::numeric_limits<Distance_Type>::max()),
365 path_mat(n, n), dist(n, n), sa(__sa),
366 distance(std::forward<D>(__distance))
367 {
368 ah_invalid_argument_if(n <= 0) << "Graph must contain at least one node";
369
370 long i = 0;
371 nodes.reserve(n);
372 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
373 nodes.access(i++) = it.get_curr();
374 in_place_sort(nodes); // sort by node pointer value
375
376 dist.allocate();
377 path_mat.allocate(); { // initialize matrices
378 for (long i = 0; i < n; ++i)
379 for (long j = 0; j < n; ++j)
380 {
381 dist(i, j) = i == j ? 0 : Inf;
382 path_mat(i, j) = i == j ? j : -1;
383 }
384
385 // Of the parallel arcs, the lightest counts; a loop counts only if
386 // it is negative, as a negative cycle
387 const bool directed = g.is_digraph();
388 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
389 {
390 Arc *arc = it.get_curr_ne();
391 const long i = index_node(g.get_src_node(arc));
392 const long j = index_node(g.get_tgt_node(arc));
393 const Distance_Type w = distance(arc);
394 if (w < dist(i, j))
395 {
396 dist(i, j) = w;
397 path_mat(i, j) = j;
398 }
399 if (not directed and w < dist(j, i))
400 {
401 dist(j, i) = w;
402 path_mat(j, i) = i;
403 }
404 }
405 }
406
407 // With a negative cycle, the distances that go round it can double
408 // at each k and soon leave the range of the type, whatever the cost
409 // of the cycle; so the computation stops at the first one: a negative
410 // loop, or a node that reaches itself at a negative cost at the end
411 // of a k. Before it, each distance is that of a walk whose cycles are
412 // not negative, at least n - 1 times the lightest weight, so a sum
413 // goes below lowest() only with a weight below lowest() / (2 (n - 1)).
415 for (long k = 0; k < n and not negative_cycle; ++k)
416 {
417 for (long i = 0; i < n; ++i)
418 {
419 const Distance_Type & dik = dist(i, k);
420 for (long j = 0; j < n; ++j)
421 {
422 const Distance_Type & dij = dist(i, j);
423 if (dik == Inf)
424 continue;
425
426 const Distance_Type & dkj = dist(k, j);
427 if (dkj == Inf)
428 continue;
429
430 // Calculate new distance through intermediate node k.
431 // Important: avoid undefined behavior on signed overflow
432 // (e.g. Inf - negative) and handle negative weights safely.
433 bool can_add = true;
434 if constexpr (std::numeric_limits<Distance_Type>::is_integer)
435 {
436 if constexpr (std::numeric_limits<Distance_Type>::is_signed)
437 {
438 const Distance_Type maxv = std::numeric_limits<Distance_Type>::max();
439 const Distance_Type minv = std::numeric_limits<Distance_Type>::lowest();
440 if (dkj > 0)
441 can_add = (dik <= maxv - dkj);
442 else if (dkj < 0) // below lowest() it would be shorter
443 ah_overflow_error_if(dik < minv - dkj)
444 << "Floyd_All_Shortest_Paths: a distance is below "
445 << "the range of the distance type";
446 }
447 else
448 {
449 can_add = (dik <= std::numeric_limits<Distance_Type>::max() - dkj);
450 }
451 }
452
453 if (!can_add)
454 continue;
455
456 const Distance_Type new_dist = dik + dkj;
457 if (new_dist < dij)
458 {
459 dist(i, j) = new_dist;
460 path_mat(i, j) = path_mat(i, k);
461 }
462 }
463 }
464
466 }
467 }
468
479 Floyd_All_Shortest_Paths(const GT & __g, SA & __sa)
480 : Floyd_All_Shortest_Paths(__g, Distance(), __sa) {}
481
492 Floyd_All_Shortest_Paths(const GT & g, SA && sa = SA())
494
500
515 noexcept(std::is_nothrow_move_constructible_v<SA>
516 and std::is_nothrow_move_constructible_v<Distance>
517 and std::is_nothrow_copy_constructible_v<Distance_Type>)
518 : nodes(std::move(other.nodes)), g(other.g), n(std::exchange(other.n, 0)),
519 Inf(other.Inf), negative_cycle(std::exchange(other.negative_cycle, false)),
520 path_mat(std::move(other.path_mat)), dist(std::move(other.dist)),
521 sa(std::move(other.sa)), distance(std::move(other.distance))
522 {}
523
530 std::string entry(const Distance_Type & e) const
531 {
532 if (e == Inf)
533 return "Inf";
534
535 std::stringstream ss;
536 ss << e;
537 return ss.str();
538 }
539
549 {
550 const Distance_Type Inf = std::numeric_limits<Distance_Type>::max();
551 const int n = dist.rows();
552 for (int i = 0; i < n; ++i)
553 {
554 for (int j = 0; j < n; ++j)
555 if (dist.access(i, j) == Inf)
556 std::cout << "inf ";
557 else
558 std::cout << dist.access(i, j) << " ";
559 std::cout << '\n';
560 }
561 std::cout << '\n';
562 }
563
578 Path<GT> get_min_path(const long src_idx, const long tgt_idx) const
579 {
580 ah_out_of_range_error_if(src_idx < 0 or src_idx >= n)
581 << "Source index out of range";
582 ah_out_of_range_error_if(tgt_idx < 0 or tgt_idx >= n)
583 << "Target index out of range";
585 << "Floyd_All_Shortest_Paths::get_min_path(): the graph has a "
586 << "negative cycle";
587
588 if (dist(src_idx, tgt_idx) == Inf)
589 return Path<GT>(g);
590
591 auto src = nodes(src_idx);
592 Path<GT> path(g, src);
593
594 if (src_idx == tgt_idx)
595 return path;
596
597 auto && d = path_distance();
598 long i = src_idx;
599 while (true)
600 {
601 const auto & k = path_mat(i, tgt_idx);
602 append_lightest_arc(path, nodes(i), nodes(k), d);
603 if (k == tgt_idx)
604 break;
605 i = k;
606 }
607
608 return path;
609 }
610
624 typename GT::Node *tgt) const
625 {
626 return get_min_path(index_node(src), index_node(tgt));
627 }
628 };
629
635 template <AlephGraph GT, ArcDistance<GT> Distance,
636 ArcFilter<GT> SA = Dft_Show_Arc<GT>>
639} // end namespace Aleph
640
641# endif // FLOYD_WARSHALL_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#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_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
C++20 concepts for the protocol shared by graph algorithms.
Standard functor implementations and comparison objects.
High-level sorting functions for Aleph containers.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double w
Definition btreepic.C:153
Default distance accessor for arc weights.
size_t size() const noexcept
Return the current dimension of array.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Dynamic matrix with sparse storage.
Definition tpl_dynMat.H:122
void allocate()
Pre-allocate memory for the entire matrix.
Definition tpl_dynMat.H:271
constexpr size_t rows() const noexcept
Get the number of rows.
Definition tpl_dynMat.H:441
T & access(const size_t i, const size_t j)
Direct access to an allocated entry.
Definition tpl_dynMat.H:542
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Compute the all-pairs shortest path distance matrix and the path reconstruction matrix for a graph g ...
Floyd_All_Shortest_Paths(const GT &__g, D &&__distance, SA __sa=SA())
Construct Floyd-Warshall solver for all-pairs shortest paths.
DynMatrix< Distance_Type > dist
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.
void append_lightest_arc(Path< GT > &path, Node *p, Node *q, D &d) const
Floyd_All_Shortest_Paths(const GT &, Distance, SA=SA()) -> Floyd_All_Shortest_Paths< GT, Distance, SA >
The type of a distance given to the constructor is deduced from it: that of the constructor is not,...
decltype(auto) path_distance() const
Floyd_All_Shortest_Paths(const Floyd_All_Shortest_Paths &other)=default
Copy the matrices of another solver, on the same graph.
std::string entry(const Distance_Type &e) const
Convert a distance value to string representation.
Path< GT > get_min_path(typename GT::Node *src, typename GT::Node *tgt) const
Reconstruct the shortest path between two nodes.
Floyd_All_Shortest_Paths(Floyd_All_Shortest_Paths &&other) noexcept(std::is_nothrow_move_constructible_v< SA > and std::is_nothrow_move_constructible_v< Distance > and std::is_nothrow_copy_constructible_v< Distance_Type >)
Take the matrices of another solver, which is left without nodes, on the same graph.
Distance::Distance_Type Distance_Type
const DynArray< Node * > & get_nodes_ref() const noexcept
Get the array of graph nodes as a constant reference.
Floyd_All_Shortest_Paths(const GT &g, SA &&sa=SA())
Construct Floyd-Warshall solver with rvalue arc filter and a distance accessor built by Distance().
Floyd_All_Shortest_Paths(const GT &__g, SA &__sa)
Construct Floyd-Warshall solver with a distance accessor built by Distance().
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.
static void print(const DynMatrix< Distance_Type > &dist)
Print a distance matrix to standard output.
Path on a graph.
Definition tpl_graph.H:3832
void append(Arc *arc)
Append an arc to the path.
Definition tpl_graph.H:4052
void append_directed(Node *p)
Append a node to a directed path.
Definition tpl_graph.H:4124
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
__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
Main namespace for Aleph-w library functions.
DynArray< T > & in_place_sort(DynArray< T > &c, Cmp cmp=Cmp())
Sorts a DynArray in place.
Definition ahSort.H:328
and
Check uniqueness with explicit hash + equality functors.
bool binary_search(Itor beg, Itor end, const T &value)
Binary search for a value.
Definition ahAlgo.H:1284
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Distance accessor.
static int * k
Dynamic matrix with lazy allocation.
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.
Arc indexing for fast lookup by endpoint nodes.