183template <AlephGraph
GT,
224 if constexpr (std::is_integral_v<Distance_Type>)
228 <<
"Integer overflow in distance addition: " << a <<
" + " << b;
232 <<
"Integer underflow in distance addition: " << a <<
" + " << b;
245 if constexpr (std::is_integral_v<Distance_Type>)
247 if (b > 0
and a > std::numeric_limits<Distance_Type>::max() - b) [[unlikely]]
253 <<
"Integer underflow in distance addition: " << a <<
" + " << b;
272 <<
"Bellman_Ford: the distance from the start to a node does not fit "
275 for (NAit<GT, SA> it(p,
sa_); it.has_curr(); it.next_ne())
298 <<
"from a weight or from an overflow";
308 if constexpr (
requires (
const Distance &d)
309 { { d.tolerance() } -> std::convertible_to<Distance_Type>; })
311 if constexpr (std::is_integral_v<Distance_Type>)
316 return accum >= std::numeric_limits<Distance_Type>::lowest() + tol
332 if constexpr (std::is_floating_point_v<Distance_Type>)
333 if (not (
sum > -std::numeric_limits<Distance_Type>::infinity()))
352 typename GT::Node_Iterator it(
g_);
353 for (
size_t i = 0; it.has_curr(); ++i, it.next())
356 auto p = it.get_curr();
361 ptr->idx =
static_cast<int>(i);
394 template <
class Info_Type>
397 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next())
399 auto p = it.get_curr();
423 size_t num_painted_arcs = 0;
424 size_t num_painted_nodes = 0;
427 for (Ait<GT, SA> it(
g_,
sa_); it.has_curr(); it.next_ne())
432 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next_ne())
434 auto node = it.get_curr();
445 size_t incoming_count = 0;
446 for (Ait<GT, SA> ait(
g_,
sa_); ait.has_curr(); ait.next_ne())
447 if (
auto arc = ait.get_curr();
452 if (incoming_count != 1)
457 return num_painted_nodes != 0
and num_painted_arcs == num_painted_nodes - 1;
505 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next_ne())
508 for (Ait<GT, SA> it(
g_,
sa_); it.has_curr(); it.next_ne())
522 return s_ !=
nullptr;
558 for (
size_t i = 0; i < n - 1; ++i)
560 bool relaxed =
false;
561 for (Ait<GT, SA> it(
g_,
sa_); it.has_curr(); it.next_ne())
563 auto arc = it.get_curr();
565 const auto &accum_src =
accum(src);
566 if (accum_src ==
Inf)
569 auto tgt = it.get_tgt_node_ne();
574 auto &accum_tgt =
accum(tgt);
577 const auto &index =
idx(tgt);
611 for (NAit<GT, SA> it(src,
sa_); it.has_curr(); it.next_ne())
613 auto arc = it.get_curr();
615 const auto &accum_src =
accum(arc_src);
616 if (accum_src ==
Inf)
624 auto &accum_tgt =
accum(tgt);
627 const auto &index =
idx(tgt);
639 for (
size_t i = 0; i < n; ++i)
661 bool negative_cycle =
false;
662 for (Ait<GT, SA> it(
g_,
sa_); it.has_curr(); it.next_ne())
664 auto arc = it.get_curr();
666 auto &accum_src =
accum(src);
667 if (accum_src ==
Inf)
672 auto &accum_tgt =
accum(tgt);
679 negative_cycle =
true;
680 const auto &index =
idx(tgt);
686 return negative_cycle;
692 for (Ait<GT, SA> it(
g_,
sa_); it.has_curr(); it.next_ne())
694 auto arc = it.get_curr();
696 auto &accum_src =
accum(src);
697 if (accum_src ==
Inf)
702 auto &accum_tgt =
accum(tgt);
720 for (
size_t i = 0; i < n; ++i)
730 if (start !=
nullptr)
742 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next_ne())
763 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next_ne())
764 mark(it.get_curr()) = 0;
767 auto cycle_reached_from = [&](
Node *v) ->
Node *
773 while (p !=
nullptr and mark(p) == 0)
778 return p !=
nullptr and mark(p) == walk ? p :
nullptr;
782 for (
typename GT::Node_Iterator it(
g_); c ==
nullptr and it.has_curr(); it.next_ne())
783 c = cycle_reached_from(it.get_curr());
799 for (
auto it = cycle.
get_it(); it.has_curr(); it.next_ne())
811 "Serious inconsistency. Bellman-Ford algorithm has detected\n"
812 "a negative cycle, but the graph of the predecessors has no\n"
814 "Be very careful, this is provably a bug");
844 if (not negative_cycle)
853 return negative_cycle;
880 Node *sentinel = &__sentinel;
885 for (
size_t i = 0; not q.
is_empty();)
906 if (not negative_cycle)
915 return negative_cycle;
957 return negative_cycle;
991 Node *sentinel = &__sentinel;
995 double threshold = it_factor * n;
1002 if (src == sentinel)
1015 return std::make_tuple(std::move(ret), i);
1031 return std::make_tuple(std::move(ret), i);
1043 Node *sentinel = &__sentinel;
1047 for (
size_t i = 0; not q.
is_empty(); )
1050 if (src == sentinel)
1205 for (
size_t i = 0; i <
arcs_.
size(); ++i)
1229 for (
auto curr = node; curr !=
s_; )
1235 for (NAit<GT, SA> it(parent,
sa_); it.has_curr(); it.next_ne())
1236 if (
auto arc = it.get_curr();
1274 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next_ne())
1276 auto gp = it.get_curr();
1281 for (
typename GT::Node_Iterator it(
g_); it.has_curr(); it.next_ne())
1283 auto gtgt = it.get_curr();
1285 if (gsrc ==
nullptr)
1289 Arc *garc =
nullptr;
1292 auto a = ait.get_curr();
1301 auto tsrc_ptr = table.
search(gsrc);
1302 auto ttgt_ptr = table.
search(gtgt);
1305 auto tarc = tree.
insert_arc(tsrc_ptr->second, ttgt_ptr->second, garc->get_info());
1358 return Aleph::get_min_path<GT, Distance>(
s_, end, path,
dist_);
1381 Node *sentinel = &__sentinel;
1386 for (
size_t i = 0; not q.
is_empty(); )
1389 if (src == sentinel)
1404 if (not negative_cycle)
1405 for (
auto it =
g_.
get_node_it(); it.has_curr(); it.next_ne())
1407 auto p = it.get_curr();
1438template <AlephGraph
GT,
1485 SA &&sa = SA())
const
Tarjan's algorithm for strongly connected components.
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error()
Throws std::domain_error unconditionally.
#define ah_logic_error_unless(C)
Throws std::logic_error if condition does NOT hold.
#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.
C++20 concepts for the protocol shared by graph algorithms.
#define WARNING(...)
Print a warning message (no-op when MESSAGES is not defined).
RAII guard for exception-safe resource cleanup.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
void empty() noexcept
Empties the container.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
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.
void init_with_indexes(Node *start)
Initialize node cookies with predecessor tracking for path reconstruction.
Path< GT > negative_cycle_witness()
The witness of a negative cycle that the last pass found.
bool has_computation() const noexcept
Check if a shortest-path tree has been computed or painted.
bool last_relax_and_prepare_check_negative_cycle()
Perform one more relaxation pass and check for negative cycle.
bool check_painted_arcs() noexcept(nothrow_arc_filter_v< GT, SA >)
Check that painted arcs form a valid spanning tree structure.
static void throw_not_finite()
bool faster_paint_spanning_tree(Node *start)
Faster shortest paths tree painting from a start node.
void link_cookies_and_free(typename GT::Node *start) noexcept
Free node cookies and set up predecessor pointers for path reconstruction.
bool relaxes(const Distance_Type &sum, const Distance_Type &accum) const
Whether sum relaxes the distance accum: it is below it, by more than the tolerance of the distance,...
void relax_arcs()
Relax all arcs up to n-1 times (standard Bellman-Ford).
DynMapTree< Node *, Distance_Type > compute_nodes_weights()
Returns a mapping with the shortest distances to each node obtained after executing the Bellman-Ford ...
Path< GT > search_negative_cycle(Node *start)
Searches a negative cycle using the faster version of Bellman-Ford algorithm (SPFA variant).
bool test_negative_cycle(typename GT::Node *s, Path< GT > &cycle)
Test for negative cycle and return it if found.
void check_beyond_max(Node *start)
std::tuple< Path< GT >, size_t > faster_find_negative_cycle(Node *start, double it_factor, size_t step)
SPFA, which, from it_factor * n rounds, and then every step rounds, looks for a cycle among the prede...
static GT::Node * get_from_queue(DynListQueue< typename GT::Node * > &q)
Remove a node from the queue and clear its in-queue flag.
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
bool detect_negative_cycle(Node *start)
void uninit() noexcept
Release the memory associated with the node cookies, and the bits Depth_First that SPFA leaves on the...
Path< GT > search_negative_cycle()
See search_negative_cycle(Node * start).
Path< GT > test_negative_cycle()
Searches and returns a negative cycle (if it exists).
void clear() noexcept(nothrow_arc_filter_v< GT, SA >)
Clear the painted state and reset internal data structures.
void paint_tree() noexcept
Paint the spanning tree nodes and arcs with the Spanning_Tree bit.
std::tuple< Path< GT >, size_t > search_negative_cycle(double it_factor, const size_t step)
Searches a negative cycle using the faster version of Bellman-Ford algorithm and iteratively searchin...
Path< GT > cycle_of_predecessors()
A cycle of the graph of the predecessors, the arcs of the last relaxations, as a path of its arcs; em...
void put_sources_in_queue(DynListQueue< typename GT::Node * > &q)
Put in q the start, or, without one, every node, as the virtual source reaches them.
bool is_painted() const noexcept
Check if a shortest-path tree has been painted.
void abandon() noexcept
Leave the object without a computation, and the graph without the data of the nodes,...
bool add_if_fits(const Distance_Type &a, const Distance_Type &b, Distance_Type &out)
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()
Test if a negative cycle exists anywhere in the graph.
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
bool last_relax_and_test_negative_cycle()
Perform one more relaxation pass to detect (but not prepare) negative cycle.
void relax_arcs(typename GT::Node *src, DynListQueue< typename GT::Node * > &q)
Relax outgoing arcs from a source node (SPFA variant).
static void put_in_queue(DynListQueue< typename GT::Node * > &q, typename GT::Node *p)
Insert a node into the queue if not already present (SPFA optimization).
Array< typename GT::Arc * > arcs_
static Distance_Type & accum(Node *p) noexcept
Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extract the shortest path to a node from a previously painted tree.
bool test_negative_cycle(Path< GT > &cycle)
Test for negative cycle anywhere in the graph.
Node * pred_node(Node *p) noexcept
The source of the arc by which the last relaxation of p reached it, or nullptr.
static int & idx(Node *p) noexcept
Bellman_Ford(GT &__g, Distance d=Distance(), SA __sa=SA())
Construct a Bellman-Ford executor.
const GT & get_graph() const noexcept
Get reference to the graph.
Path< GT > faster_find_negative_cycle(Node *start)
SPFA; without a start, every node is a source.
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.
Path< GT > find_negative_cycle(Node *start)
Without a start, every node is a source.
Distance_Type checked_add(const Distance_Type &a, const Distance_Type &b) const
void build_tree(GT &tree, bool with_map=true)
Extract from the graph a previously painted shortest paths tree.
Distance::Distance_Type Distance_Type
static void check_finite(const Distance_Type &sum)
Throw domain_error if a floating sum of the last pass is -inf or NaN, from a weight or from an overfl...
static size_t & mark(Node *p) noexcept
Stack of the frames of a depth-first search that does not recurse.
T & push(Args &&...args)
Builds a frame on top of the stack.
bool is_empty() const noexcept
Whether the stack has no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
Default distance accessor for arc weights.
bool has_curr() const noexcept
Return true the iterator has an current arc.
T & touch(const size_t i)
Touch the entry i.
void reserve(const size_t l, const size_t r)
Allocate a range of entries.
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
T & insert(const T &item)
Generic key-value map implemented on top of a binary search tree.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Dynamic set backed by balanced binary search trees with automatic memory management.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
RAII guard for graph algorithm initialization.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Graph_Node< Node_Info > Node
The graph type.
Graph_Arc< Arc_Info > Arc
The node class type.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Filtered iterator for outcoming arcs of a node.
bool is_empty() const noexcept
Return true if the path is empty.
void append_directed(Node *p)
Append a node to a directed path.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
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)
static void map_arcs(A1 *p, A2 *q) noexcept
Map the arcs through their cookies.
void reset_bit(Node *node, int bit) const noexcept
Reset the bit of node (to zero)
constexpr size_t vsize() const noexcept
See get_num_nodes().
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
static void map_nodes(N1 *p, N2 *q) noexcept
Map the nodes through their cookies.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
RAII guards for graph node/arc cookies.
__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)
constexpr bool nothrow_arc_filter_v
Whether a filter of type SA of the arcs of GT is copied, moved and called without exceptions: then an...
#define ARC_COOKIE(p)
Return the arc cookie
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
#define NODE_BITS(p)
Get the control bits of a node.
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Filtered iterator on all the arcs of a graph.
Detects if a negative cycle exists and eventually computes it.
Path< GT > operator()(GT &g, typename GT::Node *s, Distance &d, SA &sa) const
Search for a negative cycle starting from a specific node.
bool operator()(GT &g, typename GT::Node *s, Path< GT > &path, Distance &&d=Distance(), SA &&sa=SA()) const
Path< GT > operator()(GT &g, Distance &&d=Distance(), SA &&sa=SA()) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
bool operator()(GT &g, Path< GT > &path, Distance &d, SA &sa) const
Invokes the detection and calculation of a negative cycle.
bool operator()(GT &g, typename GT::Node *s, Path< GT > &path, Distance &d, SA &sa) const
Invokes the detection and calculation of a negative cycle.
Path< GT > operator()(GT &g, Distance &d, SA &sa) const
Search for a negative cycle in the entire graph.
Path< GT > operator()(GT &g, typename GT::Node *s, Distance &&d=Distance(), SA &&sa=SA()) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
bool operator()(GT &g, Path< GT > &path, Distance &&d=Distance(), SA &&sa=SA()) const
Default filter for filtered iterators on arcs.
Filtered iterator of adjacent arcs of a node.
Dynamic array container with automatic resizing.
Stack of the frames of a depth-first search that does not recurse.
Dynamic queue implementation based on linked lists.
Dynamic set implementations based on balanced binary search trees.
Utility algorithms and operations for graphs.