Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_net.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
49#ifndef TPL_NET_H
50#define TPL_NET_H
51
52#include <algorithm>
53#include <cmath>
54#include <limits>
55#include <set>
56#include <tuple>
57#include <type_traits>
58#include <utility>
59#include <vector>
60
61#include <tpl_array.H>
62#include <tpl_sort_utils.H>
63#include <tpl_dynDlist.H>
64#include <tpl_dynListStack.H>
65#include <tpl_dynBinHeap.H>
66#include <tpl_dynSetTree.H>
67#include <tpl_dynSetHash.H>
68#include <tpl_random_queue.H>
69#include <tpl_graph_utils.H>
70#include <tpl_find_path.H>
71#include <graph-traverse.H>
72#include <ah-errors.H>
73#include <cookie_guard.H>
74
75namespace Aleph {
76using std::get;
77
85template <typename Arc_Info, typename Flow_Type>
86struct Net_Arc_Info : public Arc_Info
87{
90
93
95 Net_Arc_Info() = default;
96
98 Net_Arc_Info(const Arc_Info &info, Flow_Type __cap, Flow_Type __flow)
99 : Arc_Info(info), cap(__cap), flow(__flow)
100 {
101 // empty
102 }
103};
104
105namespace net_detail {
125[[deprecated("float as the type of a flow is deprecated: its precision is below what the "
126 "tolerances of the floating flows need; use double. It is rejected in 8.0.0")]]
127constexpr bool flow_type_ok(const float *) noexcept
128{
129 return true;
130}
131
137constexpr bool flow_type_ok(const void *) noexcept
138{
139 return true;
140}
141} // namespace net_detail
142
158template <typename Arc_Info, typename F_Type = double>
159struct Net_Arc : public Graph_Aarc<Arc_Info> // Arc type for flow networks.
160{
162
163 // A float flow warns that it is deprecated
164 static_assert(net_detail::flow_type_ok(static_cast<const F_Type *>(nullptr)));
165
166 using Flow_Type = F_Type;
167
170
173
175 bool check_arc() const noexcept
176 {
177 return flow >= 0 and flow <= cap;
178 }
179
181 Net_Arc(const Arc_Info &info) : Base(info)
182 { /* empty */
183 }
184
186 Net_Arc(const Net_Arc &arc) : Base(arc.arc_info), cap(arc.cap), flow(arc.flow)
187 {
188 // empty
189 }
190
193 { /* empty */
194 }
195
198 {
199 if (this == &arc)
200 return *this;
201
202 *static_cast<Base *>(this) = arc;
203 cap = arc.cap;
204 flow = arc.flow;
205
206 return *this;
207 }
208};
209
211template <class Net>
212bool is_residual(typename Net::Node *src, typename Net::Arc *a) noexcept
213{
214 assert(a->src_node == src or a->tgt_node == src);
215 return a->tgt_node == src;
216}
217
222template <class Net>
224{
225 typename Net::Node *p = nullptr;
226
227 void *cookie = nullptr;
228
230 void set_cookie(void *__cookie) noexcept
231 {
232 cookie = __cookie;
233 }
234
236 Net_Filt(typename Net::Node *s = nullptr) noexcept : p(s)
237 { /* empty */
238 }
239
241 bool operator () (typename Net::Arc *a) const noexcept
242 {
243 assert(p);
244 assert(a->src_node == p or a->tgt_node == p);
245 auto src = static_cast<typename Net::Node *>(a->src_node);
246 if (src == p)
247 return a->cap - a->flow > 0; // normal arc
248
249 assert(is_residual<Net>(p, a));
250 return a->flow > 0; // residual arc
251 }
252
254 bool operator () (const Net &, typename Net::Arc *arc) noexcept
255 {
256 return (*this)(arc);
257 }
258
260 typename Net::Node *get_node(typename Net::Arc *a) const noexcept
261 {
262 assert(p);
263 assert(a->src_node == p or a->tgt_node == p);
264 return static_cast<typename Net::Node *>(a->src_node == p ? a->tgt_node : a->src_node);
265 }
266};
267
268template <class Net>
270
272template <class Net, class Show_Arc = Dft_Show_Arc<Net>>
274
282template <class Net>
283typename Net::Flow_Type remaining_flow(typename Net::Node *src, typename Net::Arc *a) noexcept
284{
285 return is_residual<Net>(src, a) ? a->flow : a->cap - a->flow;
286}
287
289template <typename Node_Info = Empty_Class>
291
309template <class NodeT = Net_Node<Empty_Class>, class ArcT = Net_Arc<Empty_Class, double>>
310struct Net_Graph : public Array_Graph<NodeT, ArcT>
311{
313
315
316 using Base::Base;
317 using Base::insert_node;
318
319 using Graph = Base;
320
322 using Arc = ArcT;
323
325 using Node = NodeT;
326
328 using Flow_Type = typename Arc::Flow_Type;
329
331 using Node_Type = typename Node::Node_Type;
332
334 using Arc_Type = typename Arc::Arc_Type;
335
337
339 DynList<Arc *> out_arcs(Node *p) const noexcept
340 {
341 return Aleph::out_arcs<Net_Graph>(p);
342 }
343
345 DynList<Node *> out_nodes(Node *p) const noexcept
346 {
347 return out_pairs<Net_Graph>(p).template maps<Node *>([](const ArcPair<Net_Graph> &p)
348 {
349 return get<1>(p);
350 });
351 }
352
354 DynList<Arc *> in_arcs(Node *p) const noexcept
355 {
356 return Aleph::in_arcs<Net_Graph>(p);
357 }
358
360 DynList<Node *> in_nodes(Node *p) const noexcept
361 {
362 return in_pairs<Net_Graph>(p).template maps<Node *>([](const ArcPair<Net_Graph> &p)
363 {
364 return get<1>(p);
365 });
366 }
367
369 [[nodiscard]] Flow_Type get_in_cap(Node *node) const noexcept
370 {
372 for (_In_Iterator<Net_Graph> it(node); it.has_curr(); it.next_ne())
373 sum += it.get_curr()->cap;
374 return sum;
375 }
376
378 [[nodiscard]] Flow_Type get_out_cap(Node *node) const noexcept
379 {
381 for (_Out_Iterator<Net_Graph> it(node); it.has_curr(); it.next_ne())
382 sum += it.get_curr()->cap;
383 return sum;
384 }
385
387 size_t get_in_degree(Node *p) const noexcept
388 {
389 return this->in_degree(p);
390 }
391
393 size_t get_out_degree(Node *p) const noexcept
394 {
395 return this->out_degree(p);
396 }
397
399 [[nodiscard]] Flow_Type get_out_flow(Node *node) const noexcept
400 {
402 for (_Out_Iterator<Net_Graph> it(node); it.has_curr(); it.next_ne())
403 sum += it.get_curr()->flow;
404 return sum;
405 }
406
408 [[nodiscard]] Flow_Type get_in_flow(Node *node) const noexcept
409 {
411 for (_In_Iterator<Net_Graph> it(node); it.has_curr(); it.next_ne())
412 sum += it.get_curr()->flow;
413 return sum;
414 }
415
417 bool is_source(Node *node) const noexcept
418 {
419 return src_nodes.contains(node);
420 }
421
423 bool is_sink(Node *node) const noexcept
424 {
425 return sink_nodes.contains(node);
426 }
427
429 [[nodiscard]] constexpr bool is_single_source() const noexcept
430 {
431 return src_nodes.size() == 1;
432 }
433
435 [[nodiscard]] constexpr bool is_single_sink() const noexcept
436 {
437 return sink_nodes.size() == 1;
438 }
439
441 bool is_connected(Node *p) const noexcept
442 {
443 return get_in_degree(p) != 0 or get_out_degree(p) != 0;
444 }
445
453 static Flow_Type node_tolerance(const Flow_Type &in, const Flow_Type &out) noexcept
454 {
455 if constexpr (std::is_floating_point_v<Flow_Type>)
456 return std::max(std::abs(in), std::abs(out)) * 1e-9;
457 else
458 return Flow_Type{0};
459 }
460
468 bool check_node(Node *node) const noexcept
469 {
470 if (not is_connected(node))
471 return false;
472
473 auto out_flow = get_out_flow(node);
474 auto in_flow = get_in_flow(node);
475
476 // Use tolerance for floating-point comparison. Equal flows balance,
477 // also infinite ones, whose difference, inf - inf, is NaN
478 const auto eps = check_tolerance(in_flow, out_flow);
479 const auto nearly_zero = [eps](auto x)
480 {
481 return std::abs(x) <= eps;
482 };
483 const auto nearly_equal = [eps](auto a, auto b)
484 {
485 return a == b or std::abs(a - b) <= eps;
486 };
487
488 if (is_sink(node))
489 return nearly_zero(out_flow) and in_flow >= -eps;
490
491 if (is_source(node))
492 return nearly_zero(in_flow) and out_flow >= -eps;
493
494 return nearly_equal(out_flow, in_flow);
495 }
496
497private:
500
501 // The super source and the super sink that make_super_source() and
502 // make_super_sink() inserted, if any, which unmake_super_source() and
503 // unmake_super_sink() remove
506
507 // The tolerance of check_node() for a node whose flows into and out of
508 // it are in and out: node_tolerance(), but zero if one of them is
509 // infinite. That of an infinite flow, infinite too, took any imbalance,
510 // as an infinite flow into a node that sends 2.5; with zero, the flows
511 // balance only if they are equal, as the infinite flows into and out
512 // of a node of a path of arcs of infinite capacity
513 static Flow_Type check_tolerance(const Flow_Type &in, const Flow_Type &out) noexcept
514 {
515 if constexpr (std::is_floating_point_v<Flow_Type>)
516 if (std::isinf(in) or std::isinf(out))
517 return Flow_Type{0};
518 return node_tolerance(in, out);
519 }
520
521 // The sum of the tolerances of check_node() of every node: as each
522 // keeps its flow but for its own, the flow out of the sources and that
523 // into the sinks differ, at most, by it. O(V + E)
525 {
526 Flow_Type sum{0};
527 for (Node_Iterator<Net_Graph> it(*this); it.has_curr(); it.next_ne())
528 sum += check_tolerance(get_in_flow(it.get_curr()), get_out_flow(it.get_curr()));
529 return sum;
530 }
531
532 // Whether the flow out of the sources and that into the sinks are the
533 // same: exactly, or, for a floating type, but for rounding: within the
534 // tolerance of check_node() of the totals, or within the sum of those
535 // of the nodes, which is computed only if the first does not hold.
536 // Equal totals are the same, also infinite ones, whose difference is
537 // NaN; an infinite total and a finite one are not
538 bool same_totals(const Flow_Type &out, const Flow_Type &in) const
539 {
540 if constexpr (std::is_floating_point_v<Flow_Type>)
541 {
542 if (out == in)
543 return true;
544 const Flow_Type diff = std::abs(out - in);
545 return diff <= check_tolerance(out, in) or diff <= nodes_tolerance();
546 }
547 else
548 return out == in;
549 }
550
553 {
555 for (auto it = src_nodes.get_it(); it.has_curr(); it.next_ne())
556 sum += get_out_flow(it.get_curr());
557 return sum;
558 }
559
562 {
564 for (auto it = sink_nodes.get_it(); it.has_curr(); it.next_ne())
565 sum += get_in_flow(it.get_curr());
566 return sum;
567 }
568
571 {
572 try
573 {
574 src_nodes.insert(p);
576 }
577 catch (...)
578 {
579 src_nodes.remove(p);
582 throw;
583 }
584 return p;
585 }
586
587public:
589 const DynSetTree<Node *> &get_src_nodes() const noexcept
590 {
591 return src_nodes;
592 }
593
595 const DynSetTree<Node *> &get_sink_nodes() const noexcept
596 {
597 return sink_nodes;
598 }
599
600public:
604 {
605 if (src_nodes.size() == 1)
606 return;
607
608 ah_domain_error_if(src_nodes.size() == 0) << "network has no source nodes (it has cycles)";
609
610 DynList<Node *> sources;
611 for (auto it = src_nodes.get_it(); it.has_curr(); it.next_ne())
612 sources.append(it.get_curr());
613
614 Node *super_source = insert_node();
615 try
616 {
617 for (auto it = sources.get_it(); it.has_curr(); it.next_ne())
618 insert_arc(super_source, it.get_curr(), get_out_cap(it.get_curr()));
619 }
620 catch (...)
621 {
622 remove_node(super_source); // with the arcs that it got
623 throw;
624 }
625
626 super_source_node = super_source;
627 with_super_source = true;
628 }
629
641 {
642 if (not with_super_source)
643 return;
644
645 if (super_source_node == nullptr) // the flag was set by hand
646 {
647 with_super_source = false;
648 return;
649 }
650
651 remove_node(super_source_node); // which clears it and the flag
652 }
653
657 {
658 if (sink_nodes.size() == 1)
659 return;
660
661 ah_domain_error_if(sink_nodes.size() == 0) << "network has no sink nodes (it has cycles)";
662
663 DynList<Node *> sinks;
664 for (auto it = sink_nodes.get_it(); it.has_curr(); it.next_ne())
665 sinks.append(it.get_curr());
666
667 Node *super_sink = insert_node();
668 try
669 {
670 for (auto it = sinks.get_it(); it.has_curr(); it.next_ne())
671 insert_arc(it.get_curr(), super_sink, get_in_cap(it.get_curr()));
672 }
673 catch (...)
674 {
675 remove_node(super_sink); // with the arcs that it got
676 throw;
677 }
678 super_sink_node = super_sink;
679 with_super_sink = true;
680 }
681
689 {
690 if (not with_super_sink)
691 return;
692
693 if (super_sink_node == nullptr) // the flag was set by hand
694 {
695 with_super_sink = false;
696 return;
697 }
698
699 remove_node(super_sink_node); // which clears it and the flag
700 }
701
710 {
711 const bool had_super_source = with_super_source;
713 try
714 {
716 }
717 catch (...)
718 {
719 if (not had_super_source)
721 throw;
722 }
723 }
724
731
734 {
735 return src_nodes.get_item();
736 }
737
739 Node *get_sink() const
740 {
741 return sink_nodes.get_item();
742 }
743
750 Node *insert_node(const Node_Type &node_info)
751 {
752 return register_node(Graph::insert_node(node_info));
753 }
754
760
763 {
764 return register_node(Graph::insert_node(std::move(info)));
765 }
766
768 template <typename... Args>
769 Node *emplace_node(Args &&...args)
770 {
771 return insert_node(Node_Type(std::forward<Args>(args)...));
772 }
773
781 Node *insert_node(Node *p) override
782 {
784 return register_node(p);
785 }
786
799 Arc *insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &flow,
800 const typename Arc::Arc_Type &arc_info = Arc_Type())
801 {
802 // As Net_Arc::check_arc(), before the arc enters the network
803 ah_overflow_error_if(not (flow >= 0 and flow <= cap)) << "flow is greater than capacity";
804
805 auto arc = Graph::insert_arc(src_node, tgt_node, arc_info); // base insertion
806
807 src_nodes.remove(tgt_node); // update sources/sinks
808 sink_nodes.remove(src_node);
809
810 arc->cap = cap;
811 arc->flow = flow;
812
813 return arc;
814 }
815
816 template <typename... Args>
818 Arc *emplace_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &flow,
819 Args &&...args)
820 {
821 return insert_arc(src_node, tgt_node, cap, flow, Arc_Type(std::forward<Args>(args)...));
822 }
823
833 {
835
836 auto src = this->get_src_node(arc);
837 auto tgt = this->get_tgt_node(arc);
838
839 src_nodes.remove(tgt); // target is no longer a source
840 sink_nodes.remove(src); // source is no longer a sink
841
842 return arc;
843 }
844
846 Arc *insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap)
847 {
848 return insert_arc(src_node, tgt_node, cap, 0, Arc_Type());
849 }
850
858 Arc *insert_arc(Node *src_node, Node *tgt_node, const Arc_Type &arc_info = Arc_Type())
859 requires(not std::is_same_v<Arc_Type, Flow_Type> and not std::is_arithmetic_v<Arc_Type>)
860 {
861 return insert_arc(src_node, tgt_node, 0, 0, arc_info);
862 }
863
871 Arc *insert_arc(Node *src_node, Node *tgt_node)
872 requires(std::is_same_v<Arc_Type, Flow_Type> or std::is_arithmetic_v<Arc_Type>)
873 {
874 return insert_arc(src_node, tgt_node, 0, 0, Arc_Type());
875 }
876
877private:
878 // Puts in the sets of sources and of sinks the nodes that arc leaves as
879 // one when it goes. It is done before the arc goes, so that if a set
880 // cannot take a node, the network is as it was.
882 {
883 auto src = this->get_src_node(arc);
884 auto tgt = this->get_tgt_node(arc);
885 const bool new_source =
886 get_in_degree(tgt) == 1 and src_nodes.insert(tgt) != nullptr; // target becomes a source
887 try
888 {
889 if (get_out_degree(src) == 1)
890 sink_nodes.insert(src); // source becomes a sink
891 }
892 catch (...)
893 {
894 if (new_source)
895 src_nodes.remove(tgt);
896 throw;
897 }
898 }
899
900public:
906 void remove_arc(Arc *arc) override
907 {
909 Graph::remove_arc(arc); // base removal
910 }
911
921 virtual void disconnect_arc(Arc *arc)
922 {
924 Graph::disconnect_arc(arc); // base disconnection
925 }
926
933 void remove_node(Node *p) override
934 {
935 const bool super_source = p == super_source_node;
936 const bool super_sink = p == super_sink_node;
937 Graph::remove_node(p); // base removal
938 src_nodes.remove(p);
940 if (super_source) // the network has no super source any more
941 {
942 super_source_node = nullptr;
943 with_super_source = false;
944 }
945 if (super_sink)
946 {
947 super_sink_node = nullptr;
948 with_super_sink = false;
949 }
950 }
951
954 : Array_Graph<NodeT, ArcT>::Array_Graph(),
955 Infinity(std::numeric_limits<typename Arc::Flow_Type>::max()),
957 {
958 copy_graph(*this, net, false); // copy without mapping
959
960 using Pair = std::pair<typename Net_Graph::Arc *, typename Net_Graph::Arc *>;
961 zip(this->arcs(), net.arcs())
962 .for_each([](const Pair &p)
963 {
964 auto atgt = p.first;
965 auto asrc = p.second;
966 atgt->cap = asrc->cap;
967 atgt->flow = asrc->flow;
968 });
969
970 // The copy has the nodes of net in their order: the super nodes are
971 // those at their places
972 if (net.super_source_node != nullptr or net.super_sink_node != nullptr)
973 {
974 Node_Iterator<Net_Graph> jt(*this);
975 for (Node_Iterator<Net_Graph> it(net); it.has_curr(); it.next_ne(), jt.next_ne())
976 {
977 if (it.get_curr() == net.super_source_node)
979 if (it.get_curr() == net.super_sink_node)
981 }
982 }
983 }
984
985protected:
995 void swap_contents(Net_Graph &other) noexcept
996 {
997 Graph::common_swap(other); // swap num_nodes, num_arcs, digraph, cookie
998 Graph::get_node_dlink().swap(other.get_node_dlink());
999 Graph::get_arc_dlink().swap(other.get_arc_dlink());
1000 src_nodes.swap(other.src_nodes);
1001 sink_nodes.swap(other.sink_nodes);
1002 std::swap(Infinity, other.Infinity);
1003 std::swap(with_super_source, other.with_super_source);
1004 std::swap(with_super_sink, other.with_super_sink);
1005 std::swap(super_source_node, other.super_source_node);
1006 std::swap(super_sink_node, other.super_sink_node);
1007 }
1008
1023 virtual void swapped() noexcept {}
1024
1025public:
1032 void swap(Net_Graph &other) noexcept
1033 {
1034 if (this == &other)
1035 return; // nothing is exchanged
1036 swap_contents(other);
1037 swapped();
1038 other.swapped();
1039 }
1040
1042 Net_Graph(Net_Graph &&other) noexcept
1043 : Infinity(std::numeric_limits<typename Arc::Flow_Type>::max()), with_super_source(false),
1044 with_super_sink(false)
1045 {
1046 swap_contents(other);
1047 other.swapped(); // nothing is kept for this one yet
1048 }
1049
1052 {
1053 if (this != &other)
1054 swap(other);
1055 return *this;
1056 }
1057
1060 {
1061 if (this == &net)
1062 return *this;
1063
1064 Net_Graph tmp(net); // copy construct
1065 tmp.get_cookie() = this->get_cookie(); // the network keeps its cookie
1066 swap(tmp); // swap with copy
1067 return *this;
1068 }
1069
1071 void set_cap(Arc *arc, const Flow_Type &cap)
1072 {
1073 ah_out_of_range_error_if(cap < arc->flow) << "capacity value is smaller than flow";
1074
1075 arc->cap = cap;
1076 }
1077
1079 void set_flow(Arc *arc, const Flow_Type &flow)
1080 {
1081 ah_out_of_range_error_if(flow > arc->cap) << "flow value is greater than capacity";
1082
1083 arc->flow = flow;
1084 }
1085
1087 const Flow_Type &get_flow(Arc *arc) const noexcept
1088 {
1089 return arc->flow;
1090 }
1091
1093 const Flow_Type &get_cap(Arc *arc) const noexcept
1094 {
1095 return arc->cap;
1096 }
1097
1099 void reset()
1100 {
1101 for (Arc_Iterator<Net_Graph> it(*this); it.has_curr(); it.next_ne())
1102 it.get_curr()->flow = 0;
1103 }
1104
1116 bool check_network() const
1117 {
1119 return false;
1120
1121 const bool flow_balanced = same_totals(total_source_out_flow(), total_sink_in_flow());
1122
1123 return this->nodes().all(
1124 [this](Node *p)
1125 {
1126 return check_node(p);
1127 }) and
1128 this->arcs().all(
1129 [](Arc *a)
1130 {
1131 return a->check_arc();
1132 }) and
1133 flow_balanced;
1134 }
1135
1140 {
1142 << "network has no source or sink nodes";
1143
1144 const auto total_out = total_source_out_flow();
1145 assert(same_totals(total_out, total_sink_in_flow()));
1146 return total_out;
1147 }
1148
1151
1154
1157 : Infinity(std::numeric_limits<typename Arc::Flow_Type>::max()), with_super_source(false),
1158 with_super_sink(false)
1159 { /* empty */
1160 }
1161
1163 friend std::ostream &operator << (std::ostream &s, const Path<Net_Graph> &path)
1164 {
1165 if (path.is_empty())
1166 return s << "Path is Empty";
1167
1168 const Net_Graph &net = path.get_graph();
1169 typename Path<Net_Graph>::Iterator it(path);
1170 s << it.get_current_node()->get_info();
1171 for (; it.has_current_arc(); it.next_ne())
1172 {
1173 typename Net_Graph::Arc *a = it.get_current_arc_ne();
1174 s << "(" << a->cap << "," << a->flow << ")"
1175 << net.get_connected_node(a, it.get_current_node_ne())->get_info();
1176 }
1177 return s;
1178 }
1179};
1180
1187template <class Net>
1188using Parc = std::tuple<typename Net::Arc *, bool>; // second field marks forward.
1189
1197template <class Net>
1198using SemiPath = std::tuple<bool, typename Net::Flow_Type, DynList<Parc<Net>>>;
1199
1201template <class Net>
1202inline void print(const DynList<Parc<Net>> &sp)
1203{
1204 if (sp.is_empty())
1205 {
1206 std::cout << "Semi path is Empty";
1207 return;
1208 }
1209
1210 for (auto it = sp.get_it(); it.has_curr(); it.next_ne())
1211 {
1212 const Parc<Net> &pa = it.get_curr();
1213 auto a = get<0>(pa);
1214 auto s = static_cast<typename Net::Node *>(a->src_node);
1215 auto t = static_cast<typename Net::Node *>(a->tgt_node);
1216 std::cout << s->get_info() << "(" << a->flow << "," << a->cap << ")" << t->get_info() << " "
1217 << (get<1>(pa) ? "Normal" : "Reduced") << '\n';
1218 }
1219}
1220
1221namespace net_detail {
1222// Adds slack to the flow of arc. A floating slack that covers what the
1223// arc has left takes the flow to the capacity, exactly, so that the arc
1224// that bounds a path is saturated, as it would be without rounding,
1225// and no arc goes beyond it.
1226template <class Arc, typename Flow_Type>
1227inline void add_flow(Arc *arc, const Flow_Type &slack) noexcept
1228{
1229 if constexpr (std::is_floating_point_v<Flow_Type>)
1230 if (arc->cap - arc->flow <= slack)
1231 {
1232 arc->flow = arc->cap;
1233 return;
1234 }
1235 arc->flow += slack;
1236}
1237
1238// The largest excess of a node of degree arcs, whose flows into and
1239// out of it are in and out, that is a residue of rounding, and not flow
1240// to push: for a floating flow, the errors that its sums of flows, and
1241// the pushes of a discharge, may make, an epsilon of the larger of in
1242// and out by each of its arcs and two more; zero for an integer flow. A
1243// push-relabel algorithm that pushed it could move it around forever,
1244// as no arc may take it. The scale is the node's own flows, not the
1245// capacities of the network nor those of the node: a node may receive a
1246// small flow through a small arc beside a large one, and that flow is
1247// not a residue; nor is 21 beside 1e15, though 256 epsilons of 1e15
1248// are 57.
1249template <typename Flow_Type>
1250inline Flow_Type node_residue(const Flow_Type &in, const Flow_Type &out, size_t arcs) noexcept
1251{
1252 if constexpr (std::is_floating_point_v<Flow_Type>)
1253 return std::numeric_limits<Flow_Type>::epsilon() * Flow_Type(arcs + 2) * std::max(in, out);
1254 else
1255 {
1256 (void) in;
1257 (void) out;
1258 (void) arcs;
1259 return Flow_Type{0};
1260 }
1261}
1262
1263// Whether node p of net, which a preflow algorithm has just pushed
1264// flow into, does not send more than it receives, beyond the
1265// tolerance of check_node(); for an integer flow, whether it has an
1266// excess
1267template <class Net>
1268bool not_short(const Net &net, typename Net::Node *p)
1269{
1270 const auto in = net.get_in_flow(p), out = net.get_out_flow(p);
1271 if constexpr (std::is_floating_point_v<typename Net::Flow_Type>)
1272 return in - out >= -Net::node_tolerance(in, out);
1273 else
1274 return in > out;
1275}
1276
1277// Subtracts slack from the flow of arc, along an augmenting path. A
1278// floating flow that is left next to zero, or below it, relative to
1279// the numbers of the subtraction, is zero, as the slack of the path
1280// was computed on another arc, or the flow added up rounding errors.
1281// The preflows do not take it: they push with push_excess().
1282template <class Arc, typename Flow_Type>
1283inline void subtract_flow(Arc *arc, const Flow_Type &slack) noexcept
1284{
1285 if constexpr (std::is_floating_point_v<Flow_Type>)
1286 {
1287 const Flow_Type before = arc->flow;
1288 arc->flow -= slack;
1289 if (arc->flow <= 256 * std::numeric_limits<Flow_Type>::epsilon() * std::max(before, slack))
1290 arc->flow = 0;
1291 }
1292 else
1293 arc->flow -= slack;
1294}
1295
1303template <typename Flow_Type>
1305{
1306#if defined(__FAST_MATH__) || defined(_M_FP_FAST)
1307 static_assert(not std::is_floating_point_v<Flow_Type>,
1308 "The floating flows of tpl_net.H need strict floating "
1309 "arithmetic, which -ffast-math and /fp:fast are not");
1310#endif
1311
1314
1316 void add(const Flow_Type &x) noexcept
1317 {
1318 const Flow_Type s = hi + x;
1319 const Flow_Type b = s - hi;
1320 lo += (hi - (s - b)) + (x - b);
1321 hi = s;
1322 }
1323
1325 void replace(const Flow_Type &from, const Flow_Type &to) noexcept
1326 {
1327 add(-from);
1328 add(to);
1329 }
1330
1332 [[nodiscard]] Flow_Type value() const noexcept
1333 {
1334 return hi + lo;
1335 }
1336
1338 [[nodiscard]] Flow_Type minus(const Flow_Sum &other) const noexcept
1339 {
1340 Flow_Sum d = *this;
1341 d.add(-other.hi);
1342 return d.hi + (d.lo - other.lo);
1343 }
1344};
1345
1346// Sums into in and out the flows into and out of node p of net
1347template <class Net>
1350{
1351 for (typename Net::Node_Arc_Iterator it(p); it.has_curr(); it.next_ne())
1352 {
1353 auto arc = it.get_curr_ne();
1354 if (net.get_src_node(arc) == p)
1355 out.add(arc->flow);
1356 if (net.get_tgt_node(arc) == p)
1357 in.add(arc->flow);
1358 }
1359}
1360
1361// Pushes the excess of a node whose flows into and out of it are in
1362// and out along arc, forward or back, as much as the arc takes, for a
1363// floating flow: the flow of the arc becomes what keeps the node in
1364// balance, in - (out - flow) forward and out - (in - flow) back, or the
1365// capacity, or zero, if that is beyond them. The sums keep what their
1366// rounding loses, so that a small flow beside a large one is not lost,
1367// as 0.05 left by the return of 1e15. Updates in and out by what the
1368// arc took.
1369template <class Arc, typename Flow_Type>
1370inline void push_excess(Arc *arc, bool forward, Flow_Sum<Flow_Type> &in,
1371 Flow_Sum<Flow_Type> &out) noexcept
1372{
1373 const Flow_Type before = arc->flow;
1374 Flow_Sum<Flow_Type> &with = forward ? out : in; // the sum that has arc
1375 const Flow_Sum<Flow_Type> &other = forward ? in : out;
1376 with.add(-before);
1377 const Flow_Type balanced = other.minus(with);
1378 if (forward)
1379 arc->flow = balanced >= arc->cap ? arc->cap : balanced;
1380 else
1381 arc->flow = balanced <= Flow_Type{0} ? Flow_Type{0} : balanced;
1382 with.add(arc->flow);
1383}
1384
1409template <class Net>
1410void return_dust(Net &net, typename Net::Node *source, typename Net::Node *sink)
1411{
1412 using Flow_Type = typename Net::Flow_Type;
1413 if constexpr (std::is_floating_point_v<Flow_Type>)
1414 {
1415 using Node = typename Net::Node;
1416 using Arc = typename Net::Arc;
1417
1418 // Nothing to do, and nothing to allocate, if every node but the
1419 // ends keeps its flow within the tolerance of check_node(), as it
1420 // sums the flows, where it stays, and the totals agree, or both
1421 // carry flow: a pass over the arcs, the least that the maximum
1422 // flows of a floating flow pay for their residues
1423 {
1424 bool within = true;
1425 Flow_Type sent{0}, received{0};
1426 for (Node_Iterator<Net> it(net); within and it.has_curr(); it.next_ne())
1427 {
1428 Node *p = it.get_curr_ne();
1429 Flow_Type in{0}, out{0};
1430 for (typename Net::Node_Arc_Iterator a(p); a.has_curr(); a.next_ne())
1431 {
1432 Arc *arc = a.get_curr_ne();
1433 if (net.get_src_node(arc) == p)
1434 out += arc->flow;
1435 if (net.get_tgt_node(arc) == p)
1436 in += arc->flow;
1437 }
1438 if (p == source)
1439 sent = out - in;
1440 else if (p == sink)
1441 received = in - out;
1442 else
1443 within = std::abs(in - out) <= Net::node_tolerance(in, out);
1444 }
1445 if (within and (sent == received or (sent != Flow_Type{0} and received != Flow_Type{0})))
1446 return;
1447 }
1448
1449 struct Info
1450 {
1451 Flow_Sum<Flow_Type> in; // which keep what their rounding loses
1453 long from_source = -1; // depth from the source, by arcs with flow
1454 long to_sink = -1; // depth to the sink, by arcs with flow
1455 Arc *parent = nullptr; // by which a search reached it
1456 size_t stamp = 0; // the last search that reached it
1457 };
1458 // The storage first, so that it outlives the saver of cookies,
1459 // and all of it before any flow moves
1460 auto info = Array<Info>::create(net.vsize());
1461 Array<Node *> order, queue; // of the searches
1462 order.reserve(net.vsize());
1463 queue.reserve(net.vsize());
1464 Array<Arc *> end_arcs; // of the source or the sink
1465 end_arcs.reserve(std::max(net.get_num_arcs(source), net.get_num_arcs(sink)));
1466 Cookie_Saver<Net> saver(net, true, false);
1467 {
1468 size_t i = 0;
1469 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne(), ++i)
1470 NODE_COOKIE(it.get_curr_ne()) = &info(i);
1471 }
1472 auto at = [](Node *p) -> Info &
1473 {
1474 return *static_cast<Info *>(NODE_COOKIE(p));
1475 };
1476 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
1477 {
1478 Arc *a = it.get_curr_ne();
1479 at(net.get_src_node(a)).out.add(a->flow);
1480 at(net.get_tgt_node(a)).in.add(a->flow);
1481 }
1482
1483 // Lowers the flow of a by d, at most its flow
1484 auto lower = [&](Arc *a, const Flow_Type &d)
1485 {
1486 const Flow_Type before = a->flow;
1487 a->flow = d >= before ? Flow_Type{0} : before - d;
1488 at(net.get_src_node(a)).out.replace(before, a->flow);
1489 at(net.get_tgt_node(a)).in.replace(before, a->flow);
1490 };
1491 auto between = [source, sink](Node *p)
1492 {
1493 return p != source and p != sink;
1494 };
1495 auto excess = [&](Node *p)
1496 {
1497 return at(p).in.minus(at(p).out);
1498 };
1499
1500 // The nodes by depth from start, along arcs with flow, forward if
1501 // forward, else backward; none goes on from stop
1502 auto search = [&](Node *start, Node *stop, bool forward, long Info::*depth)
1503 {
1504 order.clear();
1505 at(start).*depth = 0;
1506 order.append(start);
1507 for (size_t k = 0; k < order.size(); ++k)
1508 {
1509 Node *u = order(k);
1510 if (u == stop)
1511 continue;
1512 for (typename Net::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
1513 {
1514 Arc *a = it.get_curr_ne();
1515 Node *from = forward ? net.get_src_node(a) : net.get_tgt_node(a);
1516 Node *v = forward ? net.get_tgt_node(a) : net.get_src_node(a);
1517 if (from == u and a->flow > Flow_Type{0} and at(v).*depth < 0)
1518 {
1519 at(v).*depth = at(u).*depth + 1;
1520 order.append(v);
1521 }
1522 }
1523 }
1524 };
1525
1526 // Whether p keeps or lacks more than the tolerance of check_node()
1527 // of its flows: what it keeps or lacks within it stays, as the
1528 // rounding of their sums
1529 auto tolerance_of = [&](Node *p)
1530 {
1531 return Net::node_tolerance(at(p).in.value(), at(p).out.value());
1532 };
1533 auto off = [&](Node *p)
1534 {
1535 return std::abs(excess(p)) > tolerance_of(p);
1536 };
1537
1538 // What each node keeps beyond its tolerance goes back, the
1539 // deepest first, along arcs from nodes nearer to the source, which
1540 // come later
1541 search(source, sink, true, &Info::from_source);
1542 for (size_t k = order.size(); k-- > 1;)
1543 if (Node *v = order(k); between(v) and off(v))
1544 for (typename Net::Node_Arc_Iterator it(v); it.has_curr() and excess(v) > Flow_Type{0};
1545 it.next_ne())
1546 {
1547 Arc *a = it.get_curr_ne();
1548 Node *u = net.get_src_node(a);
1549 if (net.get_tgt_node(a) == v and u != v and a->flow > Flow_Type{0} and
1550 at(u).from_source >= 0 and at(u).from_source < at(v).from_source)
1551 lower(a, excess(v));
1552 }
1553
1554 // What each node lacks beyond it goes forward likewise, toward
1555 // the sink
1556 search(sink, source, false, &Info::to_sink);
1557 for (size_t k = order.size(); k-- > 1;)
1558 if (Node *v = order(k); between(v) and off(v))
1559 for (typename Net::Node_Arc_Iterator it(v); it.has_curr() and excess(v) < Flow_Type{0};
1560 it.next_ne())
1561 {
1562 Arc *a = it.get_curr_ne();
1563 Node *w = net.get_tgt_node(a);
1564 if (net.get_src_node(a) == v and w != v and a->flow > Flow_Type{0} and
1565 at(w).to_sink >= 0 and at(w).to_sink < at(v).to_sink)
1566 lower(a, -excess(v));
1567 }
1568
1569 // What is left beyond the tolerance of check_node() of its node
1570 // goes, an excess backward and a lack forward, along a shortest
1571 // path of arcs with flow, to the first node that takes it: the
1572 // source or the sink, a node with the opposite beyond its own
1573 // tolerance, a node of flows large enough to take it within their
1574 // tolerance, or else the first node with some of the opposite. So
1575 // an island of arcs with flow apart from both ends, and a path of
1576 // dust from the source into a circulation, in which rounding hid
1577 // it, go, and no move goes around a cycle. What a node keeps or
1578 // lacks within its tolerance stays: it is the rounding of the sums
1579 // of its flows. Each search takes a path to zero at one of its
1580 // arcs, settles its node, or settles the node that takes it; the
1581 // searches are bounded all the same
1582 size_t stamp = 0;
1583 auto settle = [&]
1584 {
1585 size_t budget = net.vsize() + net.esize();
1586 for (Node_Iterator<Net> nt(net); nt.has_curr() and budget > 0; nt.next_ne())
1587 for (Node *v = nt.get_curr_ne(); between(v) and off(v) and budget > 0; --budget)
1588 {
1589 const bool keeps = excess(v) > Flow_Type{0};
1590 const Flow_Type d = std::abs(excess(v));
1591 auto opposite = [&](Node *w)
1592 {
1593 const Flow_Type e = excess(w);
1594 return between(w) and (keeps ? e < Flow_Type{0} : e > Flow_Type{0});
1595 };
1596 auto takes_all = [&](Node *w)
1597 {
1598 return not between(w) or std::abs(excess(w)) + d <= tolerance_of(w);
1599 };
1600 // A search from v, backward if it keeps, else forward,
1601 // to the first node that takes all, or has the opposite
1602 // beyond its tolerance, or else to the first that has
1603 // some of the opposite, which, as the flow decomposes
1604 // into paths and cycles, a search finds
1605 ++stamp;
1606 at(v).stamp = stamp;
1607 queue.clear();
1608 queue.append(v);
1609 Node *w = nullptr, *some = nullptr;
1610 for (size_t k = 0; k < queue.size() and w == nullptr; ++k)
1611 for (typename Net::Node_Arc_Iterator it(queue(k)); it.has_curr(); it.next_ne())
1612 {
1613 Arc *a = it.get_curr_ne();
1614 Node *near = keeps ? net.get_tgt_node(a) : net.get_src_node(a);
1615 Node *x = keeps ? net.get_src_node(a) : net.get_tgt_node(a);
1616 if (near != queue(k) or x == near or not (a->flow > Flow_Type{0}) or
1617 at(x).stamp == stamp)
1618 continue;
1619 at(x).stamp = stamp;
1620 at(x).parent = a;
1621 if (takes_all(x) or (opposite(x) and off(x)))
1622 {
1623 w = x;
1624 break;
1625 }
1626 if (some == nullptr and opposite(x))
1627 some = x;
1628 queue.append(x);
1629 }
1630 if (w == nullptr)
1631 w = some;
1632 if (w == nullptr)
1633 break; // nothing takes it
1634 auto next = [&](Node *x)
1635 {
1636 Arc *a = at(x).parent;
1637 return keeps ? net.get_tgt_node(a) : net.get_src_node(a);
1638 };
1639 Flow_Type m = d; // what goes: at most the flow of the path
1640 for (Node *x = w; x != v; x = next(x))
1641 m = std::min(m, at(x).parent->flow);
1642 if (not takes_all(w)) // only what it has of the opposite
1643 m = std::min(m, std::abs(excess(w)));
1644 for (Node *x = w; x != v;)
1645 {
1646 Arc *a = at(x).parent;
1647 x = next(x);
1648 lower(a, m);
1649 }
1650 }
1651 };
1652 settle();
1653
1654 // When nothing reaches the sink, what still leaves the source, or
1655 // the other way, which the rounding of the sums of the nodes
1656 // between them hides, is dust too, if it is within the tolerances
1657 // of those nodes: the arcs of the source, or of the sink, with the
1658 // least flow lose it, so that a maximum flow of 0 gives 0. A
1659 // difference of the totals when both carry flow is what rounding
1660 // hides between them, and it stays, within the tolerance that
1661 // check_network() takes
1662 Flow_Type tolerance{0};
1663 for (const Info &x : info)
1664 tolerance += Net::node_tolerance(x.in.value(), x.out.value());
1665 const Flow_Type sent = at(source).out.minus(at(source).in);
1666 const Flow_Type received = at(sink).in.minus(at(sink).out);
1667 const Flow_Type apart = sent - received;
1668 if ((sent == Flow_Type{0} or received == Flow_Type{0}) and apart != Flow_Type{0} and
1669 std::abs(apart) <= tolerance)
1670 {
1671 Node *end = apart > Flow_Type{0} ? source : sink;
1672 for (typename Net::Node_Arc_Iterator it(end); it.has_curr(); it.next_ne())
1673 if (Arc *a = it.get_curr_ne(); a->flow > Flow_Type{0} and
1674 (end == source ? net.get_src_node(a) : net.get_tgt_node(a)) == end and
1675 net.get_src_node(a) != net.get_tgt_node(a))
1676 end_arcs.append(a);
1677 introsort(end_arcs, [](Arc *a, Arc *b)
1678 {
1679 return a->flow < b->flow;
1680 });
1681 Flow_Type left = std::abs(apart);
1682 for (Arc *a : end_arcs)
1683 {
1684 if (not (left > Flow_Type{0}))
1685 break;
1686 const Flow_Type before = a->flow;
1687 lower(a, left);
1688 left -= before - a->flow;
1689 }
1690 settle(); // what that left, next to the source or the sink
1691 }
1692 }
1693 else
1694 {
1695 (void) net;
1696 (void) source;
1697 (void) sink;
1698 }
1699}
1700} // namespace net_detail
1701
1713template <class Net>
1714typename Net::Flow_Type increase_flow(Net &net, const Path<Net> &path)
1715{
1716 typename Net::Flow_Type slack = net.Infinity; // bottleneck
1717 using Tuple = std::tuple<typename Net::Node *, typename Net::Arc *>;
1718
1719 // Compute the bottleneck of the augmenting path.
1720 for (typename Path<Net>::Iterator it(path); it.has_current_arc(); it.next_ne())
1721 {
1722 Tuple t = it.get_tuple_ne();
1723 auto p = get<0>(t);
1724 auto arc = get<1>(t);
1725 const auto w = remaining_flow<Net>(p, arc);
1726 if (w < slack)
1727 slack = w;
1728 }
1729
1730 // Increase flow along the augmenting path.
1731 for (typename Path<Net>::Iterator it(path); it.has_current_arc(); it.next_ne())
1732 {
1733 auto t = it.get_tuple_ne();
1734 auto p = get<0>(t);
1735 auto arc = get<1>(t);
1736
1737 if (is_residual<Net>(p, arc))
1738 net_detail::subtract_flow(arc, slack);
1739 else
1740 net_detail::add_flow(arc, slack);
1741
1742 assert(arc->check_arc());
1743 }
1744
1745 return slack;
1746}
1747
1762template <class Net>
1763void increase_flow(Net &net, const DynList<Parc<Net>> &semi_path, const typename Net::Flow_Type slack)
1764{
1765 (void) net; // May be unused when NDEBUG disables assert().
1766
1767 // Increase flow along the semi-path.
1768 for (auto it = semi_path.get_it(); it.has_curr(); it.next_ne())
1769 {
1770 auto p = it.get_curr();
1771 auto arc = get<0>(p);
1772 if (get<1>(p)) // forward arc
1773 net_detail::add_flow(arc, slack);
1774 else
1775 net_detail::subtract_flow(arc, slack);
1776
1777 assert(arc->check_arc());
1778 }
1779 if constexpr (not std::is_floating_point_v<typename Net::Flow_Type>)
1780 assert(net.check_network());
1781}
1782
1795template <class Net>
1796void decrease_flow(Net &net, const DynList<Parc<Net>> &semi_path, const typename Net::Flow_Type slack)
1797{
1798 (void) net;
1799
1800 // Decrease flow: reverse the direction logic from increase_flow
1801 for (auto it = semi_path.get_it(); it.has_curr(); it.next_ne())
1802 {
1803 auto p = it.get_curr();
1804 auto arc = get<0>(p);
1805 if (get<1>(p)) // forward arc: decrease instead of increase
1806 net_detail::subtract_flow(arc, slack);
1807 else // residual arc: increase instead of decrease
1808 net_detail::add_flow(arc, slack);
1809
1810 assert(arc->check_arc());
1811 }
1812}
1813
1820template <class Net, template <typename T> class Q>
1822{
1823 const Net &net;
1824
1825 // Return end node if a path is found. The cookie of each node reached
1826 // keeps the arc by which it was reached, which the paths take: with
1827 // parallel arcs, another one could have less slack than min_slack.
1828 typename Net::Node *search(typename Net::Node *start, typename Net::Node *end,
1829 typename Net::Flow_Type min_slack)
1830 {
1831 using Itor = Net_Iterator<Net>;
1832 net.reset_nodes();
1833 net.reset_bit_arcs(); // only their states: their cookies stay, as
1834 // those of an auxiliary network to the original
1835
1836 start->set_state(Processed);
1837 Q<typename Net::Arc *> q;
1838 for (Itor it(start); it.has_curr(); it.next_ne())
1839 {
1840 auto a = it.get_curr();
1841 if (remaining_flow<Net>(start, a) < min_slack)
1842 continue;
1843 auto tgt = net.get_connected_node(a, start);
1844 tgt->set_state(Processing);
1845 a->set_state(Processing);
1846 q.put(a);
1847 }
1848
1849 typename Net::Node *curr = nullptr;
1850 while (not q.is_empty())
1851 {
1852 auto arc = q.get();
1853 assert(arc->state() == Processing);
1854 arc->set_state(Processed);
1855
1856 auto s = net.get_src_node(arc);
1857 auto t = net.get_tgt_node(arc);
1858
1859 if (s->state() == Processed and t->state() == Processed)
1860 continue;
1861
1862 curr = s->state() == Processed ? t : s;
1863 assert(curr->state() == Processing);
1864 curr->set_state(Processed);
1865 NODE_COOKIE(curr) = arc;
1866
1867 if (curr == end)
1868 return curr;
1869
1870 for (Itor it(curr); it.has_curr(); it.next_ne())
1871 {
1872 auto a = it.get_curr();
1873
1874 // Skip arcs already processed or already in queue
1875 if (a->state() != Unprocessed)
1876 continue;
1877
1878 if (remaining_flow<Net>(curr, a) < min_slack)
1879 continue;
1880
1881 auto tgt = net.get_connected_node(a, curr);
1882 if (tgt->state() == Processed)
1883 {
1884 a->set_state(Processed);
1885 continue;
1886 }
1887
1888 a->set_state(Processing);
1889 q.put(a);
1890 tgt->set_state(Processing);
1891 }
1892 } // end while
1893
1894 return nullptr;
1895 }
1896
1898 Path<Net> find(typename Net::Node *start, typename Net::Node *end,
1899 const typename Net::Flow_Type &min_slack = typename Net::Flow_Type{0})
1900 {
1901 auto curr = search(start, end, min_slack);
1902
1903 Path<Net> ret(net);
1904 if (not curr)
1905 return ret;
1906
1907 assert(curr == end);
1908
1909 ret.insert(curr);
1910 while (curr != start)
1911 {
1912 auto arc = static_cast<typename Net::Arc *>(NODE_COOKIE(curr));
1913 ret.insert(arc); // the arc that the search took, of the parallels
1914 curr = net.get_connected_node(arc, curr);
1915 }
1916
1917 return ret;
1918 }
1919
1921 SemiPath<Net> find_path(typename Net::Node *start, typename Net::Node *end,
1922 typename Net::Flow_Type min_slack = typename Net::Flow_Type{0})
1923 {
1924 auto t = search(start, end, min_slack);
1925 if (not t)
1926 return std::make_tuple(false, typename Net::Flow_Type{0}, DynList<Parc<Net>>());
1927
1928 assert(t == end);
1929
1931 auto m = std::numeric_limits<typename Net::Flow_Type>::max();
1932 while (t != start)
1933 {
1934 auto a = static_cast<typename Net::Arc *>(NODE_COOKIE(t));
1935 auto s = net.get_connected_node(a, t);
1936 bool normal = a->tgt_node == t;
1937 auto slack = normal ? a->cap - a->flow : a->flow;
1938 m = std::min(m, slack);
1939 semi_path.insert(std::make_tuple(a, normal));
1940 t = s;
1941 }
1942
1943 return std::make_tuple(true, m, std::move(semi_path));
1944 }
1945
1946public:
1949 {
1950 return find_path(net.get_source(), net.get_sink(), min_slack);
1951 }
1952
1955 {
1956 return find_path(net.get_sink(), net.get_source(), min_slack);
1957 }
1958
1960 Find_Aumenting_Path(const Net &__g) : net(__g)
1961 {
1962 // empty
1963 }
1964
1966 Path<Net> operator () (typename Net::Node *start, typename Net::Node *end,
1967 typename Net::Flow_Type min_slack = 0)
1968 {
1969 return find(start, end, min_slack);
1970 }
1971
1974 {
1975 return find_aum_path(min_slack);
1976 }
1977
1982 typename Net::Flow_Type semi_path(typename Net::Node *start, typename Net::Node *end,
1984 const typename Net::Flow_Type &min_slack = 0)
1985 {
1986 semi_path.empty();
1987
1988 auto result = find_path(start, end, min_slack);
1989 if (not get<0>(result))
1990 return typename Net::Flow_Type{};
1991
1992 semi_path = std::move(get<2>(result));
1993 return get<1>(result);
1994 }
1995};
1996
2003template <class Net>
2005
2007template <class Net>
2009
2017template <class Net, template <typename T> class Q>
2018Path<Net> find_aumenting_path(const Net &net, const typename Net::Flow_Type &min_slack)
2019{
2020 auto s = net.get_source();
2021 auto t = net.get_sink();
2022 return Find_Aumenting_Path<Net, Q>(net)(s, t, min_slack);
2023}
2024
2026template <class Net>
2027Path<Net> find_aumenting_path_dfs(const Net &net, const typename Net::Flow_Type &min_slack)
2028{
2029 return find_aumenting_path<Net, DynListStack>(net, min_slack);
2030}
2031
2033template <class Net>
2034Path<Net> find_aumenting_path_bfs(const Net &net, const typename Net::Flow_Type &min_slack)
2035{
2036 return find_aumenting_path<Net, DynListQueue>(net, min_slack);
2037}
2038
2047template <class Net, template <typename T> class Q>
2049{
2050 return Find_Aumenting_Path<Net, Q>(net).find_aum_path(slack);
2051}
2052
2054template <class Net>
2056{
2057 return find_aumenting_semi_path<Net, DynListStack>(net, slack);
2058}
2059
2061template <class Net>
2063{
2064 return find_aumenting_semi_path<Net, DynListQueue>(net, slack);
2065}
2066
2075template <class Net, template <typename T> class Q>
2076SemiPath<Net> find_decrementing_path(const Net &net, const typename Net::Flow_Type &slack)
2077{
2078 return Find_Aumenting_Path<Net, Q>(net).find_dec_path(slack);
2079}
2080
2082template <class Net>
2084{
2085 return find_decrementing_path<Net, DynListStack>(net, slack);
2086}
2087
2089template <class Net>
2091{
2092 return find_decrementing_path<Net, DynListQueue>(net, slack);
2093}
2094
2096template <class Net>
2097struct PP_Res_Node : public Net_Node<Empty_Class>
2098{
2100
2103
2106
2108 PP_Res_Node(const Empty_Class &info) : Base(info) {}
2109
2111 PP_Res_Node(Empty_Class &&info) : Base(std::move(info)) {}
2112};
2113
2118template <class Net>
2119struct __Res_Arc : public Net_Arc<Empty_Class, typename Net::Flow_Type>
2120{
2122
2123 typename Net::Arc *img = nullptr; // nullptr indicates residual arc
2124 __Res_Arc *dup = nullptr;
2125
2128
2130 __Res_Arc(const Empty_Class &info) : Base(info) {}
2131
2133 __Res_Arc(Empty_Class &&info) : Base(std::move(info)) {}
2134
2136 bool is_residual() const
2137 {
2138 return img == nullptr;
2139 }
2140};
2141
2143template <class Net>
2145
2147template <class Net>
2149
2151template <class Net>
2152inline void create_residual_arc(const Net &net, PP_Res_Net<Net> &rnet, typename Net::Arc *a)
2153{
2154 using Rnet = PP_Res_Net<Net>;
2155 auto s = net.get_src_node(a);
2156 auto t = net.get_tgt_node(a);
2157
2158 assert(NODE_COOKIE(s) and NODE_COOKIE(t));
2159
2160 auto src = static_cast<typename Rnet::Node *>(NODE_COOKIE(s));
2161 auto tgt = static_cast<typename Rnet::Node *>(NODE_COOKIE(t));
2162
2163 auto arc = rnet.insert_arc(src, tgt);
2164 auto dup = rnet.insert_arc(tgt, src);
2165
2166 arc->img = a; // mark it as not residual
2167 arc->cap = a->cap;
2168 arc->flow = a->flow;
2169 arc->dup = dup;
2170
2171 dup->cap = arc->cap;
2172 dup->flow = arc->cap - arc->flow;
2173 dup->dup = arc;
2174}
2175
2177template <class Rnet>
2178struct Res_F
2179{
2180 Res_F(typename Rnet::Node *) noexcept {}
2181 Res_F() noexcept {}
2182
2183 bool operator () (typename Rnet::Arc *a) const
2184 {
2185 return a->cap > a->flow;
2186 }
2187};
2188
2193template <class Net>
2194inline std::tuple<PP_Res_Net<Net>, typename PP_Res_Net<Net>::Node *, typename PP_Res_Net<Net>::Node *>
2196{
2197 using Rnet = PP_Res_Net<Net>;
2198 net.reset_nodes();
2199 Rnet rnet;
2200
2201 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
2202 {
2203 auto p = it.get_curr();
2204 auto q = rnet.insert_node();
2205 q->in_flow = net.get_in_flow(p);
2206 q->out_flow = net.get_out_flow(p);
2207 // Directly store pointers in cookies using reinterpret_cast to
2208 // preserve exact addresses without multiple inheritance adjustment
2209 NODE_COOKIE(p) = reinterpret_cast<void *>(q);
2210 NODE_COOKIE(q) = reinterpret_cast<void *>(p);
2211 }
2212
2213 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
2214 create_residual_arc(net, rnet, it.get_curr());
2215
2216 return std::make_tuple(std::move(rnet),
2217 static_cast<typename Rnet::Node *>(NODE_COOKIE(net.get_source())),
2218 static_cast<typename Rnet::Node *>(NODE_COOKIE(net.get_sink())));
2219}
2220
2222template <class Rnet>
2223inline void update_flow(const Rnet &rnet)
2224{
2225 for (typename Rnet::Arc_Iterator it(rnet); it.has_curr(); it.next_ne())
2226 {
2227 auto arc = it.get_curr();
2228 auto img = arc->img;
2229 if (img == nullptr)
2230 continue;
2231 img->flow = arc->flow;
2232 }
2233}
2234
2257template <class Net, template <class> class Find_Path>
2259{
2261 << "Network is not single source and single sink";
2262
2263 while (true) // while an augmenting path exists
2264 {
2265 SemiPath<Net> semi_path = Find_Path<Net>(net)();
2266 if (not get<0>(semi_path))
2267 break;
2268
2269 // Skip paths with zero slack.
2270 // This can happen with parallel arcs where one arc is saturated
2271 // but the path finder still finds a path through it.
2272 auto slack = get<1>(semi_path);
2273 if (slack <= typename Net::Flow_Type{0})
2274 break;
2275
2276 increase_flow<Net>(net, get<2>(semi_path), slack);
2277 }
2278
2279 // A slack that rounding left on an arc of larger flows, next to one of
2280 // smaller capacity, may go along a path as a residue, whose nodes then
2281 // lose their balance when other paths take their flows to zero
2282 net_detail::return_dust(net, net.get_source(), net.get_sink());
2283 assert(net.get_source() == net.get_sink() or net.check_network());
2284
2285 return net.get_out_flow(net.get_source());
2286}
2287
2305template <class Net>
2307{
2308 if constexpr (std::is_floating_point_v<typename Net::Flow_Type>)
2309 return aumenting_path_maximum_flow<Net, Find_Aumenting_Path_BFS>(net);
2310 else
2311 return aumenting_path_maximum_flow<Net, Find_Aumenting_Path_DFS>(net);
2312}
2313
2318template <class Net>
2320{
2322 typename Net::Flow_Type operator () (Net &net) const
2323 {
2324 return ford_fulkerson_maximum_flow(net);
2325 }
2326};
2327
2335template <class Net>
2337{
2338 return aumenting_path_maximum_flow<Net, Find_Aumenting_Path_BFS>(net);
2339}
2340
2345template <class Net>
2347{
2349 typename Net::Flow_Type operator () (Net &net) const
2350 {
2351 return edmonds_karp_maximum_flow<Net>(net);
2352 }
2353};
2354
2356template <class Net>
2357static inline bool is_node_active(const Net &net, typename Net::Node *p)
2358{
2359 return net.get_in_flow(p) != net.get_out_flow(p);
2360}
2361
2363template <class Rnet>
2364static inline bool is_node_active(typename Rnet::Node *p)
2365{
2366 return p->in_flow != p->out_flow;
2367}
2368
2370template <class Net>
2371static inline long &node_height(typename Net::Node *p)
2372{
2373 return NODE_COUNTER(p);
2374}
2375
2377template <class Net>
2378static inline void init_height_in_nodes(Net &net)
2379{
2381 net.get_sink(), [&net](typename Net::Node *p, typename Net::Arc *a)
2382 {
2383 if (a)
2384 node_height<Net>(p) = node_height<Net>(net.get_tgt_node(a)) + 1;
2385 return true;
2386 });
2387}
2388
2390template <class Q_Type>
2391static inline void put_in_active_queue(Q_Type &q, typename Q_Type::Item_Type &p)
2392{
2393 if (NODE_BITS(p).get_bit(Aleph::Maximum_Flow))
2394 return; // the node is already into the queue
2395 NODE_BITS(p).set_bit(Aleph::Maximum_Flow, true);
2396 q.put(p);
2397}
2398
2400template <class Q_Type>
2401static inline typename Q_Type::Item_Type get_from_active_queue(Q_Type &q)
2402{
2403 auto p = q.get();
2404 assert(NODE_BITS(p).get_bit(Aleph::Maximum_Flow));
2405 NODE_BITS(p).set_bit(Aleph::Maximum_Flow, false);
2406 return p;
2407}
2408
2410template <class Q_Type>
2411static inline void remove_from_active_queue(Q_Type &q, typename Q_Type::Item_Type &p)
2412{
2413 assert(NODE_BITS(p).get_bit(Aleph::Maximum_Flow));
2414 NODE_BITS(p).set_bit(Aleph::Maximum_Flow, false);
2415 q.remove(p);
2416}
2417
2418namespace net_detail {
2419// For a floating flow, a path from the source to the sink of arcs of
2420// infinite capacity makes the maximum flow infinite. If there is one, it
2421// takes an infinite flow, and the function returns true: the preflows
2422// end then, as their initial preflow would fill an arc of infinite
2423// capacity out of the source with infinity, which a node that cannot
2424// send it on cannot send back either, inf - inf being NaN. Only arcs of
2425// infinite capacity are searched, and only if one leaves the source:
2426// otherwise, the cost is that of a pass over the arcs of the source
2427template <class Net>
2429{
2430 using Flow_Type = typename Net::Flow_Type;
2431 if constexpr (std::numeric_limits<Flow_Type>::has_infinity)
2432 {
2433 constexpr Flow_Type inf = std::numeric_limits<Flow_Type>::infinity();
2434 auto source = net.get_source();
2435 bool leaves = false;
2436 for (typename Net::Node_Arc_Iterator it(source); it.has_curr() and not leaves; it.next_ne())
2437 if (auto a = it.get_curr(); net.get_src_node(a) == source and a->cap == inf)
2438 leaves = true;
2439 if (not leaves)
2440 return false;
2441
2442 SemiPath<Net> semi_path = Find_Aumenting_Path_BFS<Net>(net)(inf);
2443 if (not get<0>(semi_path))
2444 return false;
2445 increase_flow<Net>(net, get<2>(semi_path), inf);
2446 return true;
2447 }
2448 else
2449 {
2450 (void) net;
2451 return false;
2452 }
2453}
2454
2455// The flow that the initial preflow gives an arc of infinite capacity
2456// out of the source, when no path of such arcs goes to the sink: a bound
2457// of the maximum flow, the capacity of a cut: that of the arcs into the
2458// sink, if all of them are finite, or else the sum of all the finite
2459// capacities, as the nodes that arcs of infinite capacity reach from the
2460// source make a cut without them. max() if the sum goes beyond it
2461template <class Net>
2463{
2464 using Flow_Type = typename Net::Flow_Type;
2465 constexpr Flow_Type inf = std::numeric_limits<Flow_Type>::infinity();
2466 auto sink = net.get_sink();
2467 Flow_Type bound{0};
2468 bool finite = true;
2469 for (typename Net::Node_Arc_Iterator it(sink); it.has_curr() and finite; it.next_ne())
2470 if (auto a = it.get_curr(); net.get_tgt_node(a) == sink)
2471 {
2472 if (a->cap == inf)
2473 finite = false;
2474 else
2475 bound += a->cap;
2476 }
2477 if (not finite)
2478 {
2479 bound = Flow_Type{0};
2480 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
2481 if (auto a = it.get_curr(); a->cap != inf)
2482 bound += a->cap;
2483 }
2484 return std::min(bound, std::numeric_limits<Flow_Type>::max());
2485}
2486} // namespace net_detail
2487
2525template <class Net, class Q_Type>
2527{
2529 << "Network is not single source and single sink";
2530
2531 // A path of arcs of infinite capacity makes the maximum flow infinite
2533 return net.flow_value();
2534
2535 net.reset_nodes(); // especially assures that counters are in zero
2536 init_height_in_nodes(net); // set height to minimum distance in nodes to sink
2537
2538 auto source = net.get_source();
2539 auto sink = net.get_sink();
2540 node_height<Net>(source) = net.vsize(); // except the source
2541 constexpr auto Max = std::numeric_limits<long>::max();
2542
2543 using Itor = __Net_Iterator<Net>;
2544 using Flow_Type = typename Net::Flow_Type;
2545 // An arc of infinite capacity out of the source takes a bound of the
2546 // maximum flow, computed once if one needs it
2547 [[maybe_unused]] Flow_Type bound{0};
2548 [[maybe_unused]] bool bounded = false;
2549 for (Itor it(source); it.has_curr(); it.next_ne()) // initial preflow
2550 {
2551 auto arc = it.get_curr();
2552 arc->flow = arc->cap; // saturate arc
2553 if constexpr (std::numeric_limits<Flow_Type>::has_infinity)
2554 if (arc->cap == std::numeric_limits<Flow_Type>::infinity())
2555 {
2556 if (not bounded)
2557 {
2559 bounded = true;
2560 }
2561 arc->flow = bound;
2562 }
2563 if (auto tgt = net.get_tgt_node(arc); tgt != sink) // never active
2564 put_in_active_queue(q, tgt);
2565 }
2566
2567 while (not q.is_empty()) // while there are active nodes
2568 {
2569 auto src = get_from_active_queue(q);
2570 // With a floating flow, the flows of src, which keep what their
2571 // rounding loses; an excess up to residue is a residue of rounding
2572 // of them, and is not pushed
2573 [[maybe_unused]] net_detail::Flow_Sum<Flow_Type> in, out;
2574 Flow_Type excess, residue;
2575 if constexpr (std::is_floating_point_v<Flow_Type>)
2576 {
2577 net_detail::node_flows(net, src, in, out);
2578 excess = in.minus(out);
2579 residue = net_detail::node_residue(in.value(), out.value(), net.get_num_arcs(src));
2580 }
2581 else
2582 {
2583 excess = net.get_in_flow(src) - net.get_out_flow(src);
2584 residue = Flow_Type{0};
2585 }
2586 long m = Max;
2587 bool was_eligible_arc = false;
2588 for (Itor it(src); it.has_curr() and excess > residue; it.next_ne())
2589 {
2590 auto arc = it.get_curr();
2591 auto tgt = net.get_connected_node(arc, src);
2592 if (node_height<Net>(src) != node_height<Net>(tgt) + 1)
2593 {
2594 m = std::min(m, node_height<Net>(tgt));
2595 continue;
2596 }
2597
2598 was_eligible_arc = true;
2599 if constexpr (std::is_floating_point_v<Flow_Type>)
2600 {
2601 // The excess follows the flows that src keeps, which the
2602 // arc changed: a small push beside a large excess would be
2603 // lost in it, and src would then push back too much
2604 net_detail::push_excess(arc, not is_residual<Net>(src, arc), in, out);
2605 excess = in.minus(out);
2606 }
2607 else
2608 {
2609 Flow_Type flow_to_push;
2610 if (is_residual<Net>(src, arc))
2611 {
2612 flow_to_push = std::min(arc->flow, excess);
2613 arc->flow -= flow_to_push;
2614 }
2615 else
2616 {
2617 flow_to_push = std::min(arc->cap - arc->flow, excess);
2618 arc->flow += flow_to_push;
2619 }
2620 excess -= flow_to_push;
2621 }
2622 if (tgt != source and tgt != sink)
2623 {
2624 assert(net_detail::not_short(net, tgt));
2625 put_in_active_queue(q, tgt);
2626 }
2627 }
2628
2629 if (excess > residue) // is src still active
2630 {
2631 if (not was_eligible_arc)
2632 node_height<Net>(src) = m + 1;
2633 put_in_active_queue(q, src);
2634 }
2635 }
2636
2637 // What a floating flow keeps as residues of rounding goes back
2638 net_detail::return_dust(net, source, sink);
2639
2640 // A network of one node, its source and sink, has no arcs, which
2641 // check_network() does not take
2642 assert(source == sink or net.check_network());
2643
2644 return net.flow_value();
2645}
2646
2648template <class Rnet>
2649inline void init_height_in_nodes(Rnet &rnet, typename Rnet::Node *sink)
2650{
2652 sink, [&rnet](typename Rnet::Node *p, typename Rnet::Arc *a)
2653 {
2654 if (a)
2655 node_height<Rnet>(p) = node_height<Rnet>(rnet.get_src_node(a)) + 1;
2656 return true;
2657 });
2658}
2659
2667template <class Net>
2669{
2670 using Node = typename Net::Node;
2671 return generic_preflow_vertex_push_maximum_flow<Net, DynListQueue<Node *>>(net);
2672}
2673
2678template <class Net>
2680{
2682 typename Net::Flow_Type operator () (Net &net) const
2683 {
2684 return fifo_preflow_maximum_flow(net);
2685 }
2686};
2687
2689template <class Net>
2691{
2692 bool operator () (typename Net::Node *n1, typename Net::Node *n2) const
2693 {
2694 return node_height<Net>(n1) > node_height<Net>(n2);
2695 }
2696};
2697
2705template <class Net>
2707{
2708 using Node = typename Net::Node;
2709 return generic_preflow_vertex_push_maximum_flow<Net, DynBinHeap<Node *, Compare_Height<Net>>>(net);
2710}
2711
2716template <class Net>
2718{
2720 typename Net::Flow_Type operator () (Net &net) const
2721 {
2722 return heap_preflow_maximum_flow(net);
2723 }
2724};
2725
2737template <class Net>
2739{
2740 using Node = typename Net::Node;
2741 return generic_preflow_vertex_push_maximum_flow<Net, Random_Set<Node *>>(net);
2742}
2743
2755template <class Net>
2756typename Net::Flow_Type random_preflow_maximum_flow(Net &net, const unsigned long seed)
2757{
2758 using Node = typename Net::Node;
2760 q.set_seed(seed);
2761 return generic_preflow_vertex_push_maximum_flow<Net, Random_Set<Node *>>(net, std::move(q));
2762}
2763
2768template <class Net>
2770{
2772 typename Net::Flow_Type operator () (Net &net) const
2773 {
2774 return random_preflow_maximum_flow(net);
2775 }
2776};
2777
2789template <class Net, template <class> class Maxflow>
2794{
2795 Maxflow<Net>()(net); // compute max flow
2796
2797 typename Net::Node *source = net.get_source();
2798
2799 // Traverse the residual network from source: reachable nodes go to vs.
2800 (Graph_Traverse_BFS<Net, Net_Iterator<Net>>(net))(source, [&vs](typename Net::Node *p)
2801 {
2802 vs.insert(p);
2803 return true;
2804 });
2805
2806 // Compute vt by complement.
2807 const size_t size_vt = net.get_num_nodes() - vs.size();
2808 for (Node_Iterator<Net> it(net); it.has_curr() and vt.size() < size_vt; it.next_ne())
2809 if (auto p = it.get_curr(); p->state() == Unprocessed)
2810 vt.insert(p);
2811
2812 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
2813 {
2814 auto arc = it.get_curr();
2815 if (arc->flow == 0) // residual candidate
2816 if (vt.contains(net.get_src_node(arc)) and // vt -> vs
2817 vs.contains(net.get_tgt_node(arc)))
2818 {
2819 cutt.insert(arc);
2820 continue;
2821 }
2822
2823 if (arc->flow == arc->cap) // saturated candidate
2824 if (vs.contains(net.get_src_node(arc)) and // vs -> vt
2825 vt.contains(net.get_tgt_node(arc)))
2826 cuts.insert(arc);
2827 }
2828
2829 return net.flow_value();
2830}
2831
2836template <class Net, template <class> class Maxflow = Heap_Preflow_Maximum_Flow>
2838{
2844 {
2845 return min_cut<Net, Maxflow>(net, vs, vt, cuts, cutt);
2846 }
2847};
2848} // end namespace Aleph
2849
2850#endif // TPL_NET_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double w
Definition btreepic.C:153
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
virtual void remove_arc(Arc *a)
Definition tpl_agraph.H:601
virtual Node * insert_node(Node *p)
Inserts the node p, made with new, which the graph takes.
Definition tpl_agraph.H:494
Arc * disconnect_arc(Arc *arc)
Definition tpl_agraph.H:586
Dlink & get_arc_dlink() noexcept
Returns reference to internal arc Dlink for sorting operations.
Definition tpl_agraph.H:312
virtual void remove_node(Node *p)
Definition tpl_agraph.H:606
Arc * insert_arc(Node *src, Node *tgt, void *a)
Definition tpl_agraph.H:565
Arc * connect_arc(Arc *arc)
Definition tpl_agraph.H:558
Dlink & get_node_dlink() noexcept
Returns reference to internal node Dlink for sorting operations.
Definition tpl_agraph.H:309
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void clear() noexcept
Empties the container.
Definition tpl_array.H:435
static Array create(const size_t n)
Create an array with n logical elements.
Definition tpl_array.H:245
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
auto next_ne() noexcept(noexcept(std::declval< I & >().next_ne())) -> decltype(std::declval< I & >().next_ne())
next() without checks.
RAII guard that saves and restores graph cookies.
Filtered iterator on directed graphs.
Definition tpl_graph.H:1770
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Node Node
Definition graph-dry.H:4380
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
T & insert(const T &item)
Definition htlist.H:1308
Dynamic set backed by balanced binary search trees with automatic memory management.
const Key & get_item() const
Returns any element of the set.
const size_t & size() const
Returns the cardinality of the set.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
void swap(DynSetTree &dset) noexcept(noexcept(tree.swap(dset.tree)) and noexcept(std::swap(num_nodes, dset.num_nodes)) and noexcept(std::swap(arena_allocator, dset.arena_allocator)))
Exchange all elements of this set with dset in constant time (and extremely fast).
size_t remove(const Key &key)
Removes a key from the dynamic set.
bool contains(const Key &key) const
Checks if a key exists in the set.
bool is_empty() const
returns true if the set is empty
Generic filter iterator wrapper.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Augmenting-path search over a directed network.
Definition tpl_net.H:1822
Path< Net > operator()(typename Net::Node *start, typename Net::Node *end, typename Net::Flow_Type min_slack=0)
Find a concrete Path with at least min_slack.
Definition tpl_net.H:1966
Find_Aumenting_Path(const Net &__g)
Construct a finder for net.
Definition tpl_net.H:1960
Net::Flow_Type semi_path(typename Net::Node *start, typename Net::Node *end, DynList< Parc< Net > > &semi_path, const typename Net::Flow_Type &min_slack=0)
Fill semi_path and return the slack value.
Definition tpl_net.H:1982
Path< Net > find(typename Net::Node *start, typename Net::Node *end, const typename Net::Flow_Type &min_slack=typename Net::Flow_Type{0})
Build a Path from start to end with minimum slack.
Definition tpl_net.H:1898
SemiPath< Net > find_dec_path(typename Net::Flow_Type min_slack=0.0)
Find a decrementing semi-path with at least min_slack.
Definition tpl_net.H:1954
SemiPath< Net > find_aum_path(typename Net::Flow_Type min_slack=0.0)
Find an augmenting semi-path with at least min_slack.
Definition tpl_net.H:1948
SemiPath< Net > find_path(typename Net::Node *start, typename Net::Node *end, typename Net::Flow_Type min_slack=typename Net::Flow_Type{0})
Build a SemiPath from start to end with minimum slack.
Definition tpl_net.H:1921
Net::Node * search(typename Net::Node *start, typename Net::Node *end, typename Net::Flow_Type min_slack)
Definition tpl_net.H:1828
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Iterator on nodes and arcs of a path.
Definition tpl_graph.H:4395
Node * get_current_node_ne() const noexcept
Definition tpl_graph.H:4425
Node * get_current_node() const
Return the current node of a path.
Definition tpl_graph.H:4420
Arc * get_current_arc_ne() const noexcept
Definition tpl_graph.H:4447
bool has_current_arc() const noexcept
Return true if iterator has current arc.
Definition tpl_graph.H:4506
Path on a graph.
Definition tpl_graph.H:3832
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
const GT & get_graph() const noexcept
Get a constant reference to the graph.
Definition tpl_graph.H:3921
void set_seed(unsigned long seed) const
Seeds the Mersenne Twister of the set, as gsl_rng_set() did: the positions are from then on those of ...
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Container< Arc * > arcs() const
Return a container with all the arcs of the graph.
Definition graph-dry.H:3080
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
std::tuple< Arc *, Node * > ArcPair
Pair of arc and node (topologically related)
Definition graph-dry.H:3666
void *& get_cookie() noexcept
Return a modifiable reference to graph's cookie.
Definition graph-dry.H:931
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
void common_swap(GT &g) noexcept
Definition graph-dry.H:921
void reset_bit_arcs(int bit) const noexcept
Reset bit to zero for all the arcs of graph.
Definition graph-dry.H:1332
size_t out_degree(Node *p) const noexcept
Compute the output degree of a node.
Definition graph-dry.H:3765
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
size_t esize() const noexcept
Return the total of arcs of graph.
Definition graph-dry.H:1078
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
size_t in_degree(Node *p) const noexcept
Compute the input degree of a node.
Definition graph-dry.H:3740
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
Container< Node * > nodes() const
Return a container with all the nodes of the graph.
Definition graph-dry.H:3062
Traverse a graph depth-first or breadth-first and execute a visit function.
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.
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
Graph traversal algorithms (DFS, BFS).
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
const unsigned char Processed
The node or arc has already been processed.
Definition aleph-graph.C:39
const unsigned char Processing
The node are being processed; probably it is inside a queue, stack or heap.
Definition aleph-graph.C:38
#define NODE_COUNTER(p)
Get the counter of a node.
#define NODE_COOKIE(p)
Return the node cookie
const unsigned char Unprocessed
The node have not bees processed.
Definition aleph-graph.C:37
#define NODE_BITS(p)
Get the control bits of a node.
void copy_graph(GT &gtgt, const GT &gsrc, bool cookie_map=false)
Explicit copy of graph.
Definition tpl_graph.H:4794
@ Maximum_Flow
Definition aleph-graph.H:78
@ Find_Path
Definition aleph-graph.H:76
double Flow_Type
bool not_short(const Net &net, typename Net::Node *p)
Definition tpl_net.H:1268
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 node_flows(const Net &net, typename Net::Node *p, Flow_Sum< typename Net::Flow_Type > &in, Flow_Sum< typename Net::Flow_Type > &out) noexcept
Definition tpl_net.H:1348
void subtract_flow(Arc *arc, const Flow_Type &slack) noexcept
Definition tpl_net.H:1283
constexpr bool flow_type_ok(const float *) noexcept
Whether float can be the type of a flow: it can, but it is deprecated, and this overload,...
Definition tpl_net.H:127
Net::Flow_Type infinite_arc_preflow(const Net &net)
Definition tpl_net.H:2462
Main namespace for Aleph-w library functions.
SemiPath< Net > find_aumenting_semi_path_dfs(const Net &net, const typename Net::Flow_Type &slack)
Find an augmenting semi-path using DFS.
Definition tpl_net.H:2055
static void remove_from_active_queue(Q_Type &q, typename Q_Type::Item_Type &p)
Remove a node from the active queue and clear its queue mark.
Definition tpl_net.H:2411
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
Net::Flow_Type generic_preflow_vertex_push_maximum_flow(Net &net, Q_Type q=Q_Type())
Generic preflow-push maximum flow (vertex-oriented).
Definition tpl_net.H:2526
void decrease_flow(Net &net, const DynList< Parc< Net > > &semi_path, const typename Net::Flow_Type slack)
Decrease flow along a semi-path by a given slack.
Definition tpl_net.H:1796
Net::Flow_Type edmonds_karp_maximum_flow(Net &net)
Maximize flow using the Edmonds-Karp algorithm.
Definition tpl_net.H:2336
bool is_residual(typename Net::Node *src, typename Net::Arc *a) noexcept
Return true if arc a is residual with respect to src.
Definition tpl_net.H:212
Net::Flow_Type random_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a random active-node queue.
Definition tpl_net.H:2738
Path< Net > find_aumenting_path_dfs(const Net &net, const typename Net::Flow_Type &min_slack)
Find an augmenting path using DFS.
Definition tpl_net.H:2027
SemiPath< Net > find_decrementing_path(const Net &net, const typename Net::Flow_Type &slack)
Find a decrementing semi-path using DFS or BFS based on Q.
Definition tpl_net.H:2076
Net::Flow_Type heap_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a height-ordered heap.
Definition tpl_net.H:2706
SemiPath< Net > find_aumenting_semi_path_bfs(const Net &net, const typename Net::Flow_Type &slack)
Find an augmenting semi-path using BFS.
Definition tpl_net.H:2062
DynList< std::pair< typename Container1::Item_Type, typename Container2::Item_Type > > zip(const Container1 &a, const Container2 &b)
Zip two containers into a list of pairs.
static Q_Type::Item_Type get_from_active_queue(Q_Type &q)
Dequeue an active node and clear its queue mark.
Definition tpl_net.H:2401
Net::Flow_Type increase_flow(Net &net, const Path< Net > &path)
Increase flow along an augmenting path.
Definition tpl_net.H:1714
SemiPath< Net > find_decrementing_path_dfs(const Net &net, const typename Net::Flow_Type &slack)
Find a decrementing semi-path using DFS.
Definition tpl_net.H:2083
void create_residual_arc(const Net &net, PP_Res_Net< Net > &rnet, typename Net::Arc *a)
Create residual arcs for a in the residual network.
Definition tpl_net.H:2152
std::tuple< PP_Res_Net< Net >, typename PP_Res_Net< Net >::Node *, typename PP_Res_Net< Net >::Node * > preflow_create_residual_net(Net &net)
Build the residual network for preflow-push algorithms.
Definition tpl_net.H:2195
Path< Net > find_aumenting_path_bfs(const Net &net, const typename Net::Flow_Type &min_slack)
Find an augmenting path using BFS.
Definition tpl_net.H:2034
and
Check uniqueness with explicit hash + equality functors.
bool diff(const C1 &c1, const C2 &c2, Eq e=Eq())
Check if two containers differ.
static long & node_height(typename Net::Node *p)
Access the height label stored in NODE_COUNTER.
Definition tpl_net.H:2371
std::tuple< bool, typename Net::Flow_Type, DynList< Parc< Net > > > SemiPath
Semi-path tuple:
Definition tpl_net.H:1198
SemiPath< Net > find_aumenting_semi_path(const Net &net, const typename Net::Flow_Type &slack)
Find an augmenting semi-path using DFS or BFS based on Q.
Definition tpl_net.H:2048
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
Net::Flow_Type fifo_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a FIFO queue of active nodes.
Definition tpl_net.H:2668
Path< Net > find_aumenting_path(const Net &net, const typename Net::Flow_Type &min_slack)
Find an augmenting path using DFS or BFS based on Q.
Definition tpl_net.H:2018
static bool is_node_active(const Net &net, typename Net::Node *p)
Return true if p has excess flow in net.
Definition tpl_net.H:2357
Net::Flow_Type ford_fulkerson_maximum_flow(Net &net)
Maximize flow using the Ford-Fulkerson algorithm.
Definition tpl_net.H:2306
static void init_height_in_nodes(Net &net)
Initialize node heights with BFS distance to the sink.
Definition tpl_net.H:2378
SemiPath< Net > find_decrementing_path_bfs(const Net &net, const typename Net::Flow_Type &slack)
Find a decrementing semi-path using BFS.
Definition tpl_net.H:2090
void update_flow(const Rnet &rnet)
Propagate residual arc flows back to their original arcs.
Definition tpl_net.H:2223
static void put_in_active_queue(Q_Type &q, typename Q_Type::Item_Type &p)
Enqueue an active node if it is not already enqueued.
Definition tpl_net.H:2391
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
bool between(const Point &a, const Point &b, const Point &c)
Net::Flow_Type aumenting_path_maximum_flow(Net &net)
Maximize flow using repeated augmenting-path searches.
Definition tpl_net.H:2258
void introsort(T *a, const long l, const long r, const Compare &cmp=Compare())
Sort an array using introsort (introspective sort).
Net::Flow_Type min_cut(Net &net, DynSetTree< typename Net::Node * > &vs, DynSetTree< typename Net::Node * > &vt, DynList< typename Net::Arc * > &cuts, DynList< typename Net::Arc * > &cutt)
Compute max flow and the corresponding minimum cut.
Definition tpl_net.H:2790
std::tuple< typename Net::Arc *, bool > Parc
Arc entry for a semi-path.
Definition tpl_net.H:1188
@ Tuple
Tuple type such as (Int, Bool).
void print(const DynList< Parc< Net > > &sp)
Print a semi-path to stdout.
Definition tpl_net.H:1202
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Iterator over arcs of a graph.
Definition tpl_agraph.H:334
Compare nodes by height (higher first).
Definition tpl_net.H:2691
bool operator()(typename Net::Node *n1, typename Net::Node *n2) const
Definition tpl_net.H:2692
Functor wrapper for edmonds_karp_maximum_flow().
Definition tpl_net.H:2347
Net::Flow_Type operator()(Net &net) const
Invoke edmonds_karp_maximum_flow().
Definition tpl_net.H:2349
Empty placeholder class with no data members.
Definition ahDefs.H:107
Functor wrapper for fifo_preflow_maximum_flow().
Definition tpl_net.H:2680
Net::Flow_Type operator()(Net &net) const
Invoke fifo_preflow_maximum_flow().
Definition tpl_net.H:2682
Functor wrapper for ford_fulkerson_maximum_flow().
Definition tpl_net.H:2320
Net::Flow_Type operator()(Net &net) const
Invoke ford_fulkerson_maximum_flow().
Definition tpl_net.H:2322
Functor wrapper for heap_preflow_maximum_flow().
Definition tpl_net.H:2718
Net::Flow_Type operator()(Net &net) const
Invoke heap_preflow_maximum_flow().
Definition tpl_net.H:2720
Functor wrapper for min_cut().
Definition tpl_net.H:2838
Net::Flow_Type operator()(Net &net, DynSetTree< typename Net::Node * > &vs, DynSetTree< typename Net::Node * > &vt, DynList< typename Net::Arc * > &cuts, DynList< typename Net::Arc * > &cutt)
Invoke min_cut().
Definition tpl_net.H:2840
Arc info extension that stores capacity and flow values.
Definition tpl_net.H:87
Flow_Type flow
Flow value.
Definition tpl_net.H:92
Flow_Type cap
Capacity value.
Definition tpl_net.H:89
Net_Arc_Info()=default
Default constructor.
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
bool check_arc() const noexcept
Return true if flow satisfies 0 <= flow <= cap.
Definition tpl_net.H:175
Net_Arc()
Default constructor.
Definition tpl_net.H:192
Flow_Type cap
Capacity value.
Definition tpl_net.H:169
Net_Arc(const Arc_Info &info)
Construct from arc info.
Definition tpl_net.H:181
Net_Arc & operator=(const Net_Arc &arc)
Copy assignment.
Definition tpl_net.H:197
Flow_Type flow
Flow value.
Definition tpl_net.H:172
F_Type Flow_Type
Definition tpl_net.H:166
Net_Arc(const Net_Arc &arc)
Copy constructor.
Definition tpl_net.H:186
Ftype Flow_Type
Type representing flow, capacity, and cost values.
Arc filter for residual traversal in flow networks.
Definition tpl_net.H:224
Net::Node * get_node(typename Net::Arc *a) const noexcept
Return the opposite endpoint of arc a with respect to p.
Definition tpl_net.H:260
Net_Filt(typename Net::Node *s=nullptr) noexcept
Build a filter rooted at node s.
Definition tpl_net.H:236
void set_cookie(void *__cookie) noexcept
Store an opaque cookie for compatibility with other iterators.
Definition tpl_net.H:230
bool operator()(typename Net::Arc *a) const noexcept
Return true if arc a has residual capacity with respect to p.
Definition tpl_net.H:241
Net::Node * p
Definition tpl_net.H:225
void * cookie
Definition tpl_net.H:227
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
static Flow_Type check_tolerance(const Flow_Type &in, const Flow_Type &out) noexcept
Definition tpl_net.H:513
Node * emplace_node(Args &&...args)
Construct a node in-place and insert it into the network.
Definition tpl_net.H:769
Flow_Type get_out_flow(Node *node) const noexcept
Return total outgoing flow of node.
Definition tpl_net.H:399
typename Arc::Arc_Type Arc_Type
Arc info type.
Definition tpl_net.H:334
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
Definition tpl_net.H:750
void set_cap(Arc *arc, const Flow_Type &cap)
Set the capacity of an arc.
Definition tpl_net.H:1071
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
Definition tpl_net.H:595
Node * insert_node(Node_Type &&info)
Insert a new node by moving info.
Definition tpl_net.H:762
bool check_network() const
Validate flow-conservation and capacity constraints.
Definition tpl_net.H:1116
bool is_connected(Node *p) const noexcept
Return true if p is connected (used for validation).
Definition tpl_net.H:441
bool with_super_sink
True if the network has a super-sink.
Definition tpl_net.H:1153
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
Definition tpl_net.H:589
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
typename Node::Node_Type Node_Type
Node info type.
Definition tpl_net.H:331
Arc * connect_arc(Arc *arc)
Connect a previously disconnected arc.
Definition tpl_net.H:832
Arc * emplace_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &flow, Args &&...args)
Construct arc info in-place and insert the arc.
Definition tpl_net.H:818
Net_Graph()
Default constructor.
Definition tpl_net.H:1156
Net_Graph(const Net_Graph &net)
Copy-construct a network. Throws bad_alloc on allocation failure.
Definition tpl_net.H:953
Node * super_source_node
Definition tpl_net.H:504
bool same_totals(const Flow_Type &out, const Flow_Type &in) const
Definition tpl_net.H:538
void remove_arc(Arc *arc) override
Remove arc arc from the network.
Definition tpl_net.H:906
void set_flow(Arc *arc, const Flow_Type &flow)
Set the flow of an arc. Throws if flow exceeds capacity.
Definition tpl_net.H:1079
Flow_Type nodes_tolerance() const
Definition tpl_net.H:524
virtual void disconnect_arc(Arc *arc)
Disconnect arc arc from the graph without deleting it.
Definition tpl_net.H:921
void make_super_source()
Convert a multi-source network into a single super-source network.
Definition tpl_net.H:603
void make_super_sink()
Convert a multi-sink network into a single super-sink network.
Definition tpl_net.H:656
size_t get_out_degree(Node *p) const noexcept
Return the out-degree of p (number of outgoing arcs).
Definition tpl_net.H:393
void register_ends_of_leaving(Arc *arc)
Definition tpl_net.H:881
Array_Graph< NodeT, ArcT > Base
Definition tpl_net.H:314
constexpr bool is_single_source() const noexcept
Return true if the network has a single source.
Definition tpl_net.H:429
Node * register_node(Node *p)
Insert p into source/sink sets with rollback on failure.
Definition tpl_net.H:570
Flow_Type total_sink_in_flow() const
Return total incoming flow to all sinks.
Definition tpl_net.H:561
bool is_source(Node *node) const noexcept
Return true if node is a source.
Definition tpl_net.H:417
Node * get_source() const
Return an arbitrary source node.
Definition tpl_net.H:733
friend std::ostream & operator<<(std::ostream &s, const Path< Net_Graph > &path)
Stream a path with arc (cap,flow) tuples.
Definition tpl_net.H:1163
Flow_Type get_out_cap(Node *node) const noexcept
Return total outgoing capacity of node.
Definition tpl_net.H:378
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
DynSetTree< Node * > src_nodes
Definition tpl_net.H:498
bool with_super_source
True if the network has a super-source.
Definition tpl_net.H:1150
Arc * insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap)
Insert an arc with capacity cap and zero flow.
Definition tpl_net.H:846
DynList< Node * > out_nodes(Node *p) const noexcept
Return nodes reachable from p through outgoing arcs.
Definition tpl_net.H:345
Node * insert_node(Node *p) override
Insert the node p, allocated by the caller.
Definition tpl_net.H:781
void unmake_super_nodes()
Restore a super-source/super-sink network to its original form.
Definition tpl_net.H:726
Flow_Type Infinity
Definition tpl_net.H:336
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
DynList< Arc * > out_arcs(Node *p) const noexcept
Return arcs outgoing from p (as a DynList).
Definition tpl_net.H:339
Flow_Type total_source_out_flow() const
Return total outgoing flow from all sources.
Definition tpl_net.H:552
virtual void swapped() noexcept
What swap() calls on each of its two networks, once their nodes and arcs are exchanged: nothing,...
Definition tpl_net.H:1023
Node * super_sink_node
Definition tpl_net.H:505
void unmake_super_sink()
Restore a super-sink network to its original multi-sink form, by removing the super sink that make_su...
Definition tpl_net.H:688
Flow_Type get_in_cap(Node *node) const noexcept
Return total incoming capacity of node.
Definition tpl_net.H:369
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
bool is_sink(Node *node) const noexcept
Return true if node is a sink.
Definition tpl_net.H:423
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
Arc * insert_arc(Node *src_node, Node *tgt_node)
Insert an arc with zero capacity and flow, for an arc info that is arithmetic or of the type of the f...
Definition tpl_net.H:871
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
void swap_contents(Net_Graph &other) noexcept
Exchange the nodes, the arcs and the rest of the state of this network with those of other,...
Definition tpl_net.H:995
Net_Graph & operator=(Net_Graph &&other) noexcept
Move-assign a network. O(1) operation.
Definition tpl_net.H:1051
void make_super_nodes()
Convert a multi-source/multi-sink network into super-source/super-sink.
Definition tpl_net.H:709
DynSetTree< Node * > sink_nodes
Definition tpl_net.H:499
DynList< Node * > in_nodes(Node *p) const noexcept
Return nodes that can reach p through incoming arcs.
Definition tpl_net.H:360
Net_Graph(Net_Graph &&other) noexcept
Move-construct a network. O(1) operation.
Definition tpl_net.H:1042
NodeT Node
Node type.
Definition tpl_net.H:325
const Flow_Type & get_cap(Arc *arc) const noexcept
Return the capacity value of an arc.
Definition tpl_net.H:1093
const Flow_Type & get_flow(Arc *arc) const noexcept
Return the flow value of an arc.
Definition tpl_net.H:1087
DynList< Arc * > in_arcs(Node *p) const noexcept
Return arcs incoming to p (as a DynList).
Definition tpl_net.H:354
Node * insert_node()
Insert a new node with default info.
Definition tpl_net.H:756
void unmake_super_source()
Restore a super-source network to its original multi-source form, by removing the super source that m...
Definition tpl_net.H:640
void reset()
Reset all arc flows to zero.
Definition tpl_net.H:1099
bool check_node(Node *node) const noexcept
Return true if node satisfies flow conservation constraints.
Definition tpl_net.H:468
size_t get_in_degree(Node *p) const noexcept
Return the in-degree of p (number of incoming arcs).
Definition tpl_net.H:387
void swap(Net_Graph &other) noexcept
Swap contents with another network.
Definition tpl_net.H:1032
Arc * insert_arc(Node *src_node, Node *tgt_node, const Arc_Type &arc_info=Arc_Type())
Insert an arc with zero capacity and flow.
Definition tpl_net.H:858
Residual node used by preflow-push algorithms.
Definition tpl_net.H:2098
PP_Res_Node()
Default constructor.
Definition tpl_net.H:2105
Net::Flow_Type out_flow
Definition tpl_net.H:2102
Net::Flow_Type in_flow
Definition tpl_net.H:2101
PP_Res_Node(const Empty_Class &info)
Constructor from node info.
Definition tpl_net.H:2108
PP_Res_Node(Empty_Class &&info)
Move constructor from node info.
Definition tpl_net.H:2111
Functor wrapper for random_preflow_maximum_flow().
Definition tpl_net.H:2770
Net::Flow_Type operator()(Net &net) const
Invoke random_preflow_maximum_flow().
Definition tpl_net.H:2772
Residual arc filter: keep arcs with residual capacity.
Definition tpl_net.H:2179
Res_F(typename Rnet::Node *) noexcept
Definition tpl_net.H:2180
Res_F() noexcept
Definition tpl_net.H:2181
bool operator()(typename Rnet::Arc *a) const
Definition tpl_net.H:2183
Arc of the residual network of the preflow-push algorithms.
Definition tpl_net.H:2120
__Res_Arc(const Empty_Class &info)
Constructor from arc info.
Definition tpl_net.H:2130
__Res_Arc * dup
Definition tpl_net.H:2124
bool is_residual() const
Return true if this is a residual arc.
Definition tpl_net.H:2136
__Res_Arc(Empty_Class &&info)
Move constructor from arc info.
Definition tpl_net.H:2133
Net::Arc * img
Definition tpl_net.H:2123
__Res_Arc()
Default constructor.
Definition tpl_net.H:2127
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
Flow_Type value() const noexcept
The sum, rounded once.
Definition tpl_net.H:1332
void replace(const Flow_Type &from, const Flow_Type &to) noexcept
Replaces the term from, which the sum has, by to.
Definition tpl_net.H:1325
void add(const Flow_Type &x) noexcept
Adds x.
Definition tpl_net.H:1316
Flow_Type minus(const Flow_Sum &other) const noexcept
This sum less other, rounded once but for the errors of lo.
Definition tpl_net.H:1338
Flow_Type hi
The sum, rounded.
Definition tpl_net.H:1312
Flow_Type lo
What its rounding lost.
Definition tpl_net.H:1313
Node * get_curr() const
Return the current node.
Definition graph-dry.H:522
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Dynamic array container with automatic resizing.
Dynamic binary heap with node-based storage.
Dynamic doubly linked list implementation.
Dynamic stack implementation based on linked lists.
Dynamic set implementations based on hash tables.
Dynamic set implementations based on balanced binary search trees.
Path finding algorithms in graphs.
Utility algorithms and operations for graphs.
Random access queue (bag) with O(1) random pop.
Comprehensive sorting algorithms and search utilities for Aleph-w.