Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_maxflow.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
79#ifndef TPL_MAXFLOW_H
80#define TPL_MAXFLOW_H
81
82#include <ah-graph-concepts.H>
83
84#include <cassert>
85#include <limits>
86#include <sstream>
87#include <iomanip>
88#include <iostream>
89#include <algorithm>
90#include <tpl_array.H>
91#include <tpl_dynListQueue.H>
92#include <tpl_net.H>
93#include <tpl_dynDlist.H>
94#include <ah-errors.H>
95#include <cookie_guard.H>
96
97namespace Aleph {
98//==============================================================================
99// DINIC'S ALGORITHM
100//==============================================================================
101
109template <typename Flow_Type>
111{
112 long level = -1;
113 bool blocked = false;
114 size_t current_arc = 0;
115
116 void reset() noexcept
117 {
118 level = -1;
119 blocked = false;
120 current_arc = 0;
121 }
122};
123
137template <class Net>
138inline long &dinic_level(typename Net::Node *p) noexcept
139{
140 assert(NODE_COOKIE(p) != nullptr &&
141 "NODE_COOKIE not initialized; call dinic_maximum_flow() instead");
142 return static_cast<Dinic_Node_Info<typename Net::Flow_Type> *>(NODE_COOKIE(p))->level;
143}
144
158template <class Net>
159inline bool &dinic_blocked(typename Net::Node *p) noexcept
160{
161 assert(NODE_COOKIE(p) != nullptr &&
162 "NODE_COOKIE not initialized; call dinic_maximum_flow() instead");
163 return static_cast<Dinic_Node_Info<typename Net::Flow_Type> *>(NODE_COOKIE(p))->blocked;
164}
165
177template <class Net>
178inline size_t &dinic_current_arc(typename Net::Node *p) noexcept
179{
180 assert(NODE_COOKIE(p) != nullptr &&
181 "NODE_COOKIE not initialized; call dinic_maximum_flow() instead");
182 return static_cast<Dinic_Node_Info<typename Net::Flow_Type> *>(NODE_COOKIE(p))->current_arc;
183}
184
198template <class Net>
199inline bool is_dinic_cookie_valid(typename Net::Node *p) noexcept
200{
201 return NODE_COOKIE(p) != nullptr;
202}
203
222template <class Net>
223bool build_level_graph(Net &net, typename Net::Node *source, typename Net::Node *sink)
224{
225 using Node = typename Net::Node;
226 using Flow_Type = typename Net::Flow_Type;
227
228 // Validate NODE_COOKIE and reset all levels in a single pass
229 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
230 {
231 auto p = it.get_curr_ne();
232 assert(is_dinic_cookie_valid<Net>(p) &&
233 "NODE_COOKIE not initialized for Dinic's algorithm. "
234 "Call dinic_maximum_flow() instead of build_level_graph() directly, "
235 "or initialize Dinic_Node_Info for all nodes before calling.");
236 dinic_level<Net>(p) = -1;
237 dinic_blocked<Net>(p) = false;
238 dinic_current_arc<Net>(p) = 0;
239 }
240
241 // BFS from source
243 dinic_level<Net>(source) = 0;
244 queue.put(source);
245
246 while (not queue.is_empty())
247 {
248 Node *curr = queue.front();
249 queue.get();
250
251 // Explore all adjacent arcs
252 for (typename Net::Node_Arc_Iterator it(curr); it.has_curr(); it.next_ne())
253 {
254 auto arc = it.get_curr_ne();
255 auto next = net.get_connected_node(arc, curr);
256
257 // Skip if already visited
258 if (dinic_level<Net>(next) >= 0)
259 continue;
260
261 // Check residual capacity
262 Flow_Type residual;
263 if (net.get_src_node(arc) == curr)
264 residual = arc->cap - arc->flow; // Forward edge
265 else
266 residual = arc->flow; // Backward edge
267
268 if (residual > Flow_Type{0})
269 {
270 dinic_level<Net>(next) = dinic_level<Net>(curr) + 1;
271 queue.put(next);
272 }
273 }
274 }
275
276 return dinic_level<Net>(sink) >= 0;
277}
278
295template <class Net>
296typename Net::Flow_Type dinic_blocking_flow(Net &net, typename Net::Node *source,
297 typename Net::Node *sink)
298{
299 using Node = typename Net::Node;
300 using Arc = typename Net::Arc;
301 using Flow_Type = typename Net::Flow_Type;
302
303 const size_t n = net.vsize();
304
305 // Path stack: stack[0]=source, ..., stack[depth-1]=current node
306 // path_arcs[i] = arc from stack[i] to stack[i+1]
307 // path_fwd[i] = true if path_arcs[i] is a forward arc
308 auto stack = Array<Node *>::create(n);
309 auto path_arcs = Array<Arc *>::create(n);
310 auto path_fwd = Array<char>::create(n); // char instead of bool for safety
311
312 stack(0) = source;
313 size_t depth = 1;
314 Flow_Type total_flow{0};
315
316 while (depth > 0)
317 {
318 Node *curr = stack(depth - 1);
319
320 if (curr == sink)
321 {
322 // Augmenting path found — compute bottleneck
323 Flow_Type bottleneck = std::numeric_limits<Flow_Type>::max();
324 size_t bottleneck_pos = 0;
325 for (size_t i = 0; i + 1 < depth; ++i)
326 {
327 Flow_Type res =
328 path_fwd(i) ? (path_arcs(i)->cap - path_arcs(i)->flow) : path_arcs(i)->flow;
329 if (res < bottleneck)
330 {
331 bottleneck = res;
332 bottleneck_pos = i;
333 }
334 }
335
336 // Augment flow along the path; a floating flow that rounding
337 // leaves next to the capacity or to zero is set to it
338 for (size_t i = 0; i + 1 < depth; ++i)
339 {
340 if (path_fwd(i))
341 net_detail::add_flow(path_arcs(i), bottleneck);
342 else
343 net_detail::subtract_flow(path_arcs(i), bottleneck);
344 }
345
346 total_flow += bottleneck;
347
348 // Retreat to the node whose outgoing arc was the bottleneck.
349 // That arc is now saturated, so this node will advance its
350 // current_arc past it on the next iteration.
351 depth = bottleneck_pos + 1;
352 continue;
353 }
354
355 // Try to advance from curr using its current-arc index
356 size_t &ca = dinic_current_arc<Net>(curr);
357 bool advanced = false;
358
359 while (ca < curr->num_arcs)
360 {
361 Arc *arc = static_cast<Arc *>(curr->arc_array[ca]);
362 Node *next = net.get_connected_node(arc, curr);
363
364 // Only follow edges to the next level
365 if (dinic_level<Net>(next) != dinic_level<Net>(curr) + 1)
366 {
367 ++ca;
368 continue;
369 }
370
371 // Skip blocked nodes (all their arcs are exhausted)
372 if (dinic_blocked<Net>(next))
373 {
374 ++ca;
375 continue;
376 }
377
378 // Check residual capacity. An arc of infinite capacity that
379 // carries an infinite flow has inf - inf, NaN, which is no
380 // residual: compared as residual <= 0, it went on taking the
381 // same path forever
382 const bool is_forward = (net.get_src_node(arc) == curr);
383 Flow_Type residual = is_forward ? (arc->cap - arc->flow) : arc->flow;
384
385 if (not (residual > Flow_Type{0}))
386 {
387 ++ca;
388 continue;
389 }
390
391 // Valid arc — push next onto the path
392 path_arcs(depth - 1) = arc;
393 path_fwd(depth - 1) = is_forward ? 1 : 0;
394 stack(depth) = next;
395 ++depth;
396 advanced = true;
397 break;
398 }
399
400 if (not advanced)
401 {
402 // Dead end — block this node and retreat
403 dinic_blocked<Net>(curr) = true;
404 --depth;
405 }
406 }
407
408 return total_flow;
409}
410
461template <FlowNetwork Net>
463{
464 using Node = typename Net::Node;
465 using Flow_Type = typename Net::Flow_Type;
466
468 << "Network must have single source and single sink";
469
470 Node *source = net.get_source();
471 Node *sink = net.get_sink();
472
473 if (source == sink)
474 return Flow_Type{0};
475
476 // Allocate node info first so it outlives cookie_saver.
477 // C++ destroys locals in reverse order: cookie_saver restores
478 // original cookies before node_info storage is freed.
479 auto node_info = Array<Dinic_Node_Info<Flow_Type>>::create(net.vsize());
480 Cookie_Saver<Net> cookie_saver(net, true, false); // save nodes only
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 // Main loop: build level graph and find blocking flows
486 while (build_level_graph(net, source, sink))
487 (void) dinic_blocking_flow(net, source, sink);
488
489 // The residues of rounding that the blocking flows leave go back, as
490 // those of the augmenting paths, as a node that received 5.6e-17 and
491 // sent nothing
492 net_detail::return_dust(net, source, sink);
493
494 // Cookie_Saver destructor will restore original NODE_COOKIE values
495 return net.flow_value(); // with the flow that the network had
496}
497
501template <FlowNetwork Net>
503{
518 typename Net::Flow_Type operator () (Net &net) const
519 {
520 return dinic_maximum_flow(net);
521 }
522};
523
524//==============================================================================
525// CAPACITY SCALING
526//==============================================================================
527
572template <FlowNetwork Net>
574{
575 using Node = typename Net::Node;
576 using Arc = typename Net::Arc;
577 using Flow_Type = typename Net::Flow_Type;
578
580 << "Network must have single source and single sink";
581
582 Node *source = net.get_source();
583 Node *sink = net.get_sink();
584
585 // Find maximum capacity to determine starting Δ. An infinite one gives
586 // no scale: Δ doubled up to it forever, also on a network whose
587 // maximum flow is finite
588 Flow_Type max_cap{0};
589 bool infinite_cap = false;
590 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
591 {
592 const Flow_Type cap = it.get_curr()->cap;
593 if constexpr (std::numeric_limits<Flow_Type>::has_infinity)
594 if (cap == std::numeric_limits<Flow_Type>::infinity())
595 {
596 infinite_cap = true;
597 continue;
598 }
599 max_cap = std::max(max_cap, cap);
600 }
601
602 if (max_cap == Flow_Type{0} and not infinite_cap)
603 return Flow_Type{0};
604
605 // Start with the largest power of 2 ≤ max_cap
606 Flow_Type delta{1};
607 while (delta <= max_cap / 2)
608 delta *= 2;
609
610 // BFS augmentation helper.
611 // Finds and augments all s-t paths where every edge has
612 // residual >= min_residual. Returns total flow found.
613 auto bfs_augment = [&](Flow_Type min_residual) -> Flow_Type
614 {
615 Flow_Type phase_flow{0};
616 bool found_path = true;
617 while (found_path)
618 {
619 found_path = false;
620
622 DynMapTree<Node *, Arc *> parent_arc;
623 DynMapTree<Node *, bool> is_forward;
624
626 queue.put(source);
627 parent[source] = nullptr;
628
629 while (not queue.is_empty() and not parent.has(sink))
630 {
631 Node *curr = queue.front();
632 queue.get();
633
634 for (typename Net::Node_Arc_Iterator it(curr); it.has_curr(); it.next_ne())
635 {
636 Arc *arc = it.get_curr();
637 Node *next = net.get_connected_node(arc, curr);
638
639 if (parent.has(next))
640 continue;
641
642 Flow_Type residual;
643 bool forward = (net.get_src_node(arc) == curr);
644
645 if (forward)
646 residual = arc->cap - arc->flow;
647 else
648 residual = arc->flow;
649
650 if (residual >= min_residual and residual > Flow_Type{0})
651 {
652 parent[next] = curr;
653 parent_arc[next] = arc;
654 is_forward[next] = forward;
655 queue.put(next);
656 }
657 }
658 }
659
660 if (parent.has(sink))
661 {
662 found_path = true;
663
664 Flow_Type path_flow = std::numeric_limits<Flow_Type>::max();
665 for (Node *n = sink; n != source; n = parent[n])
666 {
667 Arc *arc = parent_arc[n];
668 Flow_Type residual = is_forward[n] ? (arc->cap - arc->flow) : arc->flow;
669 path_flow = std::min(path_flow, residual);
670 }
671
672 for (Node *n = sink; n != source; n = parent[n])
673 {
674 Arc *arc = parent_arc[n];
675 if (is_forward[n])
676 net_detail::add_flow(arc, path_flow);
677 else
678 net_detail::subtract_flow(arc, path_flow);
679 }
680
681 phase_flow += path_flow;
682 }
683 }
684 return phase_flow;
685 };
686
687 // Scaling phases (delta = largest power of 2 down to 1)
688 while (delta >= Flow_Type{1})
689 {
690 (void) bfs_augment(delta);
691 delta /= 2;
692 }
693
694 // Final cleanup: capture any fractional residual flow.
695 // For integer capacities the scaling phases already found all flow,
696 // so this is a single O(V+E) no-op BFS.
697 (void) bfs_augment(Flow_Type{0});
698
699 // The residues of rounding that the paths leave go back, as those of
700 // the augmenting paths, as a node that received 5.6e-17 and sent nothing
701 net_detail::return_dust(net, source, sink);
702
703 return net.flow_value(); // with the flow that the network had
704}
705
709template <FlowNetwork Net>
711{
726 typename Net::Flow_Type operator () (Net &net) const
727 {
729 }
730};
731
732//==============================================================================
733// FLOW DECOMPOSITION
734//==============================================================================
735
745template <class Net>
747{
748 using Arc = typename Net::Arc;
749 using Node = typename Net::Node;
750 using Flow_Type = typename Net::Flow_Type;
751
755
763 [[nodiscard]] bool is_empty() const noexcept
764 {
765 return arcs.is_empty();
766 }
767
775 [[nodiscard]] size_t length() const noexcept
776 {
777 return arcs.size();
778 }
779};
780
789template <class Net>
791{
792 using Arc = typename Net::Arc;
793 using Node = typename Net::Node;
794 using Flow_Type = typename Net::Flow_Type;
795
799};
800
808template <class Net>
810{
811 using Flow_Type = typename Net::Flow_Type;
812
815
823 Flow_Type total_flow() const noexcept
824 {
825 Flow_Type sum{0};
826 for (auto it = paths.get_it(); it.has_curr(); it.next_ne())
827 sum += it.get_curr().flow;
828 return sum;
829 }
830
838 [[nodiscard]] size_t num_paths() const noexcept
839 {
840 return paths.size();
841 }
842
850 [[nodiscard]] size_t num_cycles() const noexcept
851 {
852 return cycles.size();
853 }
854};
855
901template <FlowNetwork Net>
903{
904 using Node = typename Net::Node;
905 using Arc = typename Net::Arc;
906 using Flow_Type = typename Net::Flow_Type;
907
909 << "Network must have single source and single sink";
910
912
913 // Create a copy of flow values (we'll modify them during decomposition)
915 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
916 {
917 Arc *arc = it.get_curr();
918 remaining_flow[arc] = arc->flow;
919 }
920
921 Node *source = net.get_source();
922 Node *sink = net.get_sink();
923
924 // Find paths from source to sink
925 while (true)
926 {
927 // Find an arc from source with positive remaining flow
928 Arc *start_arc = nullptr;
929 for (typename Net::Node_Arc_Iterator it(source); it.has_curr(); it.next_ne())
930 {
931 Arc *arc = it.get_curr();
932 if (net.get_src_node(arc) == source and remaining_flow[arc] > Flow_Type{0})
933 {
934 start_arc = arc;
935 break;
936 }
937 }
938
939 if (start_arc == nullptr)
940 break; // No more flow from source
941
942 // Build path by following positive flow, tracking visited nodes to detect cycles
943 FlowPath<Net> path;
944 path.nodes.append(source);
945
946 Node *curr = net.get_tgt_node(start_arc);
947 path.arcs.append(start_arc);
948 path.nodes.append(curr);
949 path.flow = remaining_flow[start_arc];
950
951 // Track visited nodes and their position in path for cycle detection
953 visited[source] = 0;
954 visited[curr] = 1;
955
956 while (curr != sink)
957 {
958 // Find outgoing arc with positive flow
959 Arc *next_arc = nullptr;
960 for (typename Net::Node_Arc_Iterator it(curr); it.has_curr(); it.next_ne())
961 {
962 Arc *arc = it.get_curr();
963 if (net.get_src_node(arc) == curr and remaining_flow[arc] > Flow_Type{0})
964 {
965 next_arc = arc;
966 break;
967 }
968 }
969
970 if (next_arc == nullptr)
971 { // curr does not send all it receives: if rounding leaves
972 // it, in a floating flow, what the last arc brings is left
973 // out, so that the walk does not start again forever; any
974 // more is a flow that is not conserved
975 const Flow_Type in = net.get_in_flow(curr), out = net.get_out_flow(curr);
977 << "decompose_flow(): the flow is not conserved at a node, which receives " << in
978 << " and sends " << out;
980 break;
981 }
982
983 Node *next_node = net.get_tgt_node(next_arc);
984
985 // Check if we've visited this node before (cycle detected)
986 if (visited.contains(next_node))
987 {
988 // Extract the cycle starting from the repeated node
989 const size_t cycle_start = visited[next_node];
990 FlowCycle<Net> cycle;
991 cycle.flow = remaining_flow[next_arc];
992
993 // Build cycle from the position where we first saw next_node
994 auto node_it = path.nodes.get_it();
995 auto arc_it = path.arcs.get_it();
996
997 // Skip to the cycle start position
998 for (size_t i = 0; i < cycle_start; ++i)
999 {
1000 node_it.next_ne();
1001 arc_it.next_ne();
1002 }
1003
1004 // Collect cycle nodes and arcs, compute minimum flow
1005 while (arc_it.has_curr())
1006 {
1007 cycle.nodes.append(node_it.get_curr());
1008 cycle.arcs.append(arc_it.get_curr());
1009 cycle.flow = std::min(cycle.flow, remaining_flow[arc_it.get_curr()]);
1010 node_it.next_ne();
1011 arc_it.next_ne();
1012 }
1013 // Add the node where the closing arc starts, the closing
1014 // arc and the closing node to complete the cycle
1015 cycle.nodes.append(curr);
1016 cycle.arcs.append(next_arc);
1017 cycle.flow = std::min(cycle.flow, remaining_flow[next_arc]);
1018 cycle.nodes.append(next_node);
1019
1020 // Subtract cycle flow from cycle arcs
1021 for (auto it = cycle.arcs.get_it(); it.has_curr(); it.next_ne())
1022 remaining_flow[it.get_curr()] -= cycle.flow;
1023
1024 if (cycle.flow > Flow_Type{0})
1025 result.cycles.append(std::move(cycle));
1026
1027 // At this point we have removed all flow along the detected cycle
1028 // from 'remaining_flow'. We intentionally discard the current
1029 // partial path (the prefix up to 'cycle_start') and restart path
1030 // construction from the source in the outer loop. This does not
1031 // lose any flow because the prefix arcs were not modified and
1032 // remain available for future paths/cycles. The trade-off is that
1033 // we may re-traverse some nodes/edges, which is acceptable here
1034 // under the assumption that cycles in the residual flow are rare.
1035 break;
1036 }
1037
1038 path.arcs.append(next_arc);
1039 path.flow = std::min(path.flow, remaining_flow[next_arc]);
1040 curr = next_node;
1041 path.nodes.append(curr);
1042 visited[curr] = path.nodes.size() - 1;
1043 }
1044
1045 // Subtract path flow from all arcs (only if we reached sink)
1046 if (curr == sink and path.flow > Flow_Type{0})
1047 {
1048 for (auto it = path.arcs.get_it(); it.has_curr(); it.next_ne())
1049 remaining_flow[it.get_curr()] -= path.flow;
1050 result.paths.append(std::move(path));
1051 }
1052 }
1053
1054 // Second phase: find cycles in the remaining flow (not connected to source)
1055 // These are cycles that exist independently of the s-t flow
1056 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1057 {
1058 Node *start = it.get_curr();
1059
1060 // Try to find a cycle starting from this node
1061 while (true)
1062 {
1063 // Find an outgoing arc with positive remaining flow
1064 Arc *first_arc = nullptr;
1065 for (typename Net::Node_Arc_Iterator ait(start); ait.has_curr(); ait.next_ne())
1066 {
1067 Arc *arc = ait.get_curr();
1068 if (net.get_src_node(arc) == start and remaining_flow[arc] > Flow_Type{0})
1069 {
1070 first_arc = arc;
1071 break;
1072 }
1073 }
1074
1075 if (first_arc == nullptr)
1076 break; // No outgoing flow from this node
1077
1078 // Follow the flow to find a cycle
1079 FlowCycle<Net> cycle;
1081 DynList<Arc *> path_arcs;
1082 DynList<Node *> path_nodes;
1083
1084 path_nodes.append(start);
1085 visited[start] = 0;
1086
1087 Node *curr = net.get_tgt_node(first_arc);
1088 path_arcs.append(first_arc);
1089 path_nodes.append(curr);
1090
1091 bool found_cycle = false;
1092
1093 while (not found_cycle)
1094 {
1095 if (visited.contains(curr))
1096 {
1097 // Found a cycle starting at 'curr'
1098 const size_t cycle_start = visited[curr];
1099 cycle.flow = std::numeric_limits<Flow_Type>::max();
1100
1101 // Skip to cycle start in path
1102 auto node_it = path_nodes.get_it();
1103 auto arc_it = path_arcs.get_it();
1104 for (size_t i = 0; i < cycle_start; ++i)
1105 {
1106 node_it.next_ne();
1107 arc_it.next_ne();
1108 }
1109
1110 // Collect cycle and find minimum flow
1111 while (arc_it.has_curr())
1112 {
1113 cycle.nodes.append(node_it.get_curr());
1114 cycle.arcs.append(arc_it.get_curr());
1115 cycle.flow = std::min(cycle.flow, remaining_flow[arc_it.get_curr()]);
1116 node_it.next_ne();
1117 arc_it.next_ne();
1118 }
1119 // Add the closing node to complete the cycle (as Phase 1 does)
1120 cycle.nodes.append(curr);
1121
1122 found_cycle = true;
1123 break;
1124 }
1125
1126 visited[curr] = path_nodes.size() - 1;
1127
1128 // Find next arc with positive flow
1129 Arc *next_arc = nullptr;
1130 for (typename Net::Node_Arc_Iterator ait(curr); ait.has_curr(); ait.next_ne())
1131 {
1132 Arc *arc = ait.get_curr();
1133 if (net.get_src_node(arc) == curr and remaining_flow[arc] > Flow_Type{0})
1134 {
1135 next_arc = arc;
1136 break;
1137 }
1138 }
1139
1140 if (next_arc == nullptr)
1141 break; // Dead end, no cycle from this path
1142
1143 path_arcs.append(next_arc);
1144 curr = net.get_tgt_node(next_arc);
1145 path_nodes.append(curr);
1146 }
1147
1148 if (found_cycle and cycle.flow > Flow_Type{0})
1149 {
1150 // Subtract cycle flow from all cycle arcs
1151 for (auto cit = cycle.arcs.get_it(); cit.has_curr(); cit.next_ne())
1152 remaining_flow[cit.get_curr()] -= cycle.flow;
1153 result.cycles.append(std::move(cycle));
1154 }
1155 else
1156 break; // No cycle found from this start node
1157 }
1158 }
1159
1160 return result;
1161}
1162
1166template <FlowNetwork Net>
1168{
1184 {
1185 return decompose_flow(net);
1186 }
1187};
1188
1189//==============================================================================
1190// HIGHEST LABEL PREFLOW-PUSH (HLPP)
1191//==============================================================================
1192
1197template <typename Flow_Type, bool = std::is_floating_point_v<Flow_Type>>
1199{
1200 long height = 0;
1202};
1203
1212template <typename Flow_Type>
1221
1223template <class Net>
1224inline long &hlpp_height(typename Net::Node *p) noexcept
1225{
1226 return static_cast<HLPP_Node_Info<typename Net::Flow_Type> *>(NODE_COOKIE(p))->height;
1227}
1228
1230template <class Net>
1231inline typename Net::Flow_Type &hlpp_excess(typename Net::Node *p) noexcept
1232{
1233 return static_cast<HLPP_Node_Info<typename Net::Flow_Type> *>(NODE_COOKIE(p))->excess;
1234}
1235
1268template <FlowNetwork Net>
1270{
1271 using Node = typename Net::Node;
1272 using Arc = typename Net::Arc;
1273 using Flow_Type = typename Net::Flow_Type;
1274
1276 << "Network must have single source and single sink";
1277
1278 Node *source = net.get_source();
1279 Node *sink = net.get_sink();
1280 const size_t n_nodes = net.vsize();
1281 const long n = static_cast<long>(n_nodes);
1282
1283 // Allocate node info first so it outlives cookie_saver.
1284 // C++ destroys locals in reverse order: cookie_saver restores
1285 // original cookies before node_info storage is freed.
1286 auto node_info = Array<HLPP_Node_Info<Flow_Type>>::create(n_nodes);
1287 Cookie_Saver<Net> cookie_saver(net, true, false); // save nodes only
1288
1289 // A path of arcs of infinite capacity makes the maximum flow infinite
1290 // (see net_detail::fill_infinite_path()). Its search writes in the
1291 // cookies of the nodes, after cookie_saver has saved them
1293 return net.flow_value();
1294
1295 {
1296 size_t idx = 0;
1297 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne(), ++idx)
1298 NODE_COOKIE(it.get_curr_ne()) = &node_info(idx);
1299 }
1300
1301 // --- Initialize heights via reverse BFS from sink ---
1302 // All heights start at n (unreachable); BFS sets exact distances
1303 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1304 hlpp_height<Net>(it.get_curr_ne()) = n;
1305
1306 hlpp_height<Net>(sink) = 0;
1307
1308 {
1310 queue.put(sink);
1311 while (not queue.is_empty())
1312 {
1313 Node *curr = queue.get();
1314 for (typename Net::Node_Arc_Iterator ait(curr); ait.has_curr(); ait.next_ne())
1315 {
1316 auto arc = ait.get_curr_ne();
1317 auto next = net.get_connected_node(arc, curr);
1318
1319 if (next == source or hlpp_height<Net>(next) != n)
1320 continue;
1321
1322 // In the residual graph (flow = 0 initially), there is a
1323 // residual arc next→curr iff the original arc goes
1324 // next→curr with cap > 0.
1325 if (net.get_src_node(arc) == next and arc->cap > Flow_Type{0})
1326 {
1327 hlpp_height<Net>(next) = hlpp_height<Net>(curr) + 1;
1328 queue.put(next);
1329 }
1330 }
1331 }
1332 }
1333
1334 // Source always has height = n
1335 hlpp_height<Net>(source) = n;
1336
1337 // With a floating flow, the flows into and out of each node, which
1338 // follow every push and give its excess; they start from the flow
1339 // that the network has
1340 constexpr bool floating = std::is_floating_point_v<Flow_Type>;
1341 [[maybe_unused]] auto info = [](Node *p)
1342 {
1343 return static_cast<HLPP_Node_Info<Flow_Type> *>(NODE_COOKIE(p));
1344 };
1345 if constexpr (floating)
1346 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1347 {
1348 Arc *arc = it.get_curr_ne();
1349 info(net.get_src_node(arc))->out.add(arc->flow);
1350 info(net.get_tgt_node(arc))->in.add(arc->flow);
1351 }
1352
1353 // --- Saturate all arcs from source ---
1354 // An arc of infinite capacity takes a bound of the maximum flow instead
1355 // (see net_detail::infinite_arc_preflow()), computed once if one needs it
1356 [[maybe_unused]] Flow_Type bound{0};
1357 [[maybe_unused]] bool bounded = false;
1358 for (typename Net::Node_Arc_Iterator it(source); it.has_curr(); it.next_ne())
1359 if (Arc *arc = it.get_curr_ne(); net.get_src_node(arc) == source)
1360 {
1361 Flow_Type full = arc->cap;
1362 if constexpr (std::numeric_limits<Flow_Type>::has_infinity)
1363 if (full == std::numeric_limits<Flow_Type>::infinity())
1364 {
1365 if (not bounded)
1366 {
1368 bounded = true;
1369 }
1370 full = std::max(bound, arc->flow);
1371 }
1372 Flow_Type delta = full - arc->flow;
1373 if constexpr (floating)
1374 {
1375 info(source)->out.replace(arc->flow, full);
1376 info(net.get_tgt_node(arc))->in.replace(arc->flow, full);
1377 }
1378 arc->flow = full;
1379 hlpp_excess<Net>(net.get_tgt_node(arc)) += delta;
1380 hlpp_excess<Net>(source) -= delta;
1381 }
1382 if constexpr (floating) // the excesses, from the flows
1383 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1384 {
1385 Node *p = it.get_curr_ne();
1386 hlpp_excess<Net>(p) = info(p)->in.minus(info(p)->out);
1387 }
1388
1389 // With a floating flow, whether p is in a bucket; else whether it has
1390 // an excess, as a node with one is in a bucket
1391 auto in_a_bucket = [](Node *p) -> bool
1392 {
1393 if constexpr (floating)
1394 return static_cast<HLPP_Node_Info<Flow_Type> *>(NODE_COOKIE(p))->in_bucket;
1395 else
1396 return hlpp_excess<Net>(p) > Flow_Type{0};
1397 };
1398 auto set_in_a_bucket = [](Node *p, bool in)
1399 {
1400 if constexpr (floating)
1401 static_cast<HLPP_Node_Info<Flow_Type> *>(NODE_COOKIE(p))->in_bucket = in;
1402 else
1403 (void) p, (void) in;
1404 };
1405
1406 // --- Initialize bucket structure ---
1407 const size_t bucket_count = static_cast<size_t>(2 * n + 1);
1408 auto buckets = Array<DynList<Node *>>::create(bucket_count);
1409 long max_height = 0;
1410
1411 // Add active nodes to buckets
1412 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1413 {
1414 auto p = it.get_curr_ne();
1415 if (p != source and p != sink and hlpp_excess<Net>(p) > Flow_Type{0})
1416 {
1417 long h = hlpp_height<Net>(p);
1418 buckets(h).append(p);
1419 set_in_a_bucket(p, true);
1420 max_height = std::max(max_height, h);
1421 }
1422 }
1423
1424 // --- Main push/relabel loop ---
1425 while (max_height >= 0)
1426 {
1427 if (buckets(max_height).is_empty())
1428 {
1429 --max_height;
1430 continue;
1431 }
1432
1433 Node *u = buckets(max_height).remove_first();
1434 set_in_a_bucket(u, false);
1435
1436 // With a floating flow, an excess of u up to this is a residue of
1437 // rounding of its flows, and is not pushed
1438 Flow_Type residue{0};
1439 if constexpr (floating)
1440 residue =
1441 net_detail::node_residue(info(u)->in.value(), info(u)->out.value(), net.get_num_arcs(u));
1442
1443 // Push/Relabel
1444 bool pushed = false;
1445 long min_height = 2 * n;
1446
1447 for (typename Net::Node_Arc_Iterator it(u); it.has_curr() and hlpp_excess<Net>(u) > residue;
1448 it.next_ne())
1449 {
1450 Arc *arc = it.get_curr_ne();
1451 Node *v = net.get_connected_node(arc, u);
1452
1453 Flow_Type residual;
1454 const bool is_forward = (net.get_src_node(arc) == u);
1455 if (is_forward)
1456 residual = arc->cap - arc->flow;
1457 else
1458 residual = arc->flow;
1459
1460 if (residual > Flow_Type{0})
1461 {
1462 if (hlpp_height<Net>(u) == hlpp_height<Net>(v) + 1)
1463 {
1464 // Push, as much as the arc takes; v becomes active if
1465 // it was not
1466 [[maybe_unused]] const Flow_Type delta = std::min(hlpp_excess<Net>(u), residual);
1467 if constexpr (floating)
1468 {
1469 // The flow of the arc keeps u in balance, and the
1470 // excesses of u and v follow their flows: a small
1471 // push beside a large excess would be lost in it
1472 const Flow_Type before = arc->flow;
1473 net_detail::push_excess(arc, is_forward, info(u)->in, info(u)->out);
1474 if (is_forward)
1475 info(v)->in.replace(before, arc->flow);
1476 else
1477 info(v)->out.replace(before, arc->flow);
1478 hlpp_excess<Net>(u) = info(u)->in.minus(info(u)->out);
1479 }
1480 else if (is_forward)
1481 arc->flow += delta;
1482 else
1483 arc->flow -= delta;
1484
1485 const bool was_inactive = (v != source and v != sink and not in_a_bucket(v));
1486
1487 if constexpr (floating)
1488 hlpp_excess<Net>(v) = info(v)->in.minus(info(v)->out);
1489 else
1490 {
1491 hlpp_excess<Net>(u) -= delta;
1492 hlpp_excess<Net>(v) += delta;
1493 }
1494
1495 if (was_inactive and hlpp_excess<Net>(v) > Flow_Type{0})
1496 {
1497 buckets(hlpp_height<Net>(v)).append(v);
1498 set_in_a_bucket(v, true);
1499 max_height = std::max(max_height, hlpp_height<Net>(v));
1500 }
1501
1502 pushed = true;
1503 }
1504 else
1505 min_height = std::min(min_height, hlpp_height<Net>(v));
1506 }
1507 }
1508
1509 if (hlpp_excess<Net>(u) > residue)
1510 {
1511 if (not pushed)
1512 {
1513 if (min_height >= 2 * n)
1514 continue; // no admissible neighbour; drop the node
1515 hlpp_height<Net>(u) = min_height + 1;
1516 }
1517 buckets(hlpp_height<Net>(u)).append(u);
1518 set_in_a_bucket(u, true);
1519 max_height = std::max(max_height, hlpp_height<Net>(u));
1520 }
1521 }
1522
1523 // What a floating flow keeps as residues of rounding goes back
1524 net_detail::return_dust(net, source, sink);
1525
1526 return net.flow_value(); // with the flow that the network had
1527}
1528
1532template <FlowNetwork Net>
1534{
1549 typename Net::Flow_Type operator () (Net &net) const
1550 {
1551 return hlpp_maximum_flow(net);
1552 }
1553};
1554
1555//==============================================================================
1556// FLOW STATISTICS
1557//==============================================================================
1558
1562template <typename Flow_Type>
1564{
1568 size_t num_empty_arcs{0};
1570 double utilization{0.0};
1571
1582 [[nodiscard]] std::string to_string() const
1583 {
1584 std::ostringstream oss;
1585 oss << "=== Flow Statistics ===\n"
1586 << "Total flow: " << total_flow << "\n"
1587 << "Total capacity: " << total_capacity << "\n"
1588 << "Saturated arcs: " << num_saturated_arcs << "\n"
1589 << "Empty arcs: " << num_empty_arcs << "\n"
1590 << "Partial arcs: " << num_partial_arcs << "\n"
1591 << "Utilization: " << std::fixed << std::setprecision(2) << (utilization * 100) << "%\n";
1592 return oss.str();
1593 }
1594
1604 void print() const
1605 {
1606 std::cout << to_string();
1607 }
1608};
1609
1622template <class Net>
1624{
1625 using Flow_Type = typename Net::Flow_Type;
1626
1628
1629 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1630 {
1631 auto arc = it.get_curr();
1632 stats.total_capacity += arc->cap;
1633
1634 if (arc->flow == arc->cap)
1635 ++stats.num_saturated_arcs;
1636 else if (arc->flow == Flow_Type{0})
1637 ++stats.num_empty_arcs;
1638 else
1639 ++stats.num_partial_arcs;
1640 }
1641
1642 if (net.is_single_source())
1643 stats.total_flow = net.flow_value();
1644
1645 if (stats.total_capacity > Flow_Type{0})
1646 stats.utilization =
1647 static_cast<double>(stats.total_flow) / static_cast<double>(stats.total_capacity);
1648
1649 return stats;
1650}
1651} // namespace Aleph
1652
1653#endif // TPL_MAXFLOW_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
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double h
Definition btreepic.C:154
size_t size_t int32_t * out
Definition ca-c-api.h:120
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
RAII guard that saves and restores graph cookies.
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.
T & front()
Return a modifiable reference to the oldest item in the queue.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T & get_last()
Return the last item of the list.
Definition htlist.H:1529
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Generic key-value map implemented on top of a binary search tree.
bool contains(const Key &key) const noexcept(nothrow_search)
Same as has().
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.
constexpr bool is_empty() const noexcept
Definition htlist.H:434
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
RAII guards for graph node/arc cookies.
#define NODE_COOKIE(p)
Return the node cookie
double Flow_Type
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
bool fill_infinite_path(Net &net)
Definition tpl_net.H:2428
void push_excess(Arc *arc, bool forward, Flow_Sum< Flow_Type > &in, Flow_Sum< Flow_Type > &out) noexcept
Definition tpl_net.H:1370
Flow_Type node_residue(const Flow_Type &in, const Flow_Type &out, size_t arcs) noexcept
Definition tpl_net.H:1250
void subtract_flow(Arc *arc, const Flow_Type &slack) noexcept
Definition tpl_net.H:1283
Net::Flow_Type infinite_arc_preflow(const Net &net)
Definition tpl_net.H:2462
Main namespace for Aleph-w library functions.
Net::Flow_Type remaining_flow(typename Net::Node *src, typename Net::Arc *a) noexcept
Return the remaining flow of a as seen from src.
Definition tpl_net.H:283
FlowStatistics< typename Net::Flow_Type > compute_flow_statistics(const Net &net)
Compute statistics about the current flow in a network.
bool is_dinic_cookie_valid(typename Net::Node *p) noexcept
Check if a node's cookie is properly initialized for Dinic's algorithm.
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
long & hlpp_height(typename Net::Node *p) noexcept
Access the height label stored in the node's cookie.
bool build_level_graph(Net &net, typename Net::Node *source, typename Net::Node *sink)
Build level graph using BFS from source.
long & dinic_level(typename Net::Node *p) noexcept
Access the node level in Dinic's algorithm.
FlowDecomposition< Net > decompose_flow(const Net &net)
Decompose network flow into paths and cycles.
Net::Flow_Type capacity_scaling_maximum_flow(Net &net)
Compute maximum flow using capacity scaling.
bool & dinic_blocked(typename Net::Node *p) noexcept
Check if a node is blocked in Dinic's algorithm.
size_t & dinic_current_arc(typename Net::Node *p) noexcept
Access the current arc index in Dinic's algorithm.
Net::Flow_Type hlpp_maximum_flow(Net &net)
Compute maximum flow using Highest-Label Preflow-Push.
and
Check uniqueness with explicit hash + equality functors.
Net::Flow_Type & hlpp_excess(typename Net::Node *p) noexcept
Access the excess flow stored in the node's cookie.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
Net::Flow_Type dinic_blocking_flow(Net &net, typename Net::Node *source, typename Net::Node *sink)
Find all blocking flows using iterative DFS with current-arc optimization.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Functor wrapper for capacity scaling.
Net::Flow_Type operator()(Net &net) const
Invoke capacity scaling maximum flow algorithm on the given network.
Functor wrapper for flow decomposition.
FlowDecomposition< Net > operator()(const Net &net) const
Invoke flow decomposition on the given network.
Functor wrapper for Dinic's algorithm.
Net::Flow_Type operator()(Net &net) const
Invoke Dinic's maximum flow algorithm on the given network.
Level information for Dinic's algorithm.
size_t current_arc
Current arc index for current-arc optimization.
void reset() noexcept
bool blocked
Whether the node is blocked in the current phase.
long level
BFS level from source (-1 = unreachable)
Represents a flow cycle in the network.
typename Net::Flow_Type Flow_Type
Flow_Type flow
Flow on this cycle.
typename Net::Arc Arc
DynList< Node * > nodes
Nodes in the cycle.
DynList< Arc * > arcs
Arcs in the cycle.
typename Net::Node Node
Result of flow decomposition.
DynList< FlowCycle< Net > > cycles
Cycles (if any)
typename Net::Flow_Type Flow_Type
Flow_Type total_flow() const noexcept
Total flow (sum of path flows).
size_t num_paths() const noexcept
Number of paths.
size_t num_cycles() const noexcept
Number of cycles.
DynList< FlowPath< Net > > paths
Source-to-sink paths.
Represents a flow path from source to sink.
DynList< Node * > nodes
Nodes in the path.
bool is_empty() const noexcept
Check if a path is empty.
Flow_Type flow
Flow on this path.
typename Net::Flow_Type Flow_Type
size_t length() const noexcept
Get path length (number of arcs).
typename Net::Arc Arc
DynList< Arc * > arcs
Arcs in the path (source to sink order)
typename Net::Node Node
Statistics about a network flow.
std::string to_string() const
Format statistics as a string.
size_t num_saturated_arcs
Arcs with flow = capacity.
size_t num_empty_arcs
Arcs with flow = 0.
Flow_Type total_capacity
Sum of all capacities.
Flow_Type total_flow
Total flow value.
void print() const
Print statistics to standard output.
size_t num_partial_arcs
Arcs with 0 < flow < capacity.
double utilization
flow / capacity ratio
Functor wrapper for HLPP.
Net::Flow_Type operator()(Net &net) const
Invoke the Highest-Label Preflow-Push algorithm on the given network.
net_detail::Flow_Sum< Flow_Type > in
The flow into the node.
net_detail::Flow_Sum< Flow_Type > out
The flow out of the node.
Node info for HLPP algorithm.
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
Flow_Type get_out_flow(Node *node) const noexcept
Return total outgoing flow of node.
Definition tpl_net.H:399
static Flow_Type node_tolerance(const Flow_Type &in, const Flow_Type &out) noexcept
The tolerance of rounding of the flow of a node whose flows into and out of it are in and out.
Definition tpl_net.H:453
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
ArcT Arc
Arc type.
Definition tpl_net.H:322
Flow_Type get_in_flow(Node *node) const noexcept
Return total incoming flow of node.
Definition tpl_net.H:408
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
A sum of floating flows that keeps the error of its rounding, as hi + lo, by the error-free addition ...
Definition tpl_net.H:1305
Dynamic array container with automatic resizing.
Dynamic doubly linked list implementation.
Dynamic queue implementation based on linked lists.
Network flow graph structures.