95template <
typename Flow_Type>
107 distance = std::numeric_limits<Flow_Type>::max();
141 Flow_Type pi_src = ssp_info<Net>(src).potential;
142 Flow_Type pi_tgt = ssp_info<Net>(tgt).potential;
147 return arc->cost + pi_src - pi_tgt;
151 return -arc->cost + pi_tgt - pi_src;
161namespace mincost_detail
165 template <
typename Flow_Type>
168 if constexpr (std::is_floating_point_v<Flow_Type>)
169 return std::abs(a - b) <= std::max(std::abs(a), std::abs(b)) * 1e-9;
182 const Flow_Type INF = std::numeric_limits<Flow_Type>::max();
186 ssp_info<Net>(it.get_curr_ne()).reset();
188 ssp_info<Net>(source).distance = 0;
191 using PQ_Entry = std::pair<Flow_Type, Node *>;
198 auto [dist, u] = pq.
getMin();
200 if (dist > ssp_info<Net>(u).distance)
206 Arc *arc = it.get_curr_ne();
211 Flow_Type residual = forward ? (arc->cap - arc->flow) : arc->flow;
220 Flow_Type rc = reduced_cost<Net>(net, arc, forward);
221 if constexpr (std::is_floating_point_v<Flow_Type>)
226 const Flow_Type INF_D = std::numeric_limits<Flow_Type>::max();
227 const Flow_Type ud = ssp_info<Net>(u).distance;
229 if constexpr (std::is_integral_v<Flow_Type>)
230 new_dist = (rc > 0
and ud > INF_D - rc) ? INF_D : ud + rc;
233 if (new_dist < ssp_info<Net>(v).distance)
235 ssp_info<Net>(v).distance = new_dist;
236 ssp_info<Net>(v).parent_arc = arc;
237 ssp_info<Net>(v).parent_node = u;
238 ssp_info<Net>(v).forward = forward;
244 return ssp_info<Net>(sink).distance < INF;
348 const Flow_Type INF = std::numeric_limits<Flow_Type>::max();
349 const Flow_Type LOWEST = std::numeric_limits<Flow_Type>::lowest();
350 const size_t n = net.
vsize();
354 if constexpr (std::is_integral_v<Flow_Type>) {
355 if (b > 0
and a > INF - b)
return INF;
356 if (b < 0
and a < LOWEST - b)
return LOWEST;
361 if constexpr (std::is_integral_v<Flow_Type>) {
362 if (b < 0 and a > INF + b)
return INF;
363 if (b > 0
and a < LOWEST + b)
return LOWEST;
373 if constexpr (std::is_floating_point_v<Flow_Type>)
377 if (
const Flow_Type c = std::abs(it.get_curr_ne()->cost); c < INF)
378 largest = std::max(largest, c);
379 tol = 4 *
Flow_Type(n) *
Flow_Type(n) * std::numeric_limits<Flow_Type>::epsilon() * largest;
383 if constexpr (std::is_floating_point_v<Flow_Type>)
384 return d < potential - tol;
388 return d < potential;
394 ssp_info<Net>(it.get_curr_ne()).potential = 0;
397 for (
size_t i = 0; i < n - 1; ++i)
399 bool changed =
false;
402 auto arc = it.get_curr_ne();
407 if (arc->cap > arc->flow)
409 Flow_Type d = ssp_info<Net>(src).potential;
413 if (improves(new_d, ssp_info<Net>(tgt).potential))
415 ssp_info<Net>(tgt).potential = new_d;
424 Flow_Type d = ssp_info<Net>(tgt).potential;
428 if (improves(new_d, ssp_info<Net>(src).potential))
430 ssp_info<Net>(src).potential = new_d;
444 auto arc = it.get_curr_ne();
448 if (arc->cap > arc->flow)
450 Flow_Type d = ssp_info<Net>(src).potential;
451 if (d < INF
and improves(sat_add(d, arc->cost), ssp_info<Net>(tgt).potential))
457 Flow_Type d = ssp_info<Net>(tgt).potential;
458 if (d < INF
and improves(sat_sub(d, arc->cost), ssp_info<Net>(src).potential))
466template <FlowNetwork Net>
474 <<
"Network must have single source and single sink";
495 } cookie_clearer{net};
499 <<
"successive_shortest_paths: negative-cost cycle detected in residual graph";
514 it.get_curr_ne()->flow = saved(i);
520 flows_back.saved(i) = it.get_curr_ne()->flow;
532 using Limits = std::numeric_limits<Flow_Type>;
533 Flow_Type path_flow = Limits::has_infinity ? Limits::infinity() : Limits::max();
534 for (
Node *v = sink; v != source;)
536 Arc *arc =
static_cast<Arc *
>(ssp_info<Net>(v).parent_arc);
537 bool forward = ssp_info<Net>(v).forward;
539 Flow_Type residual = forward ? (arc->cap - arc->flow) : arc->flow;
540 path_flow = std::min(path_flow, residual);
542 v =
static_cast<Node *
>(ssp_info<Net>(v).parent_node);
544 if constexpr (Limits::has_infinity)
546 <<
"successive_shortest_paths: the maximum flow is infinite, through a "
547 <<
"path of arcs of infinite capacity from the source to the sink";
553 for (
Node *v = sink; v != source;)
555 Arc *arc =
static_cast<Arc *
>(ssp_info<Net>(v).parent_arc);
557 if (ssp_info<Net>(v).forward)
562 v =
static_cast<Node *
>(ssp_info<Net>(v).parent_node);
567 Flow_Type max_potential = std::numeric_limits<Flow_Type>::lowest();
570 if (
auto p = it.get_curr_ne();
571 ssp_info<Net>(p).distance < std::numeric_limits<Flow_Type>::max())
573 max_distance = std::max(max_distance, ssp_info<Net>(p).distance);
574 ssp_info<Net>(p).potential += ssp_info<Net>(p).distance;
575 max_potential = std::max(max_potential, ssp_info<Net>(p).potential);
584 if constexpr (std::is_integral_v<Flow_Type>)
586 const Flow_Type INF_P = std::numeric_limits<Flow_Type>::max();
587 unreachable_potential =
588 (max_distance > 0
and max_potential > INF_P - max_distance)
590 : max_potential + max_distance;
593 unreachable_potential = max_potential + max_distance;
596 if (
auto p = it.get_curr_ne();
597 ssp_info<Net>(p).distance >= std::numeric_limits<Flow_Type>::max())
598 ssp_info<Net>(p).potential = unreachable_potential;
605 flows_back.done =
true;
610 total_cost += it.get_curr_ne()->flow * it.get_curr_ne()->cost;
621 std::pair<typename Net::Flow_Type, typename Net::Flow_Type>
operator()(
Net &net)
const
639template <
typename Flow_Type>
648template <
typename Flow_Type>
705template <
class Net,
class GetDemand>
742 Node *super_source =
nullptr;
743 Node *super_sink =
nullptr;
744 auto remove_super_nodes = [&]
746 if (super_sink !=
nullptr)
749 super_sink =
nullptr;
751 if (super_source !=
nullptr)
754 super_source =
nullptr;
766 Node *p = it.get_curr();
767 if (p == super_source or p == super_sink)
781 if (it.get_curr() != super_source)
782 sources.
append(it.get_curr());
784 if (it.get_curr() != super_sink)
785 sinks.
append(it.get_curr());
786 for (
auto it = sources.
get_it(); it.has_curr(); it.next_ne())
788 for (
auto it = sinks.
get_it(); it.has_curr(); it.next_ne())
804 remove_super_nodes();
813 remove_super_nodes();
824template <
typename Cost_Type>
871template <
typename Cost_Type>
879 size_t n = costs.size();
887 for (
const auto &
row : costs)
889 <<
"solve_assignment: costs matrix is not square (" << n <<
" x " <<
row.size() <<
")";
899 for (
size_t i = 0; i < n; ++i)
902 net.
insert_arc(source, workers[i], Cost_Type{1}, Cost_Type{0});
908 for (
size_t j = 0; j < n; ++j)
911 taskIndex.
insert(tasks[j], j);
912 net.
insert_arc(tasks[j], sink, Cost_Type{1}, Cost_Type{0});
916 for (
size_t i = 0; i < n; ++i)
917 for (
size_t j = 0; j < n; ++j)
918 net.
insert_arc(workers[i], tasks[j], Cost_Type{1}, costs[i][j]);
925 result.
feasible = (
static_cast<size_t>(flow) == n);
930 for (
size_t i = 0; i < n; ++i)
933 auto arc = it.get_curr();
941 size_t j = taskIndex.
find(tgt);
956template <
typename Cost_Type>
1002template <
typename Cost_Type>
1004 const std::vector<Cost_Type> &demands,
1005 const std::vector<std::vector<Cost_Type>> &costs)
1013 size_t m = supplies.
size();
1014 size_t n = demands.size();
1018 <<
"solve_transportation: costs has " << costs.size() <<
" rows but " <<
m <<
" supply points";
1019 for (
size_t i = 0; i <
m; ++i)
1021 <<
"solve_transportation: costs[" << i <<
"] has " << costs[i].
size() <<
" columns but " << n
1022 <<
" demand points";
1025 for (
size_t i = 0; i <
m; ++i)
1027 <<
"solve_transportation: supplies[" << i <<
"] is negative";
1028 for (
size_t j = 0; j < n; ++j)
1030 <<
"solve_transportation: demands[" << j <<
"] is negative";
1034 Cost_Type total_supply = Cost_Type{0};
1035 Cost_Type total_demand = Cost_Type{0};
1036 for (
auto s : supplies)
1038 for (
auto d : demands)
1043 if (
m == 0 or n == 0)
1064 for (
size_t i = 0; i <
m; ++i)
1067 net.
insert_arc(source, supply_nodes(i), supplies[i], Cost_Type{0});
1072 for (
size_t j = 0; j < n; ++j)
1075 net.
insert_arc(demand_nodes(j), sink, demands[j], Cost_Type{0});
1081 for (
size_t i = 0; i <
m; ++i)
1082 for (
size_t j = 0; j < n; ++j)
1085 std::min(supplies[i], demands[j]),
1097 result.
shipments.resize(
m, std::vector<Cost_Type>(n, Cost_Type{0}));
1098 for (
size_t i = 0; i <
m; ++i)
1099 for (
size_t j = 0; j < n; ++j)
1112template <
typename Flow_Type>
1123 std::cout <<
"=== Min-Cost Flow Statistics ===\n"
1124 <<
"Max flow: " <<
max_flow <<
"\n"
1125 <<
"Min cost: " <<
min_cost <<
"\n"
1154 auto arc = it.get_curr();
1155 solution[arc] = arc->flow;
1178 auto arc = it.get_curr();
1179 if (solution.
has(arc))
1180 arc->flow = solution[arc];
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Node Node
Iterator over the arcs of a node.
bool has_curr() const noexcept
Return true if the iterator is on an arc.
Simple dynamic array with automatic resizing and functional operations.
static Array create(const size_t n)
Create an array with n logical elements.
Dynamic heap of elements of type T ordered by a comparison functor.
T getMin()
Remove the minimum element (according to Compare) and return it.
T & insert(const T &item)
Insert a copy of item into the heap.
Doubly-linked list (defined in tpl_dynList.H).
T & append(const T &item)
Generic key-value map implemented on top of a binary search tree.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
bool contains(const Key &key) const noexcept(nothrow_search)
Same as has().
Data & find(const Key &key)
Find the value associated with key.
bool has(const Key &key) const noexcept(nothrow_search)
Return whether key is in the map.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
bool is_empty() const noexcept
Filtered iterator on the nodes of a graph.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
constexpr size_t vsize() const noexcept
See get_num_nodes().
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
constexpr size_t size() const noexcept
Returns the number of entries in the table.
DynArray< Graph::Arc * > arcs
#define NODE_COOKIE(p)
Return the node cookie
bool same_total(const Flow_Type &a, const Flow_Type &b) noexcept
void return_dust(Net &net, typename Net::Node *source, typename Net::Node *sink)
Returns the dust of a floating flow that a preflow algorithm left in net, from source to sink: what e...
void add_flow(Arc *arc, const Flow_Type &slack) noexcept
void subtract_flow(Arc *arc, const Flow_Type &slack) noexcept
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool ssp_init_potentials(Net &net, typename Net::Node *source)
Initialize potentials using Bellman-Ford.
void restore_flow_solution(Net &net, const DynMapTree< typename Net::Arc *, typename Net::Flow_Type > &solution)
Restore network simplex solution from warm start.
and
Check uniqueness with explicit hash + equality functors.
TransportationResult< Cost_Type > solve_transportation(const std::vector< Cost_Type > &supplies, const std::vector< Cost_Type > &demands, const std::vector< std::vector< Cost_Type > > &costs)
Solve the transportation problem using min-cost flow.
SSP_Node_Info< typename Net::Flow_Type > & ssp_info(typename Net::Node *p) noexcept
Access SSP node info.
TransshipmentResult< typename Net::Flow_Type > solve_transshipment(Net &net, GetDemand get_demand)
Solve minimum cost transshipment problem.
std::pair< typename Net::Flow_Type, typename Net::Flow_Type > successive_shortest_paths(Net &net)
Compute minimum cost maximum flow using Successive Shortest Paths.
AssignmentResult< Cost_Type > solve_assignment(const std::vector< std::vector< Cost_Type > > &costs)
Solve the assignment problem using min-cost flow.
bool ssp_shortest_path(Net &net, typename Net::Node *source, typename Net::Node *sink)
DynMapTree< typename Net::Arc *, typename Net::Flow_Type > save_flow_solution(const Net &net)
Save network simplex solution for warm start.
Net::Flow_Type reduced_cost(const Net &net, typename Net::Arc *arc, bool forward)
Compute reduced cost of an arc.
Filtered iterator on all the arcs of a graph.
Result of assignment problem.
DynList< std::pair< size_t, size_t > > assignments
(worker, task) pairs
Statistics for min-cost flow algorithms.
Arc type for maximum flow minimum cost networks.
Capacitated flow network with costs associated to arcs.
Flow network implemented with adjacency lists.
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
constexpr bool is_single_source() const noexcept
Return true if the network has a single source.
Node * get_source() const
Return an arbitrary source node.
Arc * insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &flow, const typename Arc::Arc_Type &arc_info=Arc_Type())
Insert a capacitated arc with an initial flow.
void remove_node(Node *p) override
Remove node p and all its arcs from the network.
Node * get_sink() const
Return an arbitrary sink node.
Flow_Type flow_value() const
Return the total flow value of the network: the flow out of its sources, which a valid flow also take...
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
constexpr bool is_single_sink() const noexcept
Return true if the network has a single sink.
Node info for SSP algorithm.
bool forward
Direction of parent arc.
Flow_Type distance
Shortest path distance.
bool in_tree
Is node in shortest path tree?
Flow_Type potential
Node potential for reduced costs.
void * parent_node
Parent node.
void * parent_arc
Parent arc in shortest path tree.
Functor wrapper for SSP algorithm.
std::pair< typename Net::Flow_Type, typename Net::Flow_Type > operator()(Net &net) const
Result of transportation problem.
std::vector< std::vector< Cost_Type > > shipments
shipments[i][j] from i to j
Result of transshipment problem.
Flow_Type total_cost
Total transportation cost.
bool feasible
Is there a feasible solution?
Flow_Type total_flow
Total flow shipped.
Node with supply/demand for transshipment problems.
Flow_Type demand
Positive = supply, negative = demand.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Dynamic array container with automatic resizing.
Dynamic binary heap with node-based storage.
Maximum flow minimum cost network algorithms.