Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_mincost.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
69#ifndef TPL_MINCOST_H
70#define TPL_MINCOST_H
71
72# include <ah-graph-concepts.H>
73
74#include <cmath>
75#include <limits>
76#include <queue>
77#include <functional>
78#include <tpl_netcost.H>
79#include <tpl_array.H>
80#include <tpl_dynBinHeap.H>
81#include <ah-errors.H>
82
83namespace Aleph {
84
85//==============================================================================
86// SUCCESSIVE SHORTEST PATHS (SSP) ALGORITHM
87//==============================================================================
88
95template <typename Flow_Type>
97{
100 bool in_tree{false};
101 void *parent_arc{nullptr};
102 void *parent_node{nullptr};
103 bool forward{true};
104
105 void reset()
106 {
107 distance = std::numeric_limits<Flow_Type>::max();
108 in_tree = false;
109 parent_arc = nullptr;
110 parent_node = nullptr;
111 }
112};
113
117template <class Net>
119{
120 return *static_cast<SSP_Node_Info<typename Net::Flow_Type> *>(NODE_COOKIE(p));
121}
122
133template <class Net>
134typename Net::Flow_Type reduced_cost(const Net &net, typename Net::Arc *arc, bool forward)
135{
136 using Flow_Type = typename Net::Flow_Type;
137
138 auto src = net.get_src_node(arc);
139 auto tgt = net.get_tgt_node(arc);
140
141 Flow_Type pi_src = ssp_info<Net>(src).potential;
142 Flow_Type pi_tgt = ssp_info<Net>(tgt).potential;
143
144 // Forward arc: src -> tgt with cost arc->cost
145 // Reduced cost = cost + π(src) - π(tgt)
146 if (forward)
147 return arc->cost + pi_src - pi_tgt;
148
149 // Backward arc: tgt -> src with cost -arc->cost
150 // Reduced cost = -cost + π(tgt) - π(src)
151 return -arc->cost + pi_tgt - pi_src;
152}
153
161namespace mincost_detail
162{
163 // Whether two totals of flow are the same: exactly, or, for a floating
164 // type, but for rounding, as check_network() takes them
165 template <typename Flow_Type>
166 bool same_total(const Flow_Type & a, const Flow_Type & b) noexcept
167 {
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;
170 else
171 return a == b;
172 }
173} // namespace mincost_detail
174
175template <class Net>
176bool ssp_shortest_path(Net &net, typename Net::Node *source, typename Net::Node *sink)
177{
178 using Node = typename Net::Node;
179 using Arc = typename Net::Arc;
180 using Flow_Type = typename Net::Flow_Type;
181
182 const Flow_Type INF = std::numeric_limits<Flow_Type>::max();
183
184 // Reset distances
185 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
186 ssp_info<Net>(it.get_curr_ne()).reset();
187
188 ssp_info<Net>(source).distance = 0;
189
190 // Priority queue: (distance, node)
191 using PQ_Entry = std::pair<Flow_Type, Node *>;
193
194 pq.insert({0, source});
195
196 while (not pq.is_empty())
197 {
198 auto [dist, u] = pq.getMin();
199
200 if (dist > ssp_info<Net>(u).distance)
201 continue; // Outdated entry
202
203 // Explore all adjacent arcs
204 for (typename Net::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
205 {
206 Arc *arc = it.get_curr_ne();
207 Node *v = net.get_connected_node(arc, u);
208
209 // Determine direction and residual capacity
210 bool forward = (net.get_src_node(arc) == u);
211 Flow_Type residual = forward ? (arc->cap - arc->flow) : arc->flow;
212
213 if (residual <= Flow_Type{0})
214 continue;
215
216 // Compute reduced cost. The potentials keep it from being
217 // negative but for rounding, which, with costs that are not
218 // exact in binary, as tenths, could take a distance down by an
219 // ulp around a cycle forever
220 Flow_Type rc = reduced_cost<Net>(net, arc, forward);
221 if constexpr (std::is_floating_point_v<Flow_Type>)
222 if (rc < Flow_Type{0})
223 rc = Flow_Type{0};
224
225 // Relaxation (saturate to avoid integer overflow)
226 const Flow_Type INF_D = std::numeric_limits<Flow_Type>::max();
227 const Flow_Type ud = ssp_info<Net>(u).distance;
228 Flow_Type new_dist;
229 if constexpr (std::is_integral_v<Flow_Type>)
230 new_dist = (rc > 0 and ud > INF_D - rc) ? INF_D : ud + rc;
231 else
232 new_dist = ud + rc;
233 if (new_dist < ssp_info<Net>(v).distance)
234 {
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;
239 pq.insert({new_dist, v});
240 }
241 }
242 }
243
244 return ssp_info<Net>(sink).distance < INF;
245}
246
323template <class Net>
324std::pair<typename Net::Flow_Type, typename Net::Flow_Type> successive_shortest_paths(Net &net);
325
343template <class Net>
344bool ssp_init_potentials(Net &net, [[maybe_unused]] typename Net::Node *source)
345{
346 using Flow_Type = typename Net::Flow_Type;
347
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();
351
352 // Overflow-safe addition/subtraction clamped to [LOWEST, INF].
353 auto sat_add = [INF, LOWEST](Flow_Type a, Flow_Type b) noexcept -> Flow_Type {
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;
357 }
358 return a + b;
359 };
360 auto sat_sub = [INF, LOWEST](Flow_Type a, Flow_Type b) noexcept -> Flow_Type {
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;
364 }
365 return a - b;
366 };
367
368 // With floating costs, a relaxation must win more than the rounding of
369 // the sums: a cycle of cost zero, as an arc with a partial flow and its
370 // residual, at c and -c, came out negative, d + c - c < d, and the
371 // check threw for it. A potential is a sum of up to n - 1 costs
372 Flow_Type tol{0};
373 if constexpr (std::is_floating_point_v<Flow_Type>)
374 {
375 Flow_Type largest{0};
376 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
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;
380 }
381 auto improves = [tol](const Flow_Type & d, const Flow_Type & potential) noexcept
382 {
383 if constexpr (std::is_floating_point_v<Flow_Type>)
384 return d < potential - tol;
385 else
386 {
387 (void) tol; // exact for an integer flow
388 return d < potential;
389 }
390 };
391
392 // Initialize distances: 0, through the arc from the virtual node
393 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
394 ssp_info<Net>(it.get_curr_ne()).potential = 0;
395
396 // Bellman-Ford: relax all edges n-1 times
397 for (size_t i = 0; i < n - 1; ++i)
398 {
399 bool changed = false;
400 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
401 {
402 auto arc = it.get_curr_ne();
403 auto src = net.get_src_node(arc);
404 auto tgt = net.get_tgt_node(arc);
405
406 // Forward arc (if has residual capacity)
407 if (arc->cap > arc->flow)
408 {
409 Flow_Type d = ssp_info<Net>(src).potential;
410 if (d < INF)
411 {
412 Flow_Type new_d = sat_add(d, arc->cost);
413 if (improves(new_d, ssp_info<Net>(tgt).potential))
414 {
415 ssp_info<Net>(tgt).potential = new_d;
416 changed = true;
417 }
418 }
419 }
420
421 // Backward arc (if has flow to cancel)
422 if (arc->flow > 0)
423 {
424 Flow_Type d = ssp_info<Net>(tgt).potential;
425 if (d < INF)
426 {
427 Flow_Type new_d = sat_sub(d, arc->cost); // backward: cost is negated
428 if (improves(new_d, ssp_info<Net>(src).potential))
429 {
430 ssp_info<Net>(src).potential = new_d;
431 changed = true;
432 }
433 }
434 }
435 }
436 if (not changed)
437 break;
438 }
439
440 // Negative-cycle detection: one extra relaxation pass.
441 // If any edge can still be relaxed, the residual graph has a negative cycle.
442 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
443 {
444 auto arc = it.get_curr_ne();
445 auto src = net.get_src_node(arc);
446 auto tgt = net.get_tgt_node(arc);
447
448 if (arc->cap > arc->flow)
449 {
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))
452 return false;
453 }
454
455 if (arc->flow > 0)
456 {
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))
459 return false;
460 }
461 }
462
463 return true;
464}
465
466template <FlowNetwork Net>
467std::pair<typename Net::Flow_Type, typename Net::Flow_Type> successive_shortest_paths(Net &net)
468{
469 using Node = typename Net::Node;
470 using Arc = typename Net::Arc;
471 using Flow_Type = typename Net::Flow_Type;
472
474 << "Network must have single source and single sink";
475
476 Node *source = net.get_source();
477 Node *sink = net.get_sink();
478
479 // Allocate node info; fixed size, no reallocation, so element addresses are stable
481 size_t idx = 0;
482 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne(), ++idx)
483 NODE_COOKIE(it.get_curr_ne()) = &node_info(idx);
484
485 // RAII: clear node cookies on every exit path so callers never see
486 // dangling pointers into the local node_info vector.
487 struct CookieClearer
488 {
489 Net &net_;
490 ~CookieClearer()
491 {
492 for (Node_Iterator<Net> it(net_); it.has_curr(); it.next_ne())
493 NODE_COOKIE(it.get_curr_ne()) = nullptr;
494 }
495 } cookie_clearer{net};
496
497 // Initialize potentials using Bellman-Ford to handle possible negative costs
499 << "successive_shortest_paths: negative-cost cycle detected in residual graph";
500
501 // The flows, which go back if something throws, for the strong
502 // guarantee: Dijkstra allocates its heap after a path has changed them
503 struct Flows_Back
504 {
505 Net &net_;
506 Array<Flow_Type> saved;
507 bool done = false;
508 ~Flows_Back()
509 {
510 if (done)
511 return;
512 size_t i = 0;
513 for (Arc_Iterator<Net> it(net_); it.has_curr(); it.next_ne(), ++i)
514 it.get_curr_ne()->flow = saved(i);
515 }
516 } flows_back{net, Array<Flow_Type>(net.get_num_arcs(), Flow_Type{0})};
517 {
518 size_t i = 0;
519 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne(), ++i)
520 flows_back.saved(i) = it.get_curr_ne()->flow;
521 }
522
523 // Main loop: find shortest augmenting paths. A source that is the sink
524 // has none: the empty path from it to itself, which it took, augmented
525 // nothing, and the loop did not end
526 while (source != sink and ssp_shortest_path(net, source, sink))
527 {
528 // Find minimum residual capacity on path. One of arcs of infinite
529 // capacity has none: the maximum flow is infinite, and the flows go
530 // back to those of the entry. It took that path forever, as the
531 // residual of an arc of infinite capacity and flow, inf - inf, is NaN
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;)
535 {
536 Arc *arc = static_cast<Arc *>(ssp_info<Net>(v).parent_arc);
537 bool forward = ssp_info<Net>(v).forward;
538
539 Flow_Type residual = forward ? (arc->cap - arc->flow) : arc->flow;
540 path_flow = std::min(path_flow, residual);
541
542 v = static_cast<Node *>(ssp_info<Net>(v).parent_node);
543 }
544 if constexpr (Limits::has_infinity)
545 ah_domain_error_if(path_flow == Limits::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";
548
549 // Augment flow. With a floating flow, flow + (cap - flow) may come
550 // out an ulp above cap: the arc that bounds the path is filled to
551 // its capacity, exactly, and a flow that goes down next to zero is
552 // zero, as along the augmenting paths of the maximum flows
553 for (Node *v = sink; v != source;)
554 {
555 Arc *arc = static_cast<Arc *>(ssp_info<Net>(v).parent_arc);
556
557 if (ssp_info<Net>(v).forward)
558 net_detail::add_flow(arc, path_flow);
559 else
560 net_detail::subtract_flow(arc, path_flow);
561
562 v = static_cast<Node *>(ssp_info<Net>(v).parent_node);
563 }
564
565 // Update potentials for reachable nodes; track max updated potential
566 // and max finite distance for the unreachable-node shift below.
567 Flow_Type max_potential = std::numeric_limits<Flow_Type>::lowest();
568 Flow_Type max_distance = Flow_Type{0};
569 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
570 if (auto p = it.get_curr_ne();
571 ssp_info<Net>(p).distance < std::numeric_limits<Flow_Type>::max())
572 {
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);
576 }
577
578 // Unreachable nodes are assigned potential = max_potential + max_distance.
579 // This ensures that for any residual arc (u→v) with u unreachable and v
580 // reachable, the reduced cost remains non-negative: the shift by
581 // max_distance dominates the largest finite d(v) seen in Dijkstra.
582 // Saturate to avoid integer overflow when both terms are large.
583 Flow_Type unreachable_potential;
584 if constexpr (std::is_integral_v<Flow_Type>)
585 {
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)
589 ? INF_P
590 : max_potential + max_distance;
591 }
592 else
593 unreachable_potential = max_potential + max_distance;
594
595 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
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;
599 }
600
601 // The residues of rounding that the paths leave go back, as those of
602 // the maximum flows; before the flows are done, so that an allocation
603 // that throws in it takes them back to those of the entry
604 net_detail::return_dust(net, source, sink);
605 flows_back.done = true;
606
607 // The value and the cost of the whole flow, with what the network had
608 Flow_Type total_cost{0};
609 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
610 total_cost += it.get_curr_ne()->flow * it.get_curr_ne()->cost;
611
612 return {net.flow_value(), total_cost};
613}
614
618template <class Net>
620{
621 std::pair<typename Net::Flow_Type, typename Net::Flow_Type> operator()(Net &net) const
622 {
623 return successive_shortest_paths(net);
624 }
625};
626
627//==============================================================================
628// MINIMUM COST FLOW WITH DEMAND (TRANSSHIPMENT)
629//==============================================================================
630
639template <typename Flow_Type>
644
648template <typename Flow_Type>
655
705template <class Net, class GetDemand>
707{
708 using Node = typename Net::Node;
709 using Flow_Type = typename Net::Flow_Type;
710
712
713 // Calculate total supply and demand
714 Flow_Type total_supply{0};
715 Flow_Type total_demand{0};
716
717 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
718 {
719 Flow_Type d = get_demand(it.get_curr());
720 if (d > 0)
721 total_supply += d;
722 else
723 total_demand -= d;
724 }
725
726 // Check balance
727 if (not mincost_detail::same_total(total_supply, total_demand))
728 {
729 result.feasible = false;
730 return result;
731 }
732
733 // Zero total flow: trivially feasible with no flow needed.
734 if (total_supply == Flow_Type{0})
735 {
736 result.feasible = true;
737 return result;
738 }
739
740 // The super nodes go, with their arcs, before returning. Not in a
741 // destructor: a removal allocates in a network, and may throw.
742 Node *super_source = nullptr;
743 Node *super_sink = nullptr;
744 auto remove_super_nodes = [&]
745 {
746 if (super_sink != nullptr)
747 {
748 net.remove_node(super_sink);
749 super_sink = nullptr;
750 }
751 if (super_source != nullptr)
752 {
753 net.remove_node(super_source);
754 super_source = nullptr;
755 }
756 };
757
758 try
759 {
760 super_source = net.insert_node();
761 super_sink = net.insert_node();
762
763 // Connect super-source to supply nodes
764 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
765 {
766 Node *p = it.get_curr();
767 if (p == super_source or p == super_sink)
768 continue;
769
770 Flow_Type d = get_demand(p);
771 if (d > 0)
772 net.insert_arc(super_source, p, d, Flow_Type{0}); // zero cost
773 else if (d < 0)
774 net.insert_arc(p, super_sink, -d, Flow_Type{0}); // zero cost
775 }
776
777 // The other sources and sinks, through arcs of capacity 0, so that
778 // the network has one source and one sink
779 DynList<Node *> sources, sinks;
780 for (auto it = net.get_src_nodes().get_it(); it.has_curr(); it.next_ne())
781 if (it.get_curr() != super_source)
782 sources.append(it.get_curr());
783 for (auto it = net.get_sink_nodes().get_it(); it.has_curr(); it.next_ne())
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())
787 net.insert_arc(super_source, it.get_curr(), Flow_Type{0}, Flow_Type{0});
788 for (auto it = sinks.get_it(); it.has_curr(); it.next_ne())
789 net.insert_arc(it.get_curr(), super_sink, Flow_Type{0}, Flow_Type{0});
790
791 // Solve min-cost max-flow
792 auto [flow, cost] = successive_shortest_paths(net);
793
794 result.total_flow = flow;
795 result.total_cost = cost;
796 result.feasible = mincost_detail::same_total(flow, total_supply);
797 }
798 catch (...)
799 {
800 // If the removal fails too, the super nodes stay, and the first
801 // exception goes on
802 try
803 {
804 remove_super_nodes();
805 }
806 catch (...)
807 {
808 // empty
809 }
810 throw;
811 }
812
813 remove_super_nodes();
814 return result;
815}
816
817//==============================================================================
818// ASSIGNMENT PROBLEM
819//==============================================================================
820
824template <typename Cost_Type>
831
871template <typename Cost_Type>
872AssignmentResult<Cost_Type> solve_assignment(const std::vector<std::vector<Cost_Type>> &costs)
873{
875 using Node = typename Net::Node;
876
878
879 size_t n = costs.size();
880 if (n == 0)
881 {
882 result.feasible = true;
883 return result;
884 }
885
886 // Verify square matrix: a non-square costs matrix is malformed input.
887 for (const auto &row : costs)
888 ah_invalid_argument_if(row.size() != n)
889 << "solve_assignment: costs matrix is not square (" << n << " x " << row.size() << ")";
890
891 Net net;
892
893 // Create source and sink
894 Node *source = net.insert_node();
895 Node *sink = net.insert_node();
896
897 // Create worker nodes
898 auto workers = Array<Node *>::create(n);
899 for (size_t i = 0; i < n; ++i)
900 {
901 workers[i] = net.insert_node();
902 net.insert_arc(source, workers[i], Cost_Type{1}, Cost_Type{0});
903 }
904
905 // Create task nodes
906 auto tasks = Array<Node *>::create(n);
907 DynMapTree<Node *, size_t> taskIndex; // Reverse lookup: task node -> index
908 for (size_t j = 0; j < n; ++j)
909 {
910 tasks[j] = net.insert_node();
911 taskIndex.insert(tasks[j], j);
912 net.insert_arc(tasks[j], sink, Cost_Type{1}, Cost_Type{0});
913 }
914
915 // Create worker-task arcs with costs
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]);
919
920 // Source and sink are detected automatically by network topology
921
922 // Solve
923 auto [flow, cost] = successive_shortest_paths(net);
924
925 result.feasible = (static_cast<size_t>(flow) == n);
926 result.total_cost = cost;
927
928 // Extract assignments from flow
929 if (result.feasible)
930 for (size_t i = 0; i < n; ++i)
931 for (typename Net::Node_Arc_Iterator it(workers[i]); it.has_curr(); it.next_ne())
932 {
933 auto arc = it.get_curr();
934 if (arc->flow <= 0)
935 continue;
936 auto tgt = net.get_tgt_node(arc);
937
938 // O(log n) lookup instead of O(n) linear search
939 if (taskIndex.contains(tgt))
940 {
941 size_t j = taskIndex.find(tgt);
942 result.assignments.append(std::make_pair(i, j));
943 }
944 }
945
946 return result;
947}
948
949//==============================================================================
950// TRANSPORTATION PROBLEM
951//==============================================================================
952
956template <typename Cost_Type>
958{
959 bool feasible{false};
960 Cost_Type total_cost{0};
961 std::vector<std::vector<Cost_Type>> shipments;
962};
963
1002template <typename Cost_Type>
1003TransportationResult<Cost_Type> solve_transportation(const std::vector<Cost_Type> &supplies,
1004 const std::vector<Cost_Type> &demands,
1005 const std::vector<std::vector<Cost_Type>> &costs)
1006{
1008 using Node = typename Net::Node;
1009 using Arc = typename Net::Arc;
1010
1012
1013 size_t m = supplies.size(); // sources
1014 size_t n = demands.size(); // destinations
1015
1016 // Validate costs matrix dimensions
1017 ah_invalid_argument_if(costs.size() != m)
1018 << "solve_transportation: costs has " << costs.size() << " rows but " << m << " supply points";
1019 for (size_t i = 0; i < m; ++i)
1020 ah_invalid_argument_if(costs[i].size() != n)
1021 << "solve_transportation: costs[" << i << "] has " << costs[i].size() << " columns but " << n
1022 << " demand points";
1023
1024 // Validate non-negative supplies and demands
1025 for (size_t i = 0; i < m; ++i)
1026 ah_invalid_argument_if(supplies[i] < Cost_Type{0})
1027 << "solve_transportation: supplies[" << i << "] is negative";
1028 for (size_t j = 0; j < n; ++j)
1029 ah_invalid_argument_if(demands[j] < Cost_Type{0})
1030 << "solve_transportation: demands[" << j << "] is negative";
1031
1032 // Compute totals first — needed both for the early-exit guard and the
1033 // balance check that follows.
1034 Cost_Type total_supply = Cost_Type{0};
1035 Cost_Type total_demand = Cost_Type{0};
1036 for (auto s : supplies)
1037 total_supply += s;
1038 for (auto d : demands)
1039 total_demand += d;
1040
1041 // If either side is empty no graph can be built. Return immediately based
1042 // on whether the totals are balanced (feasible iff both are zero).
1043 if (m == 0 or n == 0)
1044 {
1045 result.feasible = mincost_detail::same_total(total_supply, total_demand);
1046 return result;
1047 }
1048
1049 // Check supply-demand balance for the non-trivial case, but for rounding
1050 if (not mincost_detail::same_total(total_supply, total_demand))
1051 {
1052 result.feasible = false;
1053 return result;
1054 }
1055
1056 Net net;
1057
1058 // Create source and sink
1059 Node *source = net.insert_node();
1060 Node *sink = net.insert_node();
1061
1062 // Create supply nodes
1063 auto supply_nodes = Array<Node *>::create(m);
1064 for (size_t i = 0; i < m; ++i)
1065 {
1066 supply_nodes(i) = net.insert_node();
1067 net.insert_arc(source, supply_nodes(i), supplies[i], Cost_Type{0});
1068 }
1069
1070 // Create demand nodes
1071 auto demand_nodes = Array<Node *>::create(n);
1072 for (size_t j = 0; j < n; ++j)
1073 {
1074 demand_nodes(j) = net.insert_node();
1075 net.insert_arc(demand_nodes(j), sink, demands[j], Cost_Type{0});
1076 }
1077
1078 // Create arcs between supplies and demands, kept by rows for extracting
1079 // the solution: that from supply i to demand j is arcs[i * n + j]
1080 auto arcs = Array<Arc *>::create(m * n);
1081 for (size_t i = 0; i < m; ++i)
1082 for (size_t j = 0; j < n; ++j)
1083 arcs(i * n + j) = net.insert_arc(supply_nodes(i),
1084 demand_nodes(j),
1085 std::min(supplies[i], demands[j]),
1086 costs[i][j]);
1087
1088 // Source and sink are detected automatically by network topology
1089
1090 // Solve
1091 auto [flow, cost] = successive_shortest_paths(net);
1092
1093 result.feasible = mincost_detail::same_total(flow, total_supply);
1094 result.total_cost = cost;
1095
1096 // Extract shipments
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)
1100 result.shipments[i][j] = arcs(i * n + j)->flow;
1101
1102 return result;
1103}
1104
1105//==============================================================================
1106// MIN-COST FLOW STATISTICS
1107//==============================================================================
1108
1112template <typename Flow_Type>
1114{
1117 size_t iterations{0};
1118 size_t augmentations{0};
1119 double elapsed_ms{0};
1120
1121 void print() const
1122 {
1123 std::cout << "=== Min-Cost Flow Statistics ===\n"
1124 << "Max flow: " << max_flow << "\n"
1125 << "Min cost: " << min_cost << "\n"
1126 << "Iterations: " << iterations << "\n"
1127 << "Augmentations: " << augmentations << "\n"
1128 << "Time: " << elapsed_ms << " ms\n";
1129 }
1130};
1131
1132//==============================================================================
1133// WARM START FOR NETWORK SIMPLEX
1134//==============================================================================
1135
1147template <class Net>
1149{
1151
1152 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1153 {
1154 auto arc = it.get_curr();
1155 solution[arc] = arc->flow;
1156 }
1157
1158 return solution;
1159}
1160
1172template <class Net>
1175{
1176 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1177 {
1178 auto arc = it.get_curr();
1179 if (solution.has(arc))
1180 arc->flow = solution[arc];
1181 }
1182}
1183
1184} // namespace Aleph
1185
1186#endif // TPL_MINCOST_H
Exception handling system with formatted messages for Aleph-w.
#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.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
size_t row
Definition ca-c-api.h:115
Iterator over the arcs of a node.
Definition tpl_agraph.H:354
bool has_curr() const noexcept
Return true if the iterator is on an arc.
Definition tpl_agraph.H:387
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
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).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
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.
Definition tpl_graph.H:1287
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
constexpr size_t vsize() const noexcept
See get_num_nodes().
Definition graph-dry.H:984
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define NODE_COOKIE(p)
Return the node cookie
double Flow_Type
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...
Definition tpl_net.H:1410
void add_flow(Arc *arc, const Flow_Type &slack) noexcept
Definition tpl_net.H:1227
void subtract_flow(Arc *arc, const Flow_Type &slack) noexcept
Definition tpl_net.H:1283
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.
Definition tpl_graph.H:1200
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.
Definition tpl_netcost.H:96
Capacitated flow network with costs associated to arcs.
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
Definition tpl_net.H:750
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
Definition tpl_net.H:595
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
Definition tpl_net.H:589
constexpr bool is_single_source() const noexcept
Return true if the network has a single source.
Definition tpl_net.H:429
Node * get_source() const
Return an arbitrary source node.
Definition tpl_net.H:733
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.
Definition tpl_net.H:799
void remove_node(Node *p) override
Remove node p and all its arcs from the network.
Definition tpl_net.H:933
ArcT Arc
Arc type.
Definition tpl_net.H:322
Node * get_sink() const
Return an arbitrary sink node.
Definition tpl_net.H:739
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...
Definition tpl_net.H:1139
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Definition tpl_net.H:328
constexpr bool is_single_sink() const noexcept
Return true if the network has a single sink.
Definition tpl_net.H:435
NodeT Node
Node type.
Definition tpl_net.H:325
Node info for SSP algorithm.
Definition tpl_mincost.H:97
bool forward
Direction of parent arc.
Flow_Type distance
Shortest path distance.
Definition tpl_mincost.H:99
bool in_tree
Is node in shortest path tree?
Flow_Type potential
Node potential for reduced costs.
Definition tpl_mincost.H:98
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.