Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_exhaustive_flow_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
70#include <algorithm>
71#include <array>
72#include <cmath>
73#include <cstdio>
74#include <limits>
75#include <map>
76#include <memory>
77#include <new>
78#include <numeric>
79#include <random>
80#include <set>
81#include <stdexcept>
82#include <string>
83#include <type_traits>
84#include <utility>
85#include <vector>
86
87#include <gmpxx.h>
88#include <gtest/gtest.h>
89
90#include "allocation_failure.H"
91
92#include <tpl_net.H>
93#include <tpl_maxflow.H>
94#include <tpl_netcost.H>
95#include <tpl_mincost.H>
96#include <tpl_netcapgraph.H>
97#include <tpl_net_sup_dem.H>
98#include <net_apps.H>
99#include <Hungarian.H>
100#include <Johnson.H>
101
102#include "graph_harness.H"
103#include "graph_oracles.H"
104
105using namespace Aleph;
106using namespace graph_harness;
107namespace oracle = graph_oracles;
108
109namespace
110{
111 // ------------------------------------------------------------------
112 // Amounts of flow
113
116 template <typename F>
117 constexpr long long Units_Per_One = std::is_floating_point_v<F> ? 4 : 1;
118
120 template <typename F>
121 F amount(long long units)
122 {
123 return F(units) / F(Units_Per_One<F>);
124 }
125
127 template <typename F>
128 bool is_amount(F x, long long units)
129 {
130 return x * F(Units_Per_One<F>) == F(units);
131 }
132
133 template <typename F>
134 std::string text(F x)
135 {
136 if constexpr (std::is_floating_point_v<F>)
137 {
138 char buf[40];
139 std::snprintf(buf, sizeof buf, "%.17g", double(x));
140 return buf;
141 }
142 else
143 return std::to_string(x);
144 }
145
146 // ------------------------------------------------------------------
147 // Networks built from specs
148
149 template <class Net>
150 concept Cost_Network = requires (typename Net::Arc * a) { a->cost; };
151
153 template <class Net>
154 typename Net::Node * insert_numbered_node(Net & net, int i)
155 {
156 return net.insert_node(i);
157 }
158
161 constexpr int Added_Source = -1;
162 constexpr int Added_Sink = -2;
163
167 template <class Net>
168 struct Built_Net
169 {
170 using Node = typename Net::Node;
171 using Arc = typename Net::Arc;
172 using F = typename Net::Flow_Type;
173
174 Net net;
175 std::vector<Node *> nodes;
176 std::vector<Arc *> arcs;
177 size_t spec_arcs = 0;
178 Node * src = nullptr; // the source and the sink of the flow
179 Node * snk = nullptr;
180 bool added_ends = false; // whether src and snk were added for the flow
181
182 Built_Net(const Spec & s, const std::vector<long long> & cap,
183 const std::vector<long long> & cost = {})
184 {
185 for (int i = 0; i < s.n; ++i)
186 nodes.push_back(insert_numbered_node(net, i));
187 for (size_t i = 0; i < s.arcs.size(); ++i)
188 arcs.push_back(add(nodes[size_t(s.arcs[i][0])], nodes[size_t(s.arcs[i][1])],
189 amount<F>(cap[i]),
190 i < cost.size() ? amount<F>(cost[i]) : F{0}));
191 spec_arcs = arcs.size();
192 }
193
195 explicit Built_Net(const Spec & s) : Built_Net(s, s.w) {}
196
198 struct Amounts {};
199 Built_Net(const Spec & s, const std::vector<F> & cap, Amounts)
200 {
201 for (int i = 0; i < s.n; ++i)
202 nodes.push_back(insert_numbered_node(net, i));
203 for (size_t i = 0; i < s.arcs.size(); ++i)
204 arcs.push_back(add(nodes[size_t(s.arcs[i][0])], nodes[size_t(s.arcs[i][1])], cap[i]));
205 spec_arcs = arcs.size();
206 }
207
208 Built_Net(const Built_Net &) = delete;
209 Built_Net & operator = (const Built_Net &) = delete;
210
211 Arc * add(Node * u, Node * v, F cap, F cost = F{0})
212 {
213 if constexpr (Cost_Network<Net>)
214 return net.insert_arc(u, v, cap, cost);
215 else
216 {
217 (void) cost;
218 return net.insert_arc(u, v, cap, F{0});
219 }
220 }
221
228 void pin(int s, int t)
229 {
230 if (s == t)
231 {
232 src = snk = nodes[size_t(s)];
233 return;
234 }
235 Node * a = nodes[size_t(s)], * z = nodes[size_t(t)];
236 added_ends = not net.is_source(a) or not net.is_sink(z);
237 if (added_ends)
238 {
239 F total{1};
240 for (Arc * arc : arcs)
241 total += arc->cap;
242 src = insert_numbered_node(net, Added_Source);
243 snk = insert_numbered_node(net, Added_Sink);
244 arcs.push_back(add(src, a, total));
245 arcs.push_back(add(z, snk, total));
246 }
247 else
248 {
249 src = a;
250 snk = z;
251 }
252
253 std::vector<Node *> others;
254 for (auto it = net.get_src_nodes().get_it(); it.has_curr(); it.next_ne())
255 if (it.get_curr() != src)
256 others.push_back(it.get_curr());
257 for (Node * p : others)
258 arcs.push_back(add(src, p, F{0}));
259
260 others.clear();
261 for (auto it = net.get_sink_nodes().get_it(); it.has_curr(); it.next_ne())
262 if (it.get_curr() != snk)
263 others.push_back(it.get_curr());
264 for (Node * p : others)
265 arcs.push_back(add(p, snk, F{0}));
266 }
267
270 int number(Arc * a) const
271 {
272 for (size_t i = 0; i < spec_arcs; ++i)
273 if (arcs[i] == a)
274 return int(i);
275 return -1;
276 }
277
279 F value() const
280 {
281 return net.get_out_flow(src) - net.get_in_flow(src);
282 }
283
285 std::vector<F> flows() const
286 {
287 std::vector<F> r;
288 for (Arc * a : arcs)
289 r.push_back(a->flow);
290 return r;
291 }
292
294 void set_flows(const std::vector<F> & f)
295 {
296 for (size_t i = 0; i < arcs.size(); ++i)
297 arcs[i]->flow = f[i];
298 }
299 };
300
301 template <class Node>
302 std::string name_of(Node * p)
303 {
304 const int i = p->get_info();
305 return i == Added_Source ? "s*" : i == Added_Sink ? "t*" : std::to_string(i);
306 }
307
312 template <class Net>
313 std::string flow_error(const Built_Net<Net> & b, bool tolerance = false)
314 {
315 using F = typename Net::Flow_Type;
316 for (typename Net::Arc_Iterator it(b.net); it.has_curr(); it.next_ne())
317 {
318 auto a = it.get_curr();
319 if (not (a->flow >= F{0} and a->flow <= a->cap))
320 return "the arc " + name_of(b.net.get_src_node(a)) + "->" + name_of(b.net.get_tgt_node(a))
321 + " carries " + text(a->flow) + " of " + text(a->cap);
322 }
323 for (typename Net::Node_Iterator it(b.net); it.has_curr(); it.next_ne())
324 {
325 auto p = it.get_curr();
326 if (p == b.src or p == b.snk)
327 continue;
328 const F in = b.net.get_in_flow(p), out = b.net.get_out_flow(p);
329 const bool kept = tolerance
330 ? std::abs(double(in) - double(out)) <= 1e-9 * std::max(std::abs(double(in)),
331 std::abs(double(out)))
332 : in == out;
333 if (not kept)
334 return "the node " + name_of(p) + " receives " + text(in) + " and sends " + text(out);
335 }
336 return "";
337 }
338
341 template <class Net>
342 std::string max_flow_error(const Built_Net<Net> & b, typename Net::Flow_Type got,
343 long long want)
344 {
345 if (auto e = flow_error(b); not e.empty())
346 return e;
347 if (not is_amount(b.value(), want))
348 return "the flow is " + text(b.value()) + ", not "
349 + text(amount<typename Net::Flow_Type>(want));
350 if (got != b.value())
351 return "returns " + text(got) + " for a flow of " + text(b.value());
352 return "";
353 }
354
357 std::vector<std::pair<int, int>> ends_of(const Spec & s)
358 {
359 std::vector<std::pair<int, int>> r;
360 if (s.n == 1)
361 r.push_back({0, 0});
362 for (int a = 0; a < s.n; ++a)
363 for (int z = 0; z < s.n; ++z)
364 if (a != z)
365 r.push_back({a, z});
366 return r;
367 }
368
370 template <class Net>
371 std::string where(const Built_Net<Net> & b, int a, int z)
372 {
373 return "from " + std::to_string(a) + " to " + std::to_string(z)
374 + (b.added_ends ? " through added ends" : "") + ": ";
375 }
376
378 Spec with_w(const Spec & s, const std::vector<long long> & w)
379 {
380 Spec r = s;
381 r.w = w;
382 return r;
383 }
384
386 template <class F>
387 void for_each_assignment(const Spec & s, const std::vector<long long> & values, F f)
388 {
389 std::vector<size_t> pick(s.arcs.size(), 0);
390 while (true)
391 {
392 std::vector<long long> w;
393 for (size_t k : pick)
394 w.push_back(values[k]);
395 f(with_w(s, w));
396 size_t i = 0;
397 while (i < pick.size() and ++pick[i] == values.size())
398 pick[i++] = 0;
399 if (i == pick.size())
400 return;
401 }
402 }
403
406 Spec structural(const Spec & s)
407 {
408 std::vector<long long> w;
409 for (size_t i = 0; i < s.arcs.size(); ++i)
410 w.push_back(static_cast<long long>(i) + 1);
411 return with_w(s, w);
412 }
413
414 // ------------------------------------------------------------------
415 // Oracles
416
419 template <typename N>
420 N exact_max_flow(const Spec & s, const std::vector<N> & cap, int a, int z)
421 {
422 const size_t n = size_t(s.n);
423 std::vector<std::vector<N>> c(n, std::vector<N>(n, N(0)));
424 for (size_t i = 0; i < s.arcs.size(); ++i)
425 if (s.arcs[i][0] != s.arcs[i][1])
426 c[size_t(s.arcs[i][0])][size_t(s.arcs[i][1])] += cap[i];
427 N flow(0);
428 while (true)
429 {
430 std::vector<int> parent(n, -1);
431 parent[size_t(a)] = a;
432 std::vector<int> queue = {a};
433 for (size_t h = 0; h < queue.size(); ++h)
434 for (size_t v = 0; v < n; ++v)
435 if (parent[v] == -1 and c[size_t(queue[h])][v] > 0)
436 {
437 parent[v] = queue[h];
438 queue.push_back(int(v));
439 }
440 if (parent[size_t(z)] == -1)
441 return flow;
442 N b = c[size_t(parent[size_t(z)])][size_t(z)];
443 for (int v = z; v != a; v = parent[size_t(v)])
444 b = std::min(b, c[size_t(parent[size_t(v)])][size_t(v)]);
445 for (int v = z; v != a; v = parent[size_t(v)])
446 {
447 c[size_t(parent[size_t(v)])][size_t(v)] -= b;
448 c[size_t(v)][size_t(parent[size_t(v)])] += b;
449 }
450 flow += b;
451 }
452 }
453
456 long long max_flow_units(const Spec & s, int a, int z)
457 {
458 if (a == z)
459 return 0;
460 return oracle::max_flow(s, a, z);
461 }
462
465 long long min_cut_units(const Spec & s, int a, int z)
466 {
467 long long best = oracle::Inf;
468 for (unsigned long set = 0; set < (1UL << s.n); ++set)
469 {
470 if (((set >> a) & 1UL) == 0 or ((set >> z) & 1UL) != 0)
471 continue;
472 long long cut = 0;
473 for (size_t i = 0; i < s.arcs.size(); ++i)
474 if (((set >> s.arcs[i][0]) & 1UL) != 0 and ((set >> s.arcs[i][1]) & 1UL) == 0)
475 cut += s.w[i];
476 best = std::min(best, cut);
477 }
478 return best;
479 }
480
481 // ------------------------------------------------------------------
482 // The maximum flow algorithms
483
485 template <class Net>
486 struct Solver
487 {
488 std::string name;
489 typename Net::Flow_Type (*run)(Net &);
490 };
491
492 template <class Net>
493 std::vector<Solver<Net>> augmenting_solvers()
494 {
495 return {{"ford_fulkerson_maximum_flow()", &ford_fulkerson_maximum_flow<Net>},
496 {"edmonds_karp_maximum_flow()", &edmonds_karp_maximum_flow<Net>}};
497 }
498
499 template <class Net>
500 std::vector<Solver<Net>> preflow_solvers()
501 {
502 return {{"fifo_preflow_maximum_flow()", &fifo_preflow_maximum_flow<Net>},
503 {"heap_preflow_maximum_flow()", &heap_preflow_maximum_flow<Net>}};
504 }
505
508 template <class Net>
509 std::vector<Solver<Net>> random_preflow_solvers()
510 {
511 return {{"random_preflow_maximum_flow()", &random_preflow_maximum_flow<Net>}};
512 }
513
514 template <class Net>
515 std::vector<Solver<Net>> advanced_solvers()
516 {
517 return {{"dinic_maximum_flow()", &dinic_maximum_flow<Net>},
518 {"capacity_scaling_maximum_flow()", &capacity_scaling_maximum_flow<Net>},
519 {"hlpp_maximum_flow()", &hlpp_maximum_flow<Net>}};
520 }
521
522 template <class Net>
523 std::vector<Solver<Net>> all_solvers()
524 {
525 auto r = augmenting_solvers<Net>();
526 for (auto & x : preflow_solvers<Net>())
527 r.push_back(x);
528 for (auto & x : random_preflow_solvers<Net>())
529 r.push_back(x);
530 for (auto & x : advanced_solvers<Net>())
531 r.push_back(x);
532 return r;
533 }
534
537 template <class Net>
538 std::vector<Solver<Net>> functor_solvers()
539 {
540 using F = typename Net::Flow_Type;
541 return {
542 {"Ford_Fulkerson_Maximum_Flow",
543 [] (Net & n) -> F { return Ford_Fulkerson_Maximum_Flow<Net>()(n); }},
544 {"Edmonds_Karp_Maximum_Flow",
545 [] (Net & n) -> F { return Edmonds_Karp_Maximum_Flow<Net>()(n); }},
546 {"Fifo_Preflow_Maximum_Flow",
547 [] (Net & n) -> F { return Fifo_Preflow_Maximum_Flow<Net>()(n); }},
548 {"Heap_Preflow_Maximum_Flow",
549 [] (Net & n) -> F { return Heap_Preflow_Maximum_Flow<Net>()(n); }},
550 {"Random_Preflow_Maximum_Flow",
551 [] (Net & n) -> F { return Random_Preflow_Maximum_Flow<Net>()(n); }},
552 {"Dinic_Maximum_Flow", [] (Net & n) -> F { return Dinic_Maximum_Flow<Net>()(n); }},
553 {"Capacity_Scaling_Maximum_Flow",
554 [] (Net & n) -> F { return Capacity_Scaling_Maximum_Flow<Net>()(n); }},
555 {"HLPP_Maximum_Flow", [] (Net & n) -> F { return HLPP_Maximum_Flow<Net>()(n); }}};
556 }
557
561 struct Known_Class
562 {
563 std::string why;
564 bool ends_program = false;
565 };
566
571 class Family_Checks
572 {
573 std::vector<std::string> names;
574 std::vector<Known_Class> classes;
575 std::vector<Check> plain;
576 std::map<std::pair<int, size_t>, Check> known;
577
578 public:
579 template <class Solvers>
580 explicit Family_Checks(const Solvers & solvers, std::vector<Known_Class> known_classes = {})
581 : classes(std::move(known_classes))
582 {
583 for (const auto & s : solvers)
584 {
585 names.push_back(s.name);
586 plain.emplace_back(s.name);
587 }
588 }
589
592 Check * of(size_t i, int k)
593 {
594 if (k == 0)
595 return &plain[i];
596 const Known_Class & c = classes[size_t(k - 1)];
597 Check & check = known.try_emplace({k, i}, names[i] + ", " + c.why, true).first->second;
598 if (c.ends_program)
599 {
600 check.skip();
601 return nullptr;
602 }
603 return &check;
604 }
605
606 void expect() const
607 {
608 for (const auto & c : plain)
609 c.expect();
610 for (const auto & [key, c] : known)
611 c.expect();
612 }
613 };
614
616 template <class Net>
617 int no_class(size_t, const Built_Net<Net> &)
618 {
619 return 0;
620 }
621
624 template <class Net>
625 void check_refusal(const std::vector<Solver<Net>> & solvers, const Spec & s, Check & refuse)
626 {
627 Built_Net<Net> b(s);
628 if (b.net.is_single_source() and b.net.is_single_sink())
629 return;
630 for (const auto & solver : solvers)
631 {
632 refuse.run();
633 try
634 {
635 solver.run(b.net);
636 refuse.fail(s, solver.name + " does not throw");
637 }
638 catch (const std::domain_error &) {}
639 catch (const std::exception & e)
640 {
641 refuse.fail(s, solver.name + " throws " + e.what());
642 }
643 }
644 }
645
651 template <class Net, class For_Each, class Classify>
652 void check_max_flows(const std::vector<Solver<Net>> & solvers, For_Each for_each,
653 Family_Checks & checks, Check & refuse, Classify classify)
654 {
655 for_each([&] (const Spec & s)
656 {
657 check_refusal(solvers, s, refuse);
658 for (auto [a, z] : ends_of(s))
659 {
660 Built_Net<Net> b(s);
661 b.pin(a, z);
662 if (not (b.net.is_single_source() and b.net.is_single_sink()))
663 {
664 // One node with loops, refused above; else the sets of the
665 // sources and sinks are wrong
666 if (a != z)
667 refuse.fail(s, where(b, a, z) + "the network keeps other sources or sinks");
668 continue;
669 }
670 const long long want = max_flow_units(s, a, z);
671 for (size_t i = 0; i < solvers.size(); ++i)
672 {
673 Check * check = checks.of(i, classify(i, b));
674 if (check == nullptr)
675 continue;
676 b.net.reset();
677 check->run();
678 typename Net::Flow_Type got{};
679 try
680 {
681 got = solvers[i].run(b.net);
682 }
683 catch (const std::exception & e)
684 {
685 check->fail(s, where(b, a, z) + "throws " + e.what());
686 continue;
687 }
688 if (auto e = max_flow_error(b, got, want); not e.empty())
689 check->fail(s, where(b, a, z) + e);
690 }
691 }
692 });
693 }
694
696 auto structural_specs(const Domain & d)
697 {
698 return [d] (auto f)
699 {
700 for_each_spec(d, true, [&] (const Spec & s) { f(structural(s)); });
701 };
702 }
703
706 template <typename F>
707 std::vector<long long> capacity_class()
708 {
709 if constexpr (std::is_floating_point_v<F>)
710 return {0, 3, 6};
711 else
712 return {0, 1, 2};
713 }
714
718 Domain class_domain()
719 {
720 Domain d = domain(3, 3);
721 d.max_arcs = 3;
722 d.loops = false;
723 d.reversed = false;
724 return d;
725 }
726
729 template <typename F>
730 auto class_specs(const Domain & d)
731 {
732 return [d] (auto f)
733 {
734 for_each_spec(d, true, [&] (const Spec & s)
735 {
736 for_each_assignment(s, capacity_class<F>(), f);
737 });
738 };
739 }
740
744 auto random_specs(unsigned first, unsigned count)
745 {
746 return [first, count] (auto f)
747 {
748 std::mt19937 rng(seed(first));
749 for (unsigned k = 0; k < count; ++k)
750 {
751 const int n = 6 + int(rng() % 3);
752 const int m = 8 + int(rng() % 9);
753 Spec s = random_spec(rng, n, m, true);
754 random_weights(rng, s, 0, 5);
755 f(s);
756 }
757 };
758 }
759}
760
761// ======================================================================
762// Maximum flows
763
764template <class Net>
765class ExhaustiveMaxFlow : public ::testing::Test {};
766
769 ::testing::Types<Net_Graph<Net_Node<int>, Net_Arc<int, int>>,
772
774
775namespace
776{
780 template <class Net>
781 constexpr bool in_one_order = std::is_floating_point_v<typename Net::Flow_Type>;
782
787 template <class Net>
788 Domain max_flow_domain(bool one_order = false)
789 {
790 Domain d = Cost_Network<Net> ? domain(3, 3) : domain(4, 3);
791 d.reversed = not (one_order or in_one_order<Net>);
792 return d;
793 }
794
799 enum class Flow_Domain { Structural, Capacities };
800
801 template <class Net, class Classify>
802 void check_family(const std::vector<Solver<Net>> & solvers, Family_Checks & checks,
803 Check & refuse, Flow_Domain which, unsigned seed_base, Classify classify,
804 bool one_order = false)
805 {
806 if (which == Flow_Domain::Structural)
807 check_max_flows(solvers, structural_specs(max_flow_domain<Net>(one_order)), checks,
808 refuse, classify);
809 else
810 {
811 check_max_flows(solvers, class_specs<typename Net::Flow_Type>(class_domain()), checks,
812 refuse, classify);
813 check_max_flows(solvers, random_specs(seed_base, heavy() ? 400 : 40), checks, refuse,
814 classify);
815 }
816 checks.expect();
817 refuse.expect();
818 }
819
821 template <class Net>
822 void check_augmenting_paths(Flow_Domain which)
823 {
824 const auto solvers = augmenting_solvers<Net>();
825 Family_Checks checks(solvers);
826 Check refuse("the augmenting paths without one source and one sink");
827 check_family(solvers, checks, refuse, which, 11, no_class<Net>);
828 }
829
832 template <class Net>
833 void check_preflows(Flow_Domain which, bool random)
834 {
835 const auto solvers = random ? random_preflow_solvers<Net>() : preflow_solvers<Net>();
836 Family_Checks checks(solvers);
837 Check refuse("the preflows without one source and one sink");
838 // The random order does not need the arcs in two orders, and costs
839 // twice as much
840 check_family(solvers, checks, refuse, which, random ? 13 : 12, no_class<Net>, random);
841 }
842
844 template <class Net>
845 void check_advanced(Flow_Domain which)
846 {
847 const auto solvers = advanced_solvers<Net>();
848 Family_Checks checks(solvers);
849 Check refuse("Dinic, the scaling and HLPP without one source and one sink");
850 check_family(solvers, checks, refuse, which, 14, no_class<Net>);
851 }
852}
853
854TYPED_TEST(ExhaustiveMaxFlow, AugmentingPathsMatchTheOracle)
855{
856 check_augmenting_paths<TypeParam>(Flow_Domain::Structural);
857}
858
859TYPED_TEST(ExhaustiveMaxFlow, PreflowsMatchTheOracle)
860{
861 check_preflows<TypeParam>(Flow_Domain::Structural, false);
862}
863
864TYPED_TEST(ExhaustiveMaxFlow, RandomPreflowMatchesTheOracle)
865{
866 check_preflows<TypeParam>(Flow_Domain::Structural, true);
867}
868
869TYPED_TEST(ExhaustiveMaxFlow, DinicScalingAndHlppMatchTheOracle)
870{
871 check_advanced<TypeParam>(Flow_Domain::Structural);
872}
873
874template <class Net>
875class ExhaustiveMaxFlowCapacities : public ::testing::Test {};
876
879 ::testing::Types<Net_Graph<Net_Node<int>, Net_Arc<int, int>>,
881
883
884TYPED_TEST(ExhaustiveMaxFlowCapacities, AugmentingPathsTakeEveryCapacity)
885{
886 check_augmenting_paths<TypeParam>(Flow_Domain::Capacities);
887}
888
889TYPED_TEST(ExhaustiveMaxFlowCapacities, PreflowsTakeEveryCapacity)
890{
891 check_preflows<TypeParam>(Flow_Domain::Capacities, false);
892}
893
894TYPED_TEST(ExhaustiveMaxFlowCapacities, RandomPreflowTakesEveryCapacity)
895{
896 check_preflows<TypeParam>(Flow_Domain::Capacities, true);
897}
898
899TYPED_TEST(ExhaustiveMaxFlowCapacities, DinicScalingAndHlppTakeEveryCapacity)
900{
901 check_advanced<TypeParam>(Flow_Domain::Capacities);
902}
903
904// ======================================================================
905// Flows to start from, and second runs
906
907namespace
908{
910 template <class Net>
911 struct Node_Index
912 {
913 std::vector<typename Net::Node *> nodes;
914 std::map<typename Net::Node *, size_t> pos;
915
916 explicit Node_Index(const Net & net)
917 {
918 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
919 {
920 pos[it.get_curr()] = nodes.size();
921 nodes.push_back(it.get_curr());
922 }
923 }
924 };
925
928 struct Initial_Flow
929 {
930 long long value = 0;
931 bool cycle = false;
932 };
933
939 template <class Net>
940 Initial_Flow put_initial_flow(Built_Net<Net> & b, bool cycle = true)
941 {
942 using Arc = typename Net::Arc;
943 using F = typename Net::Flow_Type;
944 b.net.reset();
945 const Node_Index<Net> ix(b.net);
946 const size_t n = ix.nodes.size();
947 auto left = [] (Arc * a) { return a->cap - a->flow; };
948
949 long long value = 0;
950 if (b.src != b.snk)
951 {
952 std::vector<Arc *> by(n, nullptr);
953 std::vector<bool> seen(n, false);
954 std::vector<size_t> queue = {ix.pos.at(b.src)};
955 seen[queue[0]] = true;
956 for (size_t h = 0; h < queue.size(); ++h)
957 for (Arc * a : b.arcs)
958 if (ix.pos.at(b.net.get_src_node(a)) == queue[h] and left(a) > F{0})
959 if (const size_t v = ix.pos.at(b.net.get_tgt_node(a)); not seen[v])
960 {
961 seen[v] = true;
962 by[v] = a;
963 queue.push_back(v);
964 }
965 if (const size_t z = ix.pos.at(b.snk); seen[z])
966 {
967 F neck = std::numeric_limits<F>::max();
968 for (size_t v = z; by[v] != nullptr; v = ix.pos.at(b.net.get_src_node(by[v])))
969 neck = std::min(neck, left(by[v]));
970 for (size_t v = z; by[v] != nullptr; v = ix.pos.at(b.net.get_src_node(by[v])))
971 by[v]->flow += neck;
972 value = static_cast<long long>(neck * F(Units_Per_One<F>));
973 }
974 }
975
976 if (not cycle)
977 return {value, false};
978
979 // A cycle: a search in depth along arcs with capacity left, from each
980 // node, until an arc goes back to a node on the stack
981 for (size_t start = 0; start < n; ++start)
982 {
983 std::vector<Arc *> stack; // the arcs from start
984 std::vector<size_t> on = {start};
985 std::vector<int> state(n, 0); // 0 new, 1 on the stack, 2 done
986 std::vector<size_t> next(n, 0);
987 state[start] = 1;
988 while (not on.empty())
989 {
990 const size_t u = on.back();
991 bool advanced = false;
992 for (; next[u] < b.arcs.size(); ++next[u])
993 {
994 Arc * a = b.arcs[next[u]];
995 if (ix.pos.at(b.net.get_src_node(a)) != u or left(a) <= F{0})
996 continue;
997 const size_t v = ix.pos.at(b.net.get_tgt_node(a));
998 if (state[v] == 1)
999 {
1000 // The cycle: from v along the stack to u, and a
1001 std::vector<Arc *> c = {a};
1002 for (size_t k = stack.size(); k > 0 and on[k] != v; --k)
1003 c.push_back(stack[k - 1]);
1004 F neck = std::numeric_limits<F>::max();
1005 for (Arc * x : c)
1006 neck = std::min(neck, left(x));
1007 for (Arc * x : c)
1008 x->flow += neck;
1009 return {value, true};
1010 }
1011 if (state[v] == 0)
1012 {
1013 state[v] = 1;
1014 stack.push_back(a);
1015 on.push_back(v);
1016 ++next[u];
1017 advanced = true;
1018 break;
1019 }
1020 }
1021 if (not advanced)
1022 {
1023 state[u] = 2;
1024 on.pop_back();
1025 if (not stack.empty())
1026 stack.pop_back();
1027 }
1028 }
1029 }
1030 return {value, false};
1031 }
1032
1037 template <class Net>
1038 auto small_structural_specs()
1039 {
1040 Domain d = domain(3, 3);
1041 d.reversed = not in_one_order<Net>;
1042 return structural_specs(d);
1043 }
1044}
1045
1046TYPED_TEST(ExhaustiveMaxFlow, MaxFlowsFromAFlowAlreadyThere)
1047{
1048 using Net = TypeParam;
1049 const auto solvers = all_solvers<Net>();
1050 Family_Checks checks(solvers);
1051
1052 small_structural_specs<Net>()([&] (const Spec & s)
1053 {
1054 for (auto [a, z] : ends_of(s))
1055 {
1056 Built_Net<Net> b(s);
1057 b.pin(a, z);
1058 if (not (b.net.is_single_source() and b.net.is_single_sink()))
1059 continue;
1060 const long long want = max_flow_units(s, a, z);
1061 for (size_t i = 0; i < solvers.size(); ++i)
1062 {
1063 const long long start = put_initial_flow(b).value;
1064 Check * check = checks.of(i, 0);
1065 check->run();
1066 const std::string at = where(b, a, z) + "from a flow of "
1067 + text(amount<typename Net::Flow_Type>(start)) + ": ";
1068 try
1069 {
1070 const auto got = solvers[i].run(b.net);
1071 if (auto e = max_flow_error(b, got, want); not e.empty())
1072 check->fail(s, at + e);
1073 }
1074 catch (const std::exception & e)
1075 {
1076 check->fail(s, at + "throws " + e.what());
1077 }
1078 }
1079 }
1080 });
1081 checks.expect();
1082}
1083
1084TYPED_TEST(ExhaustiveMaxFlow, SecondRunsKeepTheMaximum)
1085{
1086 using Net = TypeParam;
1087 const auto solvers = all_solvers<Net>();
1088 const auto functors = functor_solvers<Net>();
1089 Family_Checks checks(functors);
1090
1091 small_structural_specs<Net>()([&] (const Spec & s)
1092 {
1093 for (auto [a, z] : ends_of(s))
1094 {
1095 Built_Net<Net> b(s);
1096 b.pin(a, z);
1097 if (not (b.net.is_single_source() and b.net.is_single_sink()))
1098 continue;
1099 const long long want = max_flow_units(s, a, z);
1100 for (size_t i = 0; i < solvers.size(); ++i)
1101 {
1102 Check * check = checks.of(i, 0);
1103 check->run();
1104 b.net.reset();
1105 try
1106 {
1107 solvers[i].run(b.net);
1108 const auto got = functors[i].run(b.net);
1109 if (auto e = max_flow_error(b, got, want); not e.empty())
1110 check->fail(s, where(b, a, z) + "the second run: " + e);
1111 }
1112 catch (const std::exception & e)
1113 {
1114 check->fail(s, where(b, a, z) + "throws " + e.what());
1115 }
1116 }
1117 }
1118 });
1119 checks.expect();
1120}
1121
1122// ======================================================================
1123// Minimum cuts
1124
1125namespace
1126{
1127 template <class Net>
1128 using Node_Set = DynSetTree<typename Net::Node *>;
1129
1130 template <class Net>
1131 using Arc_List = DynList<typename Net::Arc *>;
1132
1134 template <class Net>
1135 struct Cutter
1136 {
1137 std::string name;
1138 typename Net::Flow_Type (*run)(Net &, Node_Set<Net> &, Node_Set<Net> &, Arc_List<Net> &,
1139 Arc_List<Net> &);
1140 };
1141
1144 template <class Net>
1145 std::vector<Cutter<Net>> cutters()
1146 {
1147 return {
1148 {"min_cut<Ford_Fulkerson_Maximum_Flow>()", &min_cut<Net, Ford_Fulkerson_Maximum_Flow>},
1149 {"min_cut<Edmonds_Karp_Maximum_Flow>()", &min_cut<Net, Edmonds_Karp_Maximum_Flow>},
1150 {"min_cut<Fifo_Preflow_Maximum_Flow>()", &min_cut<Net, Fifo_Preflow_Maximum_Flow>},
1151 {"min_cut<Heap_Preflow_Maximum_Flow>()", &min_cut<Net, Heap_Preflow_Maximum_Flow>},
1152 {"min_cut<Random_Preflow_Maximum_Flow>()", &min_cut<Net, Random_Preflow_Maximum_Flow>},
1153 {"min_cut<Dinic_Maximum_Flow>()", &min_cut<Net, Dinic_Maximum_Flow>},
1154 {"min_cut<Capacity_Scaling_Maximum_Flow>()", &min_cut<Net, Capacity_Scaling_Maximum_Flow>},
1155 {"min_cut<HLPP_Maximum_Flow>()", &min_cut<Net, HLPP_Maximum_Flow>},
1156 {"Min_Cut", [] (Net & net, Node_Set<Net> & vs, Node_Set<Net> & vt, Arc_List<Net> & cuts,
1157 Arc_List<Net> & cutt) { return Min_Cut<Net>()(net, vs, vt, cuts, cutt); }}};
1158 }
1159
1162 template <class Net>
1163 std::set<typename Net::Node *> residual_reach(const Built_Net<Net> & b)
1164 {
1165 using F = typename Net::Flow_Type;
1166 std::set<typename Net::Node *> r = {b.src};
1167 for (bool grew = true; grew; )
1168 {
1169 grew = false;
1170 for (auto a : b.arcs)
1171 {
1172 auto u = b.net.get_src_node(a), v = b.net.get_tgt_node(a);
1173 if (r.count(u) and not r.count(v) and a->cap - a->flow > F{0})
1174 grew = r.insert(v).second;
1175 else if (r.count(v) and not r.count(u) and a->flow > F{0})
1176 grew = r.insert(u).second;
1177 }
1178 }
1179 return r;
1180 }
1181
1184 template <class Net>
1185 std::string cut_error(const Built_Net<Net> & b, const Node_Set<Net> & vs,
1186 const Node_Set<Net> & vt, const Arc_List<Net> & cuts,
1187 const Arc_List<Net> & cutt, typename Net::Flow_Type got, long long want)
1188 {
1189 using F = typename Net::Flow_Type;
1190 if (not is_amount(got, want))
1191 return "returns " + text(got) + ", not " + text(amount<F>(want));
1192 if (auto e = flow_error(b); not e.empty())
1193 return e;
1194 std::set<typename Net::Node *> s_side, t_side;
1195 for (auto it = vs.get_it(); it.has_curr(); it.next_ne())
1196 s_side.insert(it.get_curr());
1197 for (auto it = vt.get_it(); it.has_curr(); it.next_ne())
1198 t_side.insert(it.get_curr());
1199 if (s_side.size() + t_side.size() != b.net.get_num_nodes() or s_side.count(b.src) == 0
1200 or t_side.count(b.snk) == 0)
1201 return "the sides are not a partition with the source and the sink apart";
1202 for (auto p : s_side)
1203 if (t_side.count(p))
1204 return "the node " + name_of(p) + " is on both sides";
1205 if (s_side != residual_reach(b))
1206 return "the side of the source is not what the residual network reaches";
1207
1208 std::multiset<typename Net::Arc *> want_cuts, want_cutt, got_cuts, got_cutt;
1209 for (auto a : b.arcs)
1210 {
1211 const bool u = s_side.count(b.net.get_src_node(a)), v = s_side.count(b.net.get_tgt_node(a));
1212 if (u and not v)
1213 want_cuts.insert(a);
1214 else if (v and not u)
1215 want_cutt.insert(a);
1216 }
1217 F capacity{0};
1218 for (auto it = cuts.get_it(); it.has_curr(); it.next_ne())
1219 {
1220 got_cuts.insert(it.get_curr());
1221 capacity += it.get_curr()->cap;
1222 }
1223 for (auto it = cutt.get_it(); it.has_curr(); it.next_ne())
1224 got_cutt.insert(it.get_curr());
1225 if (got_cuts != want_cuts)
1226 return "the arcs of the cut are not those from the side of the source to the other";
1227 if (got_cutt != want_cutt)
1228 return "the arcs back are not those from the side of the sink to the other";
1229 if (capacity != got)
1230 return "the arcs of the cut have " + text(capacity) + ", not " + text(got);
1231 return "";
1232 }
1233}
1234
1235TYPED_TEST(ExhaustiveMaxFlow, MinCutsMatchTheOracle)
1236{
1237 using Net = TypeParam;
1238 const auto cuts = cutters<Net>();
1239 Family_Checks checks(cuts);
1240
1241 small_structural_specs<Net>()([&] (const Spec & s)
1242 {
1243 for (auto [a, z] : ends_of(s))
1244 {
1245 Built_Net<Net> b(s);
1246 b.pin(a, z);
1247 if (not (b.net.is_single_source() and b.net.is_single_sink()) or a == z)
1248 continue;
1249 const long long want = min_cut_units(s, a, z);
1250 for (size_t i = 0; i < cuts.size(); ++i)
1251 {
1252 Check * check = checks.of(i, 0);
1253 check->run();
1254 b.net.reset();
1255 Node_Set<Net> vs, vt;
1256 Arc_List<Net> cs, ct;
1257 try
1258 {
1259 const auto got = cuts[i].run(b.net, vs, vt, cs, ct);
1260 if (auto e = cut_error(b, vs, vt, cs, ct, got, want); not e.empty())
1261 check->fail(s, where(b, a, z) + e);
1262 }
1263 catch (const std::exception & e)
1264 {
1265 check->fail(s, where(b, a, z) + "throws " + e.what());
1266 }
1267 }
1268 }
1269 });
1270 checks.expect();
1271}
1272
1273// ======================================================================
1274// Decompositions and statistics
1275
1276namespace
1277{
1283 template <class Net>
1284 std::string decomposition_error(const Built_Net<Net> & b, const FlowDecomposition<Net> & d,
1285 bool rounded = false)
1286 {
1287 using F = typename Net::Flow_Type;
1288 using Arc = typename Net::Arc;
1289 using Node = typename Net::Node;
1290 std::map<Arc *, F> sum;
1291 auto same = [rounded] (F x, F y)
1292 {
1293 if constexpr (std::is_floating_point_v<F>)
1294 {
1295 if (rounded)
1296 return std::abs(x - y) <= 1e-9 * std::max({F{1}, std::abs(x), std::abs(y)});
1297 }
1298 else
1299 (void) rounded;
1300 return x == y;
1301 };
1302
1303 auto walk = [&] (const DynList<Arc *> & arcs, const DynList<Node *> & nodes, F flow,
1304 const char * what) -> std::string
1305 {
1306 std::vector<Arc *> as;
1307 std::vector<Node *> ns;
1308 for (auto it = arcs.get_it(); it.has_curr(); it.next_ne())
1309 as.push_back(it.get_curr());
1310 for (auto it = nodes.get_it(); it.has_curr(); it.next_ne())
1311 ns.push_back(it.get_curr());
1312 if (as.empty() or ns.size() != as.size() + 1 or not (flow > F{0}))
1313 return std::string("a ") + what + " of " + std::to_string(as.size()) + " arcs, "
1314 + std::to_string(ns.size()) + " nodes and flow " + text(flow);
1315 for (size_t k = 0; k < as.size(); ++k)
1316 {
1317 if (b.net.get_src_node(as[k]) != ns[k] or b.net.get_tgt_node(as[k]) != ns[k + 1])
1318 return std::string("a ") + what + " does not follow its arcs";
1319 sum[as[k]] += flow;
1320 }
1321 return "";
1322 };
1323
1324 for (auto it = d.paths.get_it(); it.has_curr(); it.next_ne())
1325 {
1326 const auto & p = it.get_curr();
1327 if (auto e = walk(p.arcs, p.nodes, p.flow, "path"); not e.empty())
1328 return e;
1329 if (p.nodes.get_first() != b.src or p.nodes.get_last() != b.snk)
1330 return "a path does not go from the source to the sink";
1331 }
1332 for (auto it = d.cycles.get_it(); it.has_curr(); it.next_ne())
1333 {
1334 const auto & c = it.get_curr();
1335 if (auto e = walk(c.arcs, c.nodes, c.flow, "cycle"); not e.empty())
1336 return e;
1337 if (c.nodes.get_first() != c.nodes.get_last())
1338 return "a cycle is not closed";
1339 }
1340 for (Arc * a : b.arcs)
1341 if (not same(sum[a], a->flow))
1342 return "the paths and cycles carry " + text(sum[a]) + " on the arc "
1343 + name_of(b.net.get_src_node(a)) + "->" + name_of(b.net.get_tgt_node(a)) + ", not "
1344 + text(a->flow);
1345 if (not same(d.total_flow(), b.value()))
1346 return "total_flow() is " + text(d.total_flow()) + ", not " + text(b.value());
1347 if (d.num_paths() != d.paths.size() or d.num_cycles() != d.cycles.size())
1348 return "num_paths() or num_cycles() do not count them";
1349 return "";
1350 }
1351
1354 template <class Net>
1355 std::string statistics_error(const Built_Net<Net> & b,
1357 {
1358 using F = typename Net::Flow_Type;
1359 F capacity{0};
1360 size_t saturated = 0, empty = 0, partial = 0;
1361 for (auto a : b.arcs)
1362 {
1363 capacity += a->cap;
1364 if (a->flow == a->cap)
1365 ++saturated;
1366 else if (a->flow == F{0})
1367 ++empty;
1368 else
1369 ++partial;
1370 }
1371 if (st.total_flow != b.value() or st.total_capacity != capacity)
1372 return "the flow " + text(st.total_flow) + " and capacity " + text(st.total_capacity)
1373 + ", not " + text(b.value()) + " and " + text(capacity);
1374 if (st.num_saturated_arcs != saturated or st.num_empty_arcs != empty
1375 or st.num_partial_arcs != partial)
1376 return "the counts of the arcs are wrong";
1377 const double use = capacity > F{0} ? double(b.value()) / double(capacity) : 0.0;
1378 if (st.utilization != use)
1379 return "the utilization is " + text(st.utilization) + ", not " + text(use);
1380 return "";
1381 }
1382}
1383
1384namespace
1385{
1391 template <class Net, class F>
1392 void for_each_flow_to_decompose(Check & refuse, bool reversed, F f)
1393 {
1394 for_each_spec(max_flow_domain<Net>(true), true, [&] (const Spec & given)
1395 {
1396 Spec r = given;
1397 if (reversed)
1398 std::reverse(r.arcs.begin(), r.arcs.end());
1399 const Spec s = structural(r);
1400 {
1401 Built_Net<Net> b(s);
1402 if (not (b.net.is_single_source() and b.net.is_single_sink()))
1403 {
1404 refuse.run();
1405 try
1406 {
1407 decompose_flow(b.net);
1408 refuse.fail(s, "does not throw");
1409 }
1410 catch (const std::domain_error &) {}
1411 }
1412 }
1413 for (auto [a, z] : ends_of(s))
1414 {
1415 Built_Net<Net> b(s);
1416 b.pin(a, z);
1417 if (not (b.net.is_single_source() and b.net.is_single_sink()))
1418 continue;
1419 put_initial_flow(b);
1420 f(s, b, where(b, a, z));
1421 }
1422 });
1423 }
1424}
1425
1426TYPED_TEST(ExhaustiveMaxFlow, DecompositionsRebuildFlowsWithCycles)
1427{
1428 using Net = TypeParam;
1429 Check check("decompose_flow(), of a flow with a cycle");
1430 Check refuse("decompose_flow() without one source and one sink");
1431 // The arcs in the reverse order: the other is in the test of the maximum
1432 // flows
1433 for_each_flow_to_decompose<Net>(refuse, true, [&] (const Spec & s, Built_Net<Net> & b,
1434 const std::string & at)
1435 {
1436 check.run();
1437 const auto before = b.flows();
1438 if (auto e = decomposition_error(b, decompose_flow(b.net)); not e.empty())
1439 check.fail(s, at + e);
1440 else if (b.flows() != before)
1441 check.fail(s, at + "changes the flows");
1442 });
1443 check.expect();
1444 refuse.expect();
1445}
1446
1447TYPED_TEST(ExhaustiveMaxFlow, DecompositionsRebuildTheMaximumFlow)
1448{
1449 using Net = TypeParam;
1450 Check function("decompose_flow()");
1451 Check functor("Decompose_Flow");
1452 Check stats("compute_flow_statistics()");
1453 Check refuse("decompose_flow() without one source and one sink, again");
1454 // The arcs in the order of for_each_spec(): the reverse is in the test of
1455 // the flows with cycles
1456 for_each_flow_to_decompose<Net>(refuse, false, [&] (const Spec & s, Built_Net<Net> & b,
1457 const std::string & at)
1458 {
1460 const auto after = b.flows();
1461 function.run();
1462 if (auto e = decomposition_error(b, decompose_flow(b.net)); not e.empty())
1463 function.fail(s, at + e);
1464 else if (b.flows() != after)
1465 function.fail(s, at + "changes the flows");
1466
1467 functor.run();
1468 if (auto e = decomposition_error(b, Decompose_Flow<Net>()(b.net)); not e.empty())
1469 functor.fail(s, at + e);
1470
1471 stats.run();
1472 if (auto e = statistics_error(b, compute_flow_statistics(b.net)); not e.empty())
1473 stats.fail(s, at + e);
1474 });
1475 for (const Check * c : {&function, &functor, &stats, &refuse})
1476 c->expect();
1477}
1478
1479// ======================================================================
1480// Augmenting paths
1481
1482namespace
1483{
1487 template <class Net>
1488 bool residual_path(const Built_Net<Net> & b, typename Net::Node * u, typename Net::Node * v,
1489 typename Net::Flow_Type slack)
1490 {
1491 using F = typename Net::Flow_Type;
1492 auto enough = [slack] (F x) { return x > F{0} and x >= slack; };
1493 std::set<typename Net::Node *> r = {u};
1494 for (bool grew = true; grew; )
1495 {
1496 grew = false;
1497 for (auto a : b.arcs)
1498 {
1499 auto p = b.net.get_src_node(a), q = b.net.get_tgt_node(a);
1500 if (r.count(p) and not r.count(q) and enough(a->cap - a->flow))
1501 grew = r.insert(q).second;
1502 else if (r.count(q) and not r.count(p) and enough(a->flow))
1503 grew = r.insert(p).second;
1504 }
1505 }
1506 return r.count(v) > 0;
1507 }
1508
1511 template <class Net>
1512 std::string augmenting_path_error(const Built_Net<Net> & b, const Path<Net> & p,
1513 typename Net::Node * u, typename Net::Node * v,
1514 typename Net::Flow_Type slack)
1515 {
1516 using F = typename Net::Flow_Type;
1517 std::vector<typename Net::Node *> ns;
1518 std::vector<typename Net::Arc *> as;
1519 for (typename Path<Net>::Iterator it(p); it.has_current_node(); it.next_ne())
1520 {
1521 ns.push_back(it.get_current_node_ne());
1522 if (it.has_current_arc())
1523 as.push_back(it.get_current_arc_ne());
1524 }
1525 if (ns.empty() or ns.front() != u or ns.back() != v or as.size() + 1 != ns.size())
1526 return "the path does not go from the start to the end";
1527 for (size_t k = 0; k < as.size(); ++k)
1528 {
1529 auto a = as[k];
1530 if (b.net.get_connected_node(a, ns[k]) != ns[k + 1])
1531 return "an arc of the path does not join its nodes";
1532 const F keep = remaining_flow<Net>(ns[k], a);
1533 if (not (keep > F{0} and keep >= slack))
1534 return "the path takes the arc " + name_of(b.net.get_src_node(a)) + "->"
1535 + name_of(b.net.get_tgt_node(a)) + ", which keeps " + text(keep) + " from "
1536 + name_of(ns[k]) + ", not " + text(slack);
1537 }
1538 return "";
1539 }
1540
1544 template <class Net>
1545 std::string semi_path_error(const Built_Net<Net> & b, const DynList<Parc<Net>> & sp,
1546 typename Net::Node * u, typename Net::Node * v,
1547 typename Net::Flow_Type given, typename Net::Flow_Type slack)
1548 {
1549 using F = typename Net::Flow_Type;
1550 auto at = u;
1551 F least = std::numeric_limits<F>::max();
1552 if (sp.is_empty())
1553 return "the semi-path is empty";
1554 for (auto it = sp.get_it(); it.has_curr(); it.next_ne())
1555 {
1556 auto [a, forward] = it.get_curr();
1557 F keep;
1558 if (forward)
1559 {
1560 if (b.net.get_src_node(a) != at)
1561 return "an arc forward does not leave the node where the semi-path is";
1562 keep = a->cap - a->flow;
1563 at = b.net.get_tgt_node(a);
1564 }
1565 else
1566 {
1567 if (b.net.get_tgt_node(a) != at)
1568 return "an arc backward does not enter the node where the semi-path is";
1569 keep = a->flow;
1570 at = b.net.get_src_node(a);
1571 }
1572 least = std::min(least, keep);
1573 }
1574 if (at != v)
1575 return "the semi-path does not end at the end";
1576 if (least != given)
1577 return "the slack is " + text(given) + ", not " + text(least);
1578 if (not (least > F{0} and least >= slack))
1579 return "the slack " + text(least) + " is less than " + text(slack);
1580 return "";
1581 }
1582}
1583
1584TYPED_TEST(ExhaustiveMaxFlow, AugmentingPathSearchesMatchTheOracle)
1585{
1586 using Net = TypeParam;
1587 using F = typename Net::Flow_Type;
1588 using Node = typename Net::Node;
1589 Check dfs("Find_Aumenting_Path_DFS(start, end, slack)");
1590 Check bfs("Find_Aumenting_Path_BFS(start, end, slack)");
1591 Check free_dfs("find_aumenting_path_dfs()");
1592 Check free_bfs("find_aumenting_path_bfs()");
1593 Check increase("increase_flow(net, path)");
1594 Check semi_dfs("Find_Aumenting_Path_DFS(slack)");
1595 Check semi_bfs("Find_Aumenting_Path_BFS(slack)");
1596 Check semi_free("find_aumenting_semi_path_dfs() and _bfs()");
1597 Check semi_fill("Find_Aumenting_Path_BFS::semi_path()");
1598 Check dec("find_decrementing_path_dfs() and _bfs()");
1599 Check dec_member("Find_Aumenting_Path_DFS::find_dec_path()");
1600 Check round("increase_flow(net, semi_path, slack) and decrease_flow()");
1601
1602 small_structural_specs<Net>()([&] (const Spec & s)
1603 {
1604 for (auto [a, z] : ends_of(s))
1605 {
1606 if (a == z)
1607 continue;
1608 Built_Net<Net> b(s);
1609 b.pin(a, z);
1610 for (long long units : {0LL, 1LL, 2LL})
1611 {
1612 put_initial_flow(b, false);
1613 const F slack = amount<F>(units);
1614 const std::string at = where(b, a, z) + "slack " + text(slack) + ": ";
1615 Node * u = b.src, * v = b.snk;
1616 const bool want = residual_path(b, u, v, slack);
1617 const bool want_back = residual_path(b, v, u, slack);
1618
1619 auto check_path = [&] (Check & check, const Path<Net> & p)
1620 {
1621 check.run();
1622 if (p.is_empty() == want)
1623 check.fail(s, at + (want ? "finds no path" : "finds a path"));
1624 else if (want)
1625 if (auto e = augmenting_path_error(b, p, u, v, slack); not e.empty())
1626 check.fail(s, at + e);
1627 };
1628 check_path(dfs, Find_Aumenting_Path_DFS<Net>(b.net)(u, v, slack));
1629 check_path(bfs, Find_Aumenting_Path_BFS<Net>(b.net)(u, v, slack));
1630 check_path(free_dfs, find_aumenting_path_dfs(b.net, slack));
1631 check_path(free_bfs, find_aumenting_path_bfs(b.net, slack));
1632
1633 // The slack that increase_flow() adds is the least of the path
1634 if (want)
1635 {
1636 Check & check = increase;
1637 check.run();
1638 const Path<Net> p = find_aumenting_path_bfs(b.net, slack);
1639 F least = std::numeric_limits<F>::max();
1640 for (typename Path<Net>::Iterator it(p); it.has_current_arc(); it.next_ne())
1641 least = std::min(least, remaining_flow<Net>(it.get_current_node_ne(),
1642 it.get_current_arc_ne()));
1643 const F before = b.value();
1644 const F added = increase_flow(b.net, p);
1645 if (added != least or b.value() != before + added)
1646 check.fail(s, at + "adds " + text(added) + " for a least slack of "
1647 + text(least));
1648 else if (not (added >= slack and added > F{0}))
1649 check.fail(s, at + "adds " + text(added) + ", less than the slack asked");
1650 else if (auto e = flow_error(b); not e.empty())
1651 check.fail(s, at + e);
1652 put_initial_flow(b, false);
1653 }
1654
1655 auto check_semi = [&] (Check & check, const SemiPath<Net> & sp, Node * from,
1656 Node * to, bool expected)
1657 {
1658 check.run();
1659 if (std::get<0>(sp) != expected)
1660 check.fail(s, at + (expected ? "finds no semi-path" : "finds a semi-path"));
1661 else if (expected)
1662 if (auto e = semi_path_error(b, std::get<2>(sp), from, to, std::get<1>(sp),
1663 slack); not e.empty())
1664 check.fail(s, at + e);
1665 };
1666 check_semi(semi_dfs, Find_Aumenting_Path_DFS<Net>(b.net)(slack), u, v, want);
1667 check_semi(semi_bfs, Find_Aumenting_Path_BFS<Net>(b.net)(slack), u, v, want);
1668 check_semi(semi_free, find_aumenting_semi_path_dfs(b.net, slack), u, v, want);
1669 check_semi(semi_free, find_aumenting_semi_path_bfs(b.net, slack), u, v, want);
1670 check_semi(dec, find_decrementing_path_dfs(b.net, slack), v, u, want_back);
1671 check_semi(dec, find_decrementing_path_bfs(b.net, slack), v, u, want_back);
1672 check_semi(dec_member, Find_Aumenting_Path_DFS<Net>(b.net).find_dec_path(slack),
1673 v, u, want_back);
1674
1675 semi_fill.run();
1676 {
1678 const F got = Find_Aumenting_Path_BFS<Net>(b.net).semi_path(u, v, sp, slack);
1679 if (want == sp.is_empty())
1680 semi_fill.fail(s, at + (want ? "finds no semi-path" : "finds a semi-path"));
1681 else if (want)
1682 {
1683 if (auto e = semi_path_error(b, sp, u, v, got, slack); not e.empty())
1684 semi_fill.fail(s, at + e);
1685 }
1686 else if (got != F{0})
1687 semi_fill.fail(s, at + "returns " + text(got) + " without a semi-path");
1688 }
1689
1690 // Adding the slack of a semi-path and taking it away leaves
1691 // the flow as it was
1692 if (want)
1693 {
1694 round.run();
1695 const auto before = b.flows();
1696 const F value = b.value();
1697 const auto sp = find_aumenting_semi_path_bfs(b.net, slack);
1698 increase_flow(b.net, std::get<2>(sp), std::get<1>(sp));
1699 if (auto e = flow_error(b); not e.empty())
1700 round.fail(s, at + "after increase_flow(): " + e);
1701 else if (b.value() != value + std::get<1>(sp))
1702 round.fail(s, at + "the value does not grow by the slack");
1703 decrease_flow(b.net, std::get<2>(sp), std::get<1>(sp));
1704 if (b.flows() != before)
1705 round.fail(s, at + "decrease_flow() does not undo increase_flow()");
1706 }
1707 }
1708 }
1709 });
1710 for (const Check * c : {&dfs, &bfs, &free_dfs, &free_bfs, &increase, &semi_dfs, &semi_bfs,
1711 &semi_free, &semi_fill, &dec, &dec_member, &round})
1712 c->expect();
1713}
1714
1715// ======================================================================
1716// Super sources and sinks
1717
1718namespace
1719{
1721 template <class Net>
1722 std::set<int> numbers_of(const DynSetTree<typename Net::Node *> & set)
1723 {
1724 std::set<int> r;
1725 for (auto it = set.get_it(); it.has_curr(); it.next_ne())
1726 r.insert(it.get_curr()->get_info());
1727 return r;
1728 }
1729
1731 std::pair<std::set<int>, std::set<int>> ends_by_arcs(const Spec & s)
1732 {
1733 std::set<int> sources, sinks;
1734 for (int x = 0; x < s.n; ++x)
1735 {
1736 sources.insert(x);
1737 sinks.insert(x);
1738 }
1739 for (const auto & a : s.arcs)
1740 {
1741 sources.erase(a[1]);
1742 sinks.erase(a[0]);
1743 }
1744 return {sources, sinks};
1745 }
1746
1750 long long super_max_flow(const Spec & s)
1751 {
1752 auto [sources, sinks] = ends_by_arcs(s);
1753 Spec x = s;
1754 int from = sources.size() == 1 ? *sources.begin() : x.n++;
1755 int to = sinks.size() == 1 ? *sinks.begin() : x.n++;
1756 if (sources.size() > 1)
1757 for (int v : sources)
1758 {
1759 long long out = 0;
1760 for (size_t i = 0; i < s.arcs.size(); ++i)
1761 out += s.arcs[i][0] == v ? s.w[i] : 0;
1762 x.arcs.push_back({from, v});
1763 x.w.push_back(out);
1764 }
1765 if (sinks.size() > 1)
1766 for (int v : sinks)
1767 {
1768 long long in = 0;
1769 for (size_t i = 0; i < s.arcs.size(); ++i)
1770 in += s.arcs[i][1] == v ? s.w[i] : 0;
1771 // The super source may have an arc to v
1772 for (size_t i = s.arcs.size(); i < x.arcs.size(); ++i)
1773 in += x.arcs[i][1] == v ? x.w[i] : 0;
1774 x.arcs.push_back({v, to});
1775 x.w.push_back(in);
1776 }
1777 return max_flow_units(x, from, to);
1778 }
1779}
1780
1781TYPED_TEST(ExhaustiveMaxFlow, SuperSourcesAndSinksMatchTheOracle)
1782{
1783 using Net = TypeParam;
1784 Check make("make_super_nodes(), and a maximum flow");
1785 Check refuse("make_super_source() and make_super_sink() without sources or sinks");
1786 Check unmake("unmake_super_nodes()");
1787 Check one_by_one("make_super_source() and make_super_sink()");
1788
1789 structural_specs(max_flow_domain<Net>())([&] (const Spec & s)
1790 {
1791 const auto [sources, sinks] = ends_by_arcs(s);
1792 if (sources.empty() or sinks.empty())
1793 {
1794 refuse.run();
1795 Built_Net<Net> b(s);
1796 try
1797 {
1798 b.net.make_super_nodes();
1799 refuse.fail(s, "does not throw");
1800 }
1801 catch (const std::domain_error &) {}
1802 catch (const std::exception & e)
1803 {
1804 refuse.fail(s, std::string("throws ") + e.what());
1805 }
1806 return;
1807 }
1808
1809 make.run();
1810 Built_Net<Net> b(s);
1811 try
1812 {
1813 b.net.make_super_nodes();
1814 }
1815 catch (const std::exception & e)
1816 {
1817 make.fail(s, std::string("throws ") + e.what());
1818 return;
1819 }
1820 const size_t added = (sources.size() > 1) + (sinks.size() > 1);
1821 if (b.net.get_num_nodes() != size_t(s.n) + added or not b.net.is_single_source()
1822 or not b.net.is_single_sink() or b.net.with_super_source != (sources.size() > 1)
1823 or b.net.with_super_sink != (sinks.size() > 1))
1824 {
1825 make.fail(s, "a wrong network: " + std::to_string(b.net.get_num_nodes()) + " nodes, "
1826 + std::to_string(b.net.get_src_nodes().size()) + " sources, "
1827 + std::to_string(b.net.get_sink_nodes().size()) + " sinks");
1828 return;
1829 }
1830 b.src = b.net.get_source();
1831 b.snk = b.net.get_sink();
1832 for (typename Net::Arc_Iterator it(b.net); it.has_curr(); it.next_ne())
1833 if (b.number(it.get_curr()) < 0)
1834 b.arcs.push_back(it.get_curr());
1835 const auto got = edmonds_karp_maximum_flow(b.net);
1836 if (auto e = max_flow_error(b, got, super_max_flow(s)); not e.empty())
1837 make.fail(s, e);
1838
1839 unmake.run();
1840 std::vector<typename Net::Flow_Type> spec_flows;
1841 for (size_t i = 0; i < b.spec_arcs; ++i)
1842 spec_flows.push_back(b.arcs[i]->flow);
1843 b.net.unmake_super_nodes();
1844 bool same_flows = true;
1845 for (size_t i = 0; i < b.spec_arcs; ++i)
1846 same_flows = same_flows and b.arcs[i]->flow == spec_flows[i];
1847 if (b.net.get_num_nodes() != size_t(s.n) or b.net.get_num_arcs() != s.num_arcs()
1848 or numbers_of<Net>(b.net.get_src_nodes()) != sources
1849 or numbers_of<Net>(b.net.get_sink_nodes()) != sinks or b.net.with_super_source
1850 or b.net.with_super_sink or not same_flows)
1851 unmake.fail(s, "the network is not as it was");
1852
1853 // One by one, the same
1854 one_by_one.run();
1855 Built_Net<Net> c(s);
1856 c.net.make_super_source();
1857 c.net.make_super_sink();
1858 if (not c.net.is_single_source() or not c.net.is_single_sink())
1859 one_by_one.fail(s, "more than one source or sink");
1860 else
1861 {
1862 c.net.unmake_super_sink();
1863 c.net.unmake_super_source();
1864 if (numbers_of<Net>(c.net.get_src_nodes()) != sources
1865 or numbers_of<Net>(c.net.get_sink_nodes()) != sinks
1866 or c.net.get_num_nodes() != size_t(s.n))
1867 one_by_one.fail(s, "the network is not as it was");
1868 }
1869 });
1870 make.expect();
1871 refuse.expect();
1872 unmake.expect();
1873 one_by_one.expect();
1874}
1875
1876// ======================================================================
1877// Minimum costs
1878
1879namespace
1880{
1883 template <typename F>
1884 bool is_cost(F x, long long units2)
1885 {
1886 return x * F(Units_Per_One<F>) * F(Units_Per_One<F>) == F(units2);
1887 }
1888
1889 template <typename F>
1890 F cost_amount(long long units2)
1891 {
1892 return F(units2) / F(Units_Per_One<F> * Units_Per_One<F>);
1893 }
1894
1898 std::pair<long long, long long> brute_min_cost(const Spec & s,
1899 const std::vector<long long> & cost, int a, int z)
1900 {
1901 std::vector<long long> f(s.arcs.size(), 0);
1902 long long best_value = -1, best_cost = 0;
1903 while (true)
1904 {
1905 std::vector<long long> balance(size_t(s.n), 0);
1906 for (size_t i = 0; i < f.size(); ++i)
1907 {
1908 balance[size_t(s.arcs[i][0])] -= f[i];
1909 balance[size_t(s.arcs[i][1])] += f[i];
1910 }
1911 bool kept = -balance[size_t(a)] >= 0;
1912 for (int x = 0; x < s.n and kept; ++x)
1913 kept = x == a or x == z or balance[size_t(x)] == 0;
1914 if (kept)
1915 {
1916 long long c = 0;
1917 for (size_t i = 0; i < f.size(); ++i)
1918 c += f[i] * cost[i];
1919 const long long value = -balance[size_t(a)];
1920 if (value > best_value or (value == best_value and c < best_cost))
1921 {
1922 best_value = value;
1923 best_cost = c;
1924 }
1925 }
1926 size_t i = 0;
1927 while (i < f.size() and ++f[i] > s.w[i])
1928 f[i++] = 0;
1929 if (i == f.size())
1930 return {best_value, best_cost};
1931 }
1932 }
1933
1937 std::pair<long long, long long> ssp_min_cost(const Spec & s, const std::vector<long long> & cost,
1938 int a, int z)
1939 {
1940 struct R { int u, v; long long cap, cost; size_t back; };
1941 std::vector<R> r;
1942 for (size_t i = 0; i < s.arcs.size(); ++i)
1943 if (s.arcs[i][0] != s.arcs[i][1])
1944 {
1945 r.push_back({s.arcs[i][0], s.arcs[i][1], s.w[i], cost[i], r.size() + 1});
1946 r.push_back({s.arcs[i][1], s.arcs[i][0], 0, -cost[i], r.size() - 1});
1947 }
1948 long long value = 0, total = 0;
1949 while (true)
1950 {
1951 std::vector<long long> d(size_t(s.n), oracle::Inf);
1952 std::vector<size_t> by(size_t(s.n), r.size());
1953 d[size_t(a)] = 0;
1954 for (int round = 0; round < s.n; ++round)
1955 for (size_t k = 0; k < r.size(); ++k)
1956 if (r[k].cap > 0 and d[size_t(r[k].u)] != oracle::Inf
1957 and d[size_t(r[k].u)] + r[k].cost < d[size_t(r[k].v)])
1958 {
1959 d[size_t(r[k].v)] = d[size_t(r[k].u)] + r[k].cost;
1960 by[size_t(r[k].v)] = k;
1961 }
1962 if (d[size_t(z)] == oracle::Inf)
1963 return {value, total};
1964 long long neck = oracle::Inf;
1965 for (int v = z; v != a; v = r[by[size_t(v)]].u)
1966 neck = std::min(neck, r[by[size_t(v)]].cap);
1967 for (int v = z; v != a; v = r[by[size_t(v)]].u)
1968 {
1969 r[by[size_t(v)]].cap -= neck;
1970 r[r[by[size_t(v)]].back].cap += neck;
1971 }
1972 value += neck;
1973 total += neck * d[size_t(z)];
1974 }
1975 }
1976
1981 template <class Net>
1982 struct Cost_Solver
1983 {
1984 using F = typename Net::Flow_Type;
1985 std::string name;
1986 std::pair<F, F> (*run)(Net &);
1987 std::pair<F, F> (*again)(Net &);
1988 bool returns = false;
1989 };
1990
1993 template <class Net>
1994 std::vector<Cost_Solver<Net>> cost_solvers()
1995 {
1996 using F = typename Net::Flow_Type;
1997 using P = std::pair<F, F>;
1998 return {
1999 {"max_flow_min_cost_by_cycle_canceling()",
2000 [] (Net & n) { max_flow_min_cost_by_cycle_canceling(n); return P(); },
2001 [] (Net & n) { Max_Flow_Min_Cost_By_Cycle_Canceling<Net>()(n); return P(); }},
2002 {"max_flow_min_cost_by_cycle_canceling<Edmonds_Karp_Maximum_Flow>()",
2003 [] (Net & n) { max_flow_min_cost_by_cycle_canceling<Net, Edmonds_Karp_Maximum_Flow>(n);
2004 return P(); },
2006 return P(); }},
2007 {"max_flow_min_cost_by_network_simplex()",
2008 [] (Net & n) { max_flow_min_cost_by_network_simplex(n); return P(); },
2009 [] (Net & n) { Max_Flow_Min_Cost_By_Network_Simplex<Net>()(n); return P(); }},
2010 {"max_flow_min_cost_by_network_simplex<Dinic_Maximum_Flow>()",
2011 [] (Net & n) { max_flow_min_cost_by_network_simplex<Net, Dinic_Maximum_Flow>(n);
2012 return P(); },
2014 return P(); }},
2015 {"successive_shortest_paths()", [] (Net & n) { return successive_shortest_paths(n); },
2016 [] (Net & n) { return Successive_Shortest_Paths<Net>()(n); }, true}};
2017 }
2018
2019 bool is_cycle_canceling(size_t i) { return i <= 1; }
2020 bool is_ssp(size_t i) { return i == 4; }
2021
2025 template <class Net>
2026 std::string min_cost_error(const Built_Net<Net> & b, const Cost_Solver<Net> & solver,
2027 const std::pair<typename Net::Flow_Type,
2028 typename Net::Flow_Type> & got,
2029 std::pair<long long, long long> want)
2030 {
2031 using F = typename Net::Flow_Type;
2032 if (auto e = flow_error(b); not e.empty())
2033 return e;
2034 if (not is_amount(b.value(), want.first))
2035 return "the flow is " + text(b.value()) + ", not " + text(amount<F>(want.first));
2036 if (not is_cost(b.net.flow_cost(), want.second))
2037 return "the cost is " + text(b.net.flow_cost()) + ", not "
2038 + text(cost_amount<F>(want.second));
2039 if (solver.returns and (got.first != b.value() or got.second != b.net.flow_cost()))
2040 return "returns " + text(got.first) + " and " + text(got.second) + " for a flow of "
2041 + text(b.value()) + " and cost " + text(b.net.flow_cost());
2042 return "";
2043 }
2044
2046 std::string costs_text(const std::vector<long long> & cost)
2047 {
2048 std::string r = "costs {";
2049 for (size_t i = 0; i < cost.size(); ++i)
2050 r += (i == 0 ? "" : " ") + std::to_string(cost[i]);
2051 return r + "}: ";
2052 }
2053
2058 template <class Net>
2059 bool negative_residual_cycle(const Built_Net<Net> & b)
2060 {
2061 using F = typename Net::Flow_Type;
2062 std::map<typename Net::Node *, size_t> index;
2063 for (Node_Iterator<Net> it(b.net); it.has_curr(); it.next_ne())
2064 index.emplace(it.get_curr(), index.size());
2065 struct Residual
2066 {
2067 size_t u, v;
2068 F cost;
2069 };
2070 std::vector<Residual> r;
2071 for (Arc_Iterator<Net> it(b.net); it.has_curr(); it.next_ne())
2072 {
2073 auto a = it.get_curr();
2074 const size_t u = index[b.net.get_src_node(a)], v = index[b.net.get_tgt_node(a)];
2075 if (a->flow < a->cap)
2076 r.push_back({u, v, a->cost});
2077 if (a->flow > F{0})
2078 r.push_back({v, u, -a->cost});
2079 }
2080 // Whether the distances from every node still change after as many
2081 // passes as nodes
2082 const size_t n = index.size();
2083 std::vector<F> d(n, F{0});
2084 for (size_t pass = 0; pass < n; ++pass)
2085 {
2086 bool changed = false;
2087 for (const auto & e : r)
2088 if (d[e.u] + e.cost < d[e.v])
2089 {
2090 d[e.v] = d[e.u] + e.cost;
2091 changed = true;
2092 }
2093 if (not changed)
2094 return false;
2095 }
2096 return true;
2097 }
2098
2101 std::vector<long long> structural_costs(const Spec & s)
2102 {
2103 std::vector<long long> c;
2104 for (size_t i = 0; i < s.arcs.size(); ++i)
2105 c.push_back(std::vector<long long>{2, 0, 1}[i % 3]);
2106 return c;
2107 }
2108
2115 template <class Net, class Oracle>
2116 void check_min_costs(const Spec & s, const std::vector<long long> & cost, Oracle min_cost,
2117 Family_Checks & first, Family_Checks & second, bool twice = true,
2118 int only = -1, bool variants = true)
2119 {
2120 const auto solvers = cost_solvers<Net>();
2121 for (auto [a, z] : ends_of(s))
2122 {
2123 if (a == z)
2124 continue;
2125 Built_Net<Net> b(s, s.w, cost);
2126 b.pin(a, z);
2127 const auto want = min_cost(s, cost, a, z);
2128 for (size_t i = 0; i < solvers.size(); ++i)
2129 {
2130 // only: 0 for the cycle canceling, 1 for the others
2131 if (only >= 0 and is_cycle_canceling(i) != (only == 0))
2132 continue;
2133 if (not variants and (i == 1 or i == 3))
2134 continue;
2135 Check * check = first.of(i, 0);
2136 b.net.reset();
2137 check->run();
2138 // The successive shortest paths refuse a network with a cycle of
2139 // negative cost, which the cheapest maximum flow saturates
2140 if (is_ssp(i) and negative_residual_cycle(b))
2141 {
2142 const auto before = b.flows();
2143 try
2144 {
2145 solvers[i].run(b.net);
2146 check->fail(s, where(b, a, z) + costs_text(cost)
2147 + "a cycle of negative cost: does not throw");
2148 }
2149 catch (const std::domain_error &)
2150 {
2151 if (b.flows() != before)
2152 check->fail(s, where(b, a, z) + costs_text(cost)
2153 + "throws, and the flows changed");
2154 }
2155 catch (const std::exception & e)
2156 {
2157 check->fail(s, where(b, a, z) + costs_text(cost) + "throws " + e.what());
2158 }
2159 continue;
2160 }
2161 try
2162 {
2163 const auto got = solvers[i].run(b.net);
2164 if (auto e = min_cost_error(b, solvers[i], got, want); not e.empty())
2165 {
2166 check->fail(s, where(b, a, z) + costs_text(cost) + e);
2167 continue;
2168 }
2169 if (not twice)
2170 continue;
2171 Check * again = second.of(i, 0);
2172 again->run();
2173 const auto got2 = solvers[i].again(b.net);
2174 if (auto e = min_cost_error(b, solvers[i], got2, want); not e.empty())
2175 again->fail(s, where(b, a, z) + costs_text(cost) + "the second run: " + e);
2176 }
2177 catch (const std::exception & e)
2178 {
2179 check->fail(s, where(b, a, z) + costs_text(cost) + "throws " + e.what());
2180 }
2181 }
2182 }
2183 }
2184
2187 template <class Net>
2188 struct Cost_Checks
2189 {
2190 Family_Checks first;
2191 Family_Checks second;
2192
2193 Cost_Checks()
2194 : first(cost_solvers<Net>()),
2195 second(second_names())
2196 {}
2197
2198 static std::vector<Solver<Net>> second_names()
2199 {
2200 std::vector<Solver<Net>> r;
2201 for (const auto & s : cost_solvers<Net>())
2202 r.push_back({s.name + ", then its functor", nullptr});
2203 return r;
2204 }
2205
2206 void expect() const
2207 {
2208 first.expect();
2209 second.expect();
2210 }
2211 };
2212
2220 std::vector<std::pair<Spec, std::vector<long long>>> simplex_witnesses()
2221 {
2222 std::vector<std::pair<Spec, std::vector<long long>>> r;
2223 Spec s;
2224 s.n = 3;
2225 s.arcs = {{2, 0}, {1, 2}, {0, 1}, {0, 1}};
2226 s.w = {1, 2, 3, 4};
2227 r.push_back({s, {2, 0, 1, 2}});
2228 s.n = 6;
2229 s.arcs = {{3, 2}, {4, 3}, {3, 0}, {5, 0}, {0, 4}, {4, 3}, {1, 4}};
2230 s.w = {0, 1, 0, 0, 1, 1, 0};
2231 r.push_back({s, {0, 0, 0, 0, 0, 1, 0}});
2232 s.arcs = {{1, 4}, {3, 0}, {1, 4}, {2, 1}, {4, 3}, {4, 2}};
2233 s.w = {1, 1, 1, 1, 1, 0};
2234 r.push_back({s, {1, 0, 0, 0, 0, 0}});
2235 return r;
2236 }
2237}
2238
2239template <class Net>
2240class ExhaustiveMinCost : public ::testing::Test {};
2241
2244 ::testing::Types<Net_Cost_Graph<Net_Cost_Node<int>, Net_Cost_Arc<Empty_Class, long>>,
2246
2248
2249TYPED_TEST(ExhaustiveMinCost, CycleCancelingMatchesTheOracle)
2250{
2251 using Net = TypeParam;
2252 Cost_Checks<Net> checks;
2253 small_structural_specs<Net>()([&] (const Spec & s)
2254 {
2255 check_min_costs<Net>(s, structural_costs(s), brute_min_cost, checks.first, checks.second,
2256 true, 0);
2257 });
2258 checks.expect();
2259}
2260
2261TYPED_TEST(ExhaustiveMinCost, SimplexAndShortestPathsMatchTheOracle)
2262{
2263 using Net = TypeParam;
2264 Cost_Checks<Net> checks;
2265 for (const auto & [s, cost] : simplex_witnesses())
2266 check_min_costs<Net>(s, cost, ssp_min_cost, checks.first, checks.second, true, 1);
2267 small_structural_specs<Net>()([&] (const Spec & s)
2268 {
2269 check_min_costs<Net>(s, structural_costs(s), brute_min_cost, checks.first, checks.second,
2270 true, 1);
2271 });
2272 checks.expect();
2273}
2274
2275TYPED_TEST(ExhaustiveMinCost, CheapestMaxFlowsTakeEveryCost)
2276{
2277 using Net = TypeParam;
2278 Cost_Checks<Net> checks;
2279 for (const auto & [s, cost] : simplex_witnesses())
2280 check_min_costs<Net>(s, cost, ssp_min_cost, checks.first, checks.second, false);
2281 // Unit capacities, and every assignment of the costs 0 and 2, once
2282 for_each_spec(class_domain(), true, [&] (const Spec & s)
2283 {
2284 const Spec unit = with_w(s, std::vector<long long>(s.arcs.size(), 1));
2285 for_each_assignment(s, {0, 2}, [&] (const Spec & c)
2286 {
2287 check_min_costs<Net>(unit, c.w, brute_min_cost, checks.first, checks.second, false,
2288 -1, false);
2289 });
2290 });
2291 checks.expect();
2292}
2293
2294TYPED_TEST(ExhaustiveMinCost, CheapestMaxFlowsTakeNegativeCosts)
2295{
2296 // Unit capacities, and every assignment of the costs -1 and 2, once: the
2297 // cheapest maximum flow saturates the cycles of negative cost, also
2298 // those apart from the source, which the cycle canceling cancels and the
2299 // network simplex takes as pivots; the successive shortest paths refuse
2300 // a network with one
2301 using Net = TypeParam;
2302 Cost_Checks<Net> checks;
2303 for_each_spec(class_domain(), true, [&] (const Spec & s)
2304 {
2305 const Spec unit = with_w(s, std::vector<long long>(s.arcs.size(), 1));
2306 for_each_assignment(s, {-1, 2}, [&] (const Spec & c)
2307 {
2308 check_min_costs<Net>(unit, c.w, brute_min_cost, checks.first, checks.second, false,
2309 -1, false);
2310 });
2311 });
2312 checks.expect();
2313}
2314
2315TYPED_TEST(ExhaustiveMinCost, CheapestMaxFlowsOnRandomNetworks)
2316{
2317 using Net = TypeParam;
2318 Cost_Checks<Net> checks;
2319
2320 for (const auto & [s, cost] : simplex_witnesses())
2321 check_min_costs<Net>(s, cost, ssp_min_cost, checks.first, checks.second);
2322
2323 std::mt19937 rng(seed(21));
2324 for (int k = 0; k < (heavy() ? 200 : 20); ++k)
2325 {
2326 Spec s = random_spec(rng, 6 + int(rng() % 3), 8 + int(rng() % 9), true);
2327 random_weights(rng, s, 0, 3);
2328 Spec c = s;
2329 random_weights(rng, c, 0, 5);
2330 check_min_costs<Net>(s, c.w, ssp_min_cost, checks.first, checks.second, true, -1, false);
2331 }
2332 checks.expect();
2333}
2334
2335TYPED_TEST(ExhaustiveMinCost, CheapestMaxFlowsFromAFlowAlreadyThere)
2336{
2337 using Net = TypeParam;
2338 // Every solver starts from the flow in the network; the successive
2339 // shortest paths need a residual network without cycles of negative
2340 // cost, and refuse it if it has one, wherever it is. The cycle
2341 // canceling and the network simplex run with their first maximum flow
2342 // only, as the others start from a flow in the tests of the maximum
2343 // flows
2344 const auto solvers = cost_solvers<Net>();
2345 Family_Checks checks(solvers);
2346 small_structural_specs<Net>()([&] (const Spec & s)
2347 {
2348 const auto cost = structural_costs(s);
2349 for (auto [a, z] : ends_of(s))
2350 {
2351 if (a == z)
2352 continue;
2353 Built_Net<Net> b(s, s.w, cost);
2354 b.pin(a, z);
2355 const auto want = brute_min_cost(s, cost, a, z);
2356 for (size_t i = 0; i < solvers.size(); ++i)
2357 {
2358 if (i == 1 or i == 3)
2359 continue;
2360 put_initial_flow(b);
2361 const bool refused = is_ssp(i) and negative_residual_cycle(b);
2362 Check * check = checks.of(i, 0);
2363 check->run();
2364 if (refused)
2365 {
2366 const auto before = b.flows();
2367 try
2368 {
2369 solvers[i].run(b.net);
2370 check->fail(s, where(b, a, z) + costs_text(cost)
2371 + "from a flow whose residual network has a cycle of"
2372 " negative cost: does not throw");
2373 }
2374 catch (const std::domain_error &)
2375 {
2376 if (b.flows() != before)
2377 check->fail(s, where(b, a, z) + costs_text(cost)
2378 + "throws, and the flows changed");
2379 }
2380 catch (const std::exception & e)
2381 {
2382 check->fail(s, where(b, a, z) + costs_text(cost) + "throws " + e.what());
2383 }
2384 continue;
2385 }
2386 try
2387 {
2388 const auto got = solvers[i].run(b.net);
2389 if (auto e = min_cost_error(b, solvers[i], got, want); not e.empty())
2390 check->fail(s, where(b, a, z) + costs_text(cost) + "from a flow: " + e);
2391 }
2392 catch (const std::exception & e)
2393 {
2394 check->fail(s, where(b, a, z) + costs_text(cost) + "throws " + e.what());
2395 }
2396 }
2397 }
2398 });
2399 checks.expect();
2400}
2401
2402// ======================================================================
2403// Floating flows: tenths, real numbers and capacities next to each other
2404
2405namespace
2406{
2407 using Double_Net = Net_Graph<Net_Node<int>, Net_Arc<int, double>>;
2408 using Double_Built = Built_Net<Double_Net>;
2409
2411 std::vector<mpq_class> exactly(const std::vector<double> & x)
2412 {
2413 std::vector<mpq_class> r;
2414 for (double v : x)
2415 r.emplace_back(v);
2416 return r;
2417 }
2418
2420 bool near(double x, const mpq_class & q)
2421 {
2422 const double e = q.get_d();
2423 return std::abs(x - e) <= 1e-9 * std::max(1.0, std::abs(e));
2424 }
2425
2427 mpq_class exact_min_cut(const Spec & s, const std::vector<mpq_class> & cap, int a, int z)
2428 {
2429 mpq_class best = -1;
2430 for (unsigned long set = 0; set < (1UL << s.n); ++set)
2431 {
2432 if (((set >> a) & 1UL) == 0 or ((set >> z) & 1UL) != 0)
2433 continue;
2434 mpq_class cut = 0;
2435 for (size_t i = 0; i < s.arcs.size(); ++i)
2436 if (((set >> s.arcs[i][0]) & 1UL) != 0 and ((set >> s.arcs[i][1]) & 1UL) == 0)
2437 cut += cap[i];
2438 if (best < 0 or cut < best)
2439 best = cut;
2440 }
2441 return best;
2442 }
2443
2448 std::string floating_error(const Double_Built & b, double got, const mpq_class & want)
2449 {
2450 if (auto e = flow_error(b, true); not e.empty())
2451 return e;
2452 if (not near(b.value(), want))
2453 return "the flow is " + text(b.value()) + ", not near " + text(want.get_d());
2454 if (not near(got, mpq_class(b.value())))
2455 return "returns " + text(got) + " for a flow of " + text(b.value());
2456 return "";
2457 }
2458
2461 std::vector<Solver<Double_Net>> floating_solvers()
2462 {
2463 return all_solvers<Double_Net>();
2464 }
2465
2469 template <class F>
2470 void for_each_tenths_network(F f)
2471 {
2472 for_each_spec(class_domain(), true, [&] (const Spec & s)
2473 {
2474 for_each_assignment(s, {1, 2, 3}, [&] (const Spec & t)
2475 {
2476 std::vector<double> cap;
2477 for (long long k : t.w)
2478 cap.push_back(double(k) / 10);
2479 f(t, cap);
2480 });
2481 });
2482 }
2483
2484}
2485
2486TEST(ExhaustiveFloatingFlow, TenthsStayNearTheExactMaximum)
2487{
2488 const auto solvers = floating_solvers();
2489 Family_Checks checks(solvers);
2490
2491 for_each_tenths_network([&] (const Spec & s, const std::vector<double> & cap)
2492 {
2493 const auto exact = exactly(cap);
2494 for (auto [a, z] : ends_of(s))
2495 {
2496 Double_Built b(s, cap, Double_Built::Amounts{});
2497 b.pin(a, z);
2498 const mpq_class want = a == z ? mpq_class(0) : exact_max_flow(s, exact, a, z);
2499 for (size_t i = 0; i < solvers.size(); ++i)
2500 {
2501 Check * check = checks.of(i, 0);
2502 b.net.reset();
2503 check->run();
2504 const double got = solvers[i].run(b.net);
2505 if (auto e = floating_error(b, got, want); not e.empty())
2506 check->fail(s, where(b, a, z) + e);
2507 }
2508 }
2509 });
2510 checks.expect();
2511}
2512
2513TEST(ExhaustiveFloatingFlow, CutsDecompositionsAndStatisticsOfTenths)
2514{
2515 Check cut("min_cut<Edmonds_Karp_Maximum_Flow>(), with tenths");
2516 Check stats("compute_flow_statistics(), with tenths");
2517 Check decomposition("decompose_flow(), with tenths");
2518
2519 for_each_tenths_network([&] (const Spec & s, const std::vector<double> & cap)
2520 {
2521 const auto exact = exactly(cap);
2522 for (auto [a, z] : ends_of(s))
2523 {
2524 if (a == z)
2525 continue;
2526 cut.run();
2527 Double_Built b(s, cap, Double_Built::Amounts{});
2528 b.pin(a, z);
2529 Node_Set<Double_Net> vs, vt;
2530 Arc_List<Double_Net> cs, ct;
2531 const double got = min_cut<Double_Net, Edmonds_Karp_Maximum_Flow>(b.net, vs, vt, cs, ct);
2532 if (not near(got, exact_min_cut(s, exact, a, z)))
2533 cut.fail(s, where(b, a, z) + "returns " + text(got));
2534 else if (vs.size() + vt.size() != b.net.get_num_nodes() or not vs.contains(b.src)
2535 or not vt.contains(b.snk))
2536 cut.fail(s, where(b, a, z) + "the sides are not a partition");
2537
2538 stats.run();
2539 const auto st = compute_flow_statistics(b.net);
2540 if (not near(st.total_flow, mpq_class(b.value())))
2541 stats.fail(s, where(b, a, z) + "the flow is " + text(st.total_flow));
2542
2543 // The flow of Edmonds-Karp, which its nodes keep but for rounding
2544 decomposition.run();
2545 const auto before = b.flows();
2546 if (auto e = decomposition_error(b, decompose_flow(b.net), true); not e.empty())
2547 decomposition.fail(s, where(b, a, z) + e);
2548 else if (b.flows() != before)
2549 decomposition.fail(s, where(b, a, z) + "changes the flows");
2550 }
2551 });
2552 for (const Check * c : {&cut, &stats, &decomposition})
2553 c->expect();
2554}
2555
2556namespace
2557{
2563 void check_floating(const std::vector<Solver<Double_Net>> & solvers, Family_Checks & checks,
2564 const Spec & s, const std::vector<double> & cap, const Spec & shown,
2565 const std::vector<std::pair<int, int>> & ends, double scale = 0)
2566 {
2567 const auto exact = exactly(cap);
2568 for (auto [a, z] : ends)
2569 {
2570 Double_Built b(s, cap, Double_Built::Amounts{});
2571 b.pin(a, z);
2572 const mpq_class want = a == z ? mpq_class(0) : exact_max_flow(s, exact, a, z);
2573 for (size_t i = 0; i < solvers.size(); ++i)
2574 {
2575 Check * check = checks.of(i, 0);
2576 b.net.reset();
2577 check->run();
2578 const double got = solvers[i].run(b.net);
2579 std::string e;
2580 if (scale == 0)
2581 e = floating_error(b, got, want);
2582 else if (e = flow_error(b, true); e.empty())
2583 {
2584 if (std::abs(b.value() - want.get_d()) > scale)
2585 e = "the flow is " + text(b.value()) + ", not within " + text(scale) + " of "
2586 + text(want.get_d());
2587 else if (got != b.value())
2588 e = "returns " + text(got) + " for a flow of " + text(b.value());
2589 }
2590 if (not e.empty())
2591 check->fail(shown, where(b, a, z) + e);
2592 }
2593 }
2594 }
2595}
2596
2597TEST(ExhaustiveFloatingFlow, RealsStayNearTheExactMaximum)
2598{
2599 const auto solvers = floating_solvers();
2600 Family_Checks checks(solvers);
2601 auto check_network = [&] (const Spec & s, const std::vector<double> & cap, const Spec & shown,
2602 const std::vector<std::pair<int, int>> & ends)
2603 {
2604 check_floating(solvers, checks, s, cap, shown, ends);
2605 };
2606
2607 // s->a (f), a->t (c), s->b (4) and b->a (4), for tenths f < c: the second
2608 // path adds to a->t its slack c - f, whose sum with f may round above c
2609 Spec two;
2610 two.n = 4;
2611 two.arcs = {{0, 1}, {1, 3}, {0, 2}, {2, 1}};
2612 for (int f = 1; f < 40; ++f)
2613 for (int c = f + 1; c < 40; ++c)
2614 check_network(two, {f / 10.0, c / 10.0, 4.0, 4.0}, with_w(two, {f, c, 40, 40}),
2615 {{0, 3}});
2616
2617 // The smallest networks found, of the random ones, where HLPP left a
2618 // residue of rounding beside a dead end, where HLPP and the preflow with
2619 // a queue left one with a maximum flow of 0 through added ends, and
2620 // where the random order failed the assertion of a push
2621 Spec dead;
2622 dead.n = 7;
2623 dead.arcs = {{1, 2}, {0, 4}, {1, 4}, {0, 4}, {1, 0}, {0, 6}, {3, 4}, {1, 4}};
2624 check_network(dead, {7.9158743311190074, 1.9230814882856702, 7.0493412600464511,
2625 1.1462173944341092, 1.9342502520033173, 7.6346719763601429,
2626 7.9868164808084732, 1.7200262856274111}, dead, {{1, 2}});
2627 Spec none;
2628 none.n = 6;
2629 none.arcs = {{3, 5}, {1, 5}, {3, 4}, {2, 2}, {4, 1}, {4, 2}};
2630 check_network(none, {8.4754518873571989, 0.033883492579154795, 2.8544016310908091,
2631 5.348472093612588, 7.6055185660473672, 7.6209729593968252}, none,
2632 {{1, 0}});
2633 none.n = 8;
2634 none.arcs = {{3, 0}, {1, 5}, {3, 4}, {0, 3}, {1, 6}, {6, 0}, {0, 1}, {1, 0}, {4, 5}};
2635 check_network(none, {5.8762413240161377, 9.6866242843038588, 9.8716668953306925,
2636 6.9485217634542904, 4.5520971709691489, 0.56788063415950651,
2637 6.8545648904471443, 5.3250521674031983, 3.7891499589133839}, none,
2638 {{1, 7}});
2639 Spec order;
2640 order.n = 7;
2641 order.arcs = {{5, 3}, {3, 4}, {3, 0}, {0, 0}, {4, 4}, {5, 2}, {0, 6}, {6, 1}, {1, 2}, {3, 0},
2642 {4, 5}, {4, 3}, {6, 3}, {3, 4}, {0, 5}};
2643 check_network(order, {6.7274672427936437, 0.67896405431885454, 8.3171002335098816,
2644 3.142334997783744, 9.7484939902099423, 4.1710752481577531,
2645 0.9841479965002714, 8.4695910615758159, 0.16659269185525827,
2646 8.2594276634024109, 0.081880796394979249, 3.4538564369078739,
2647 2.9875620372348917, 4.8549585581071586, 9.0570840433200761},
2648 order, {{4, 1}});
2649
2650 // Random real numbers from 0.01 to 10
2651 std::mt19937 rng(seed(31));
2652 std::uniform_real_distribution<double> real(0.01, 10.0);
2653 for (int k = 0; k < (heavy() ? 400 : 40); ++k)
2654 {
2655 const Spec s = random_spec(rng, 6 + int(rng() % 3), 8 + int(rng() % 9), true);
2656 std::vector<double> cap;
2657 for (size_t i = 0; i < s.arcs.size(); ++i)
2658 cap.push_back(real(rng));
2659 check_network(s, cap, s, ends_of(s));
2660 }
2661 checks.expect();
2662}
2663
2664TEST(ExhaustiveFloatingFlow, TenthsOnRandomNetworksStayNearTheExactMaximum)
2665{
2666 const auto solvers = floating_solvers();
2667 Family_Checks checks(solvers);
2668 auto tenths_of = [] (const std::vector<long long> & w)
2669 {
2670 std::vector<double> cap;
2671 for (long long k : w)
2672 cap.push_back(double(k) / 10);
2673 return cap;
2674 };
2675
2676 // The smallest networks found where Ford-Fulkerson broke the balance of
2677 // the nodes: from 4 to 2, by a path through a residue of 2.8e-16 below
2678 // the capacity 2.9 of 0->2; and from 1 to 14, by one through a residue of
2679 // 3.6e-16 below the capacity 0.1 of 6->20, which a slack of the arcs of
2680 // capacity 2 left there
2681 Spec small;
2682 small.n = 6;
2683 small.arcs = {{1, 3}, {3, 5}, {5, 2}, {4, 3}, {0, 2}, {4, 0}, {0, 1}, {5, 0}, {4, 0}, {0, 1},
2684 {4, 5}};
2685 small.w = {20, 20, 30, 20, 29, 2, 1, 10, 27, 19, 10};
2686 check_floating(solvers, checks, small, tenths_of(small.w), small, {{4, 2}});
2687 Spec big;
2688 big.n = 21;
2689 big.arcs = {{0, 18}, {7, 10}, {20, 4}, {7, 16}, {19, 16}, {16, 17}, {4, 3}, {10, 4}, {18, 0},
2690 {9, 6}, {11, 20}, {5, 14}, {6, 20}, {12, 13}, {2, 14}, {3, 14}, {15, 19}, {3, 15},
2691 {4, 20}, {1, 20}, {5, 7}, {6, 12}, {12, 19}, {1, 6}, {17, 3}, {16, 5}, {16, 13},
2692 {2, 14}, {6, 8}, {17, 8}, {16, 6}, {3, 17}, {12, 11}, {19, 20}, {1, 5}, {11, 19},
2693 {1, 16}, {16, 12}, {15, 9}, {8, 2}, {13, 9}};
2694 big.w = {0, 3, 7, 0, 1, 2, 7, 3, 0, 2, 6, 20, 1, 0, 10, 8, 1, 2, 0, 0, 3, 5, 0, 16, 1, 11, 1, 1,
2695 10, 5, 9, 5, 7, 1, 9, 1, 14, 7, 2, 11, 1};
2696 check_floating(solvers, checks, big, tenths_of(big.w), big, {{1, 14}});
2697
2698 // Random networks, with capacities from 0.1 to 4, in tenths
2699 std::mt19937 rng(seed(32));
2700 for (int k = 0; k < (heavy() ? 400 : 40); ++k)
2701 {
2702 Spec s = random_spec(rng, 6 + int(rng() % 3), 8 + int(rng() % 9), true);
2703 random_weights(rng, s, 1, 40);
2704 check_floating(solvers, checks, s, tenths_of(s.w), s, ends_of(s));
2705 }
2706 checks.expect();
2707}
2708
2709namespace
2710{
2712 using Double_Cost_Built = Built_Net<Double_Cost_Net>;
2713
2715 mpq_class ratio(long long x, long d)
2716 {
2717 mpq_class q(long{x});
2718 q /= d;
2719 return q;
2720 }
2721
2730 template <class Oracle>
2731 void check_tenths_min_costs(const std::vector<Cost_Solver<Double_Cost_Net>> & solvers,
2732 Family_Checks & checks, const Spec & s,
2733 const std::vector<long long> & cap,
2734 const std::vector<long long> & cost,
2735 const std::vector<std::pair<int, int>> & ends, Oracle min_cost)
2736 {
2737 const Spec tenths = with_w(s, cap);
2738 std::vector<double> amounts;
2739 for (long long c : cap)
2740 amounts.push_back(double(c) / 10);
2741 for (auto [a, z] : ends)
2742 {
2743 if (a == z)
2744 continue;
2745 Double_Cost_Built b(s, amounts, Double_Cost_Built::Amounts{});
2746 for (size_t i = 0; i < cost.size(); ++i)
2747 b.arcs[i]->cost = double(cost[i]) / 10;
2748 b.pin(a, z);
2749 const auto [value, total] = min_cost(tenths, cost, a, z);
2750 for (size_t i = 0; i < solvers.size(); ++i)
2751 {
2752 Check * check = checks.of(i, 0);
2753 b.net.reset();
2754 check->run();
2755 const bool refused = is_ssp(i) and negative_residual_cycle(b);
2756 std::string e;
2757 try
2758 {
2759 const auto got = solvers[i].run(b.net);
2760 if (refused)
2761 e = "a cycle of negative cost: does not throw";
2762 else if (e = flow_error(b, true); not e.empty())
2763 ;
2764 else if (not near(b.value(), ratio(value, 10)))
2765 e = "the flow is " + text(b.value()) + ", not near "
2766 + text(ratio(value, 10).get_d());
2767 else if (not near(b.net.flow_cost(), ratio(total, 100)))
2768 e = "the cost is " + text(b.net.flow_cost()) + ", not near "
2769 + text(ratio(total, 100).get_d());
2770 else if (solvers[i].returns
2771 and (got.first != b.value() or got.second != b.net.flow_cost()))
2772 e = "returns " + text(got.first) + " and " + text(got.second)
2773 + " for a flow of " + text(b.value()) + " and cost "
2774 + text(b.net.flow_cost());
2775 }
2776 catch (const std::domain_error & x)
2777 {
2778 if (not refused)
2779 e = std::string("throws ") + x.what();
2780 }
2781 catch (const std::exception & x)
2782 {
2783 e = std::string("throws ") + x.what();
2784 }
2785 if (not e.empty())
2786 check->fail(tenths, where(b, a, z) + costs_text(cost) + e);
2787 }
2788 }
2789 }
2790}
2791
2792TEST(ExhaustiveFloatingFlow, CheapestMaxFlowsOfTenths)
2793{
2794 const auto solvers = cost_solvers<Double_Cost_Net>();
2795 Family_Checks checks(solvers);
2796
2797 // The smallest network found where the network simplex left an arc of
2798 // capacity 2.9 with 2.9000000000000004, and then the cost -0.1, for the
2799 // least -0.8 of a flow of 1: from 0 to 3; the costs, in tenths, are
2800 // integers
2801 Spec ulp;
2802 ulp.n = 5;
2803 ulp.arcs = {{1, 4}, {2, 3}, {4, 2}, {2, 4}, {0, 1}, {0, 2}, {0, 1}};
2804 check_tenths_min_costs(solvers, checks, ulp, {9, 10, 29, 22, 26, 5, 7},
2805 {20, 30, -20, 0, 0, 20, 10}, {{0, 3}},
2806 [] (const Spec &, const std::vector<long long> &, int, int)
2807 {
2808 return std::pair<long long, long long>(10, -80);
2809 });
2810
2811 // Small random networks, with loops, of capacities from 0.1 to 0.3 and
2812 // the costs -1 and 2, by brute force: their cycles of negative cost,
2813 // which the cheapest maximum flow saturates; integer costs, so that no
2814 // sum of a cycle is negative by rounding only
2815 std::mt19937 rng(seed(33));
2816 for (int k = 0; k < (heavy() ? 2000 : 200); ++k)
2817 {
2818 Spec s = random_spec(rng, 3 + int(rng() % 2), 3 + int(rng() % 3), true);
2819 Spec c = s, w = s;
2820 random_weights(rng, c, 1, 3);
2821 random_weights(rng, w, 0, 1);
2822 for (long long & x : w.w)
2823 x = x == 0 ? -10 : 20;
2824 check_tenths_min_costs(solvers, checks, s, c.w, w.w, ends_of(s), brute_min_cost);
2825 }
2826
2827 // Random networks, with capacities from 0.1 to 4 and costs from 0 to 0.9
2828 for (int k = 0; k < (heavy() ? 200 : 20); ++k)
2829 {
2830 Spec s = random_spec(rng, 6 + int(rng() % 3), 8 + int(rng() % 9), true);
2831 Spec c = s, w = s;
2832 random_weights(rng, c, 1, 40);
2833 random_weights(rng, w, 0, 9);
2834 check_tenths_min_costs(solvers, checks, s, c.w, w.w, ends_of(s), ssp_min_cost);
2835 }
2836 checks.expect();
2837}
2838
2839TEST(ExhaustiveFloatingFlow, PathsCarryTheLeastCapacityExactly)
2840{
2841 // On a path, the maximum flow is the least capacity, and no rounding is
2842 // needed: every arc carries exactly it with the augmenting paths, Dinic
2843 // and the scaling (0, 1, 5 and 6). The preflows and HLPP leave as flow
2844 // an excess up to a residue of rounding of the largest capacity, so that
2845 // an arc may carry one ulp more or less: they are taken with the
2846 // tolerance of check_network(), 1e-9, relative
2847 const auto solvers = all_solvers<Double_Net>();
2848 Family_Checks checks(solvers);
2849 const std::vector<double> close = {3.0, std::nextafter(3.0, 0.0), std::nextafter(3.0, 4.0)};
2850
2851 for (int n = 2; n <= 4; ++n)
2852 {
2853 Spec s;
2854 s.n = n;
2855 for (int i = 0; i + 1 < n; ++i)
2856 s.arcs.push_back({i, i + 1});
2857 for_each_assignment(s, {0, 1, 2}, [&] (const Spec & t)
2858 {
2859 std::vector<double> cap;
2860 for (long long k : t.w)
2861 cap.push_back(close[size_t(k)]);
2862 const double least = *std::min_element(cap.begin(), cap.end());
2863 Double_Built b(s, cap, Double_Built::Amounts{});
2864 b.pin(0, n - 1);
2865 for (size_t i = 0; i < solvers.size(); ++i)
2866 {
2867 const bool exact = i <= 1 or i == 5 or i == 6;
2868 auto is_least = [&] (double x)
2869 {
2870 return exact ? x == least : std::abs(x - least) <= 1e-9 * least;
2871 };
2872 Check * check = checks.of(i, 0);
2873 b.net.reset();
2874 check->run();
2875 const double got = solvers[i].run(b.net);
2876 std::string e;
2877 if (not exact and not b.net.check_network())
2878 e = "check_network() is false";
2879 for (size_t k = 0; k < b.spec_arcs and e.empty(); ++k)
2880 if (not is_least(b.arcs[k]->flow))
2881 e = "the arc " + std::to_string(k) + " carries " + text(b.arcs[k]->flow)
2882 + ", not " + text(least);
2883 if (e.empty() and not is_least(got))
2884 e = "returns " + text(got) + ", not " + text(least);
2885 if (not e.empty())
2886 {
2887 Spec shown = t;
2888 check->fail(shown, "capacities 3, 3 - ulp, 3 + ulp by 0, 1, 2: " + e);
2889 }
2890 }
2891 });
2892 }
2893 checks.expect();
2894}
2895
2896
2897TEST(ExhaustiveFloatingFlow, SmallFlowsBesideLargeCapacitiesStay)
2898{
2899 // A small flow next to a large capacity, in the network or in its own
2900 // node, is no residue of rounding: s->a (1e15), a->b (10), b->t (100)
2901 // carries 10, and likewise 1e12 next to 0.05; a node that receives 10
2902 // beside an idle arc of 1e15 into it sends them on; every network of 3
2903 // nodes and 3 arcs without loops, with each assignment of a small and a
2904 // large capacity, between every pair of ends; and random networks of
2905 // capacities far apart
2906 const auto solvers = floating_solvers();
2907 Family_Checks checks(solvers);
2908 Spec chain;
2909 chain.n = 3;
2910 chain.arcs = {{0, 1}, {1, 2}};
2911 check_floating(solvers, checks, chain, {1e15, 10.0}, with_w(chain, {0, 1}), {{0, 2}});
2912 check_floating(solvers, checks, chain, {1e12, 0.05}, with_w(chain, {0, 1}), {{0, 2}});
2913 Spec three = chain;
2914 three.n = 4;
2915 three.arcs = {{0, 1}, {1, 2}, {2, 3}};
2916 check_floating(solvers, checks, three, {1e15, 10.0, 100.0}, with_w(three, {0, 1, 2}), {{0, 3}});
2917 check_floating(solvers, checks, three, {1e12, 0.05, 1.0}, with_w(three, {0, 1, 2}), {{0, 3}});
2918 // 0 -> 1 -> 2 -> 3 carries 10, beside 4 -> 2 of 1e15, idle, as 4 has
2919 // nothing to send: the capacities of node 2 reach 1e15, its flows 10
2920 Spec idle;
2921 idle.n = 5;
2922 idle.arcs = {{0, 1}, {1, 2}, {2, 3}, {4, 2}};
2923 for (const double small : {10.0, 0.05})
2924 for (const double large : {1e12, 1e15})
2925 check_floating(solvers, checks, idle, {small, small, small, large},
2926 with_w(idle, {1, 1, 1, 2}), {{0, 3}});
2927
2928 // The large flows of a node, as a circulation of 1e15 that a preflow
2929 // makes, keep the small ones only within their rounding, eight epsilons
2930 // of the capacities, which also bound the arcs that pin the ends: a
2931 // small flow that goes is beyond it. The networks take, by turns, 0.05
2932 // next to 1e12 and 10 next to 1e15
2933 size_t turn = 0;
2934 for_each_spec(class_domain(), true, [&] (const Spec & s)
2935 {
2936 // Not a structured binding, which the lambda below could not take
2937 // with Clang 14
2938 const bool first = turn++ % 2 == 0;
2939 const double small = first ? 0.05 : 10.0, large = first ? 1e12 : 1e15;
2940 for_each_assignment(s, {0, 1}, [&] (const Spec & t)
2941 {
2942 std::vector<double> cap;
2943 for (long long k : t.w)
2944 cap.push_back(k == 0 ? small : large);
2945 const double total = 2 * (1 + std::accumulate(cap.begin(), cap.end(), 0.0));
2946 check_floating(solvers, checks, s, cap, t, ends_of(s),
2947 8 * std::numeric_limits<double>::epsilon() * total);
2948 });
2949 });
2950
2951 // The smallest networks found, of random ones with capacities far apart,
2952 // where the rounded sums of the flows of a node lost a small flow beside
2953 // a large one that went back later: a cycle of 3.6e-6 beside 6e5 left
2954 // apart by 5e-11, and 0.1875 beside 7.9e12 lost 1.2e-5; where the return
2955 // of the dust moved the rounding of the sums of a node around a cycle,
2956 // and the dust that mattered stayed; and where it moved a lack of dust
2957 // along the arcs of least flow around a cycle, and not to the node next
2958 // to it whose flows take it
2959 Spec far;
2960 far.n = 6;
2961 far.arcs = {{3, 3}, {2, 3}, {1, 5}, {3, 0}, {5, 1}, {3, 1}, {1, 4}, {2, 5}};
2962 check_floating(solvers, checks, far,
2963 {55118.193817935826, 149126.55127876526, 3.6210321744802924e-06,
2964 0.0385901963482553, 603731.40689728025, 1314.8553040957299,
2965 953459.62917306356, 0.00026489820008349357}, far, {{5, 0}});
2966 far.arcs = {{2, 0}, {0, 1}, {0, 5}, {0, 4}, {5, 0}, {2, 4}, {4, 4}, {2, 3}};
2967 check_floating(solvers, checks, far,
2968 {0.59427109889739216, 7953873572469.2061, 0.81688221777390935,
2969 0.18751894271814884, 328344486869.60187, 3936541668632.1372,
2970 0.87745357597236218, 56718122500789.414}, far, {{5, 4}});
2971 far.n = 7;
2972 far.arcs = {{2, 0}, {6, 3}, {1, 6}, {1, 4}, {0, 0}, {5, 0}, {1, 1}, {0, 1}, {4, 5}, {0, 6},
2973 {6, 4}};
2974 check_floating(solvers, checks, far,
2975 {7.8578759915140388, 1.4834611226725403, 1.142136746397745e-06,
2976 71865.908828292086, 16876.398523053449, 0.00022356931471620252,
2977 0.00085033886634015452, 0.0006983639430014119, 2768.5456274341955,
2978 815923.95045026485, 1.9315827618482626}, far, {{0, 6}});
2979 far.arcs = {{4, 2}, {5, 1}, {1, 4}, {3, 0}, {3, 4}, {3, 5}, {4, 5}, {4, 1}, {5, 1}, {5, 3},
2980 {4, 5}, {2, 3}, {5, 3}, {3, 3}, {5, 3}, {6, 1}, {3, 5}};
2981 check_floating(solvers, checks, far,
2982 {0.96592538716777065, 41828262273.129745, 0.46122354099487478,
2983 1096140671258.7633, 0.26271163702451467, 0.71954778904404204,
2984 0.17797677450110017, 49428360953814.516, 0.45721147537616996,
2985 591860561869202.25, 0.3543226821218215, 4609845414.2492914,
2986 0.70720933063203661, 4845511438574.6699, 122077735988.32132,
2987 97320921918.880493, 110642036269421.2}, far, {{2, 6}});
2988
2989 // Random networks of capacities from 1e-6 to 1e6, uniform in their
2990 // logarithm, between every pair of ends
2991 std::mt19937 rng(seed(71));
2992 std::uniform_real_distribution<double> exponent(-6.0, 6.0);
2993 for (int k = 0; k < (heavy() ? 300 : 30); ++k)
2994 {
2995 const Spec s = random_spec(rng, 6 + int(rng() % 3), 8 + int(rng() % 9), true);
2996 std::vector<double> cap;
2997 for (size_t i = 0; i < s.arcs.size(); ++i)
2998 cap.push_back(std::pow(10.0, exponent(rng)));
2999 check_floating(solvers, checks, s, cap, s, ends_of(s));
3000 }
3001 checks.expect();
3002}
3003
3004// ======================================================================
3005// Assignments, transportation and transshipment
3006
3007namespace
3008{
3010 using Matrix = std::vector<std::vector<long long>>;
3011
3012 std::string matrix_text(const Matrix & c)
3013 {
3014 std::string r = "{";
3015 for (size_t i = 0; i < c.size(); ++i)
3016 {
3017 r += i == 0 ? "{" : " {";
3018 for (size_t j = 0; j < c[i].size(); ++j)
3019 r += (j == 0 ? "" : " ") + std::to_string(c[i][j]);
3020 r += "}";
3021 }
3022 return r + "}";
3023 }
3024
3028 long long best_assignment(const Matrix & c, bool most = false)
3029 {
3030 const size_t m = c.size(), n = m == 0 ? 0 : c[0].size();
3031 const size_t k = std::min(m, n);
3032 // The larger side, permuted; its first k entries take the smaller side
3033 std::vector<size_t> perm(std::max(m, n));
3034 std::iota(perm.begin(), perm.end(), size_t(0));
3035 long long best = most ? std::numeric_limits<long long>::lowest()
3036 : std::numeric_limits<long long>::max();
3037 do
3038 {
3039 long long sum = 0;
3040 for (size_t i = 0; i < k; ++i)
3041 sum += m <= n ? c[i][perm[i]] : c[perm[i]][i];
3042 best = most ? std::max(best, sum) : std::min(best, sum);
3043 }
3044 while (std::next_permutation(perm.begin(), perm.end()));
3045 return k == 0 ? 0 : best;
3046 }
3047
3049 template <class F>
3050 void for_each_matrix(size_t rows, size_t cols, const std::vector<long long> & values, F f)
3051 {
3052 std::vector<size_t> pick(rows * cols, 0);
3053 while (true)
3054 {
3055 Matrix c(rows, std::vector<long long>(cols));
3056 for (size_t k = 0; k < pick.size(); ++k)
3057 c[k / cols][k % cols] = values[pick[k]];
3058 f(c);
3059 size_t i = 0;
3060 while (i < pick.size() and ++pick[i] == values.size())
3061 pick[i++] = 0;
3062 if (i == pick.size())
3063 return;
3064 }
3065 }
3066
3070 template <class F>
3071 void for_each_assignment_matrix(bool square, F f)
3072 {
3073 for (size_t m = 1; m <= 3; ++m)
3074 for (size_t n = 1; n <= 3; ++n)
3075 if ((not square or m == n) and m * n <= 6)
3076 for_each_matrix(m, n, {-1, 0, 2}, f);
3077 for_each_matrix(3, 3, {0, 2}, f);
3078 std::mt19937 rng(seed(41));
3079 for (int k = 0; k < (heavy() ? 300 : 40); ++k)
3080 {
3081 const size_t m = 1 + rng() % 5, n = square ? m : 1 + rng() % 5;
3082 Matrix c(m, std::vector<long long>(n));
3083 for (auto & row : c)
3084 for (auto & x : row)
3085 x = static_cast<long long>(rng() % 19) - 9;
3086 f(c);
3087 }
3088 }
3089
3093 template <class Array_Of_Long, typename C>
3094 std::string assignment_error(const Matrix & c, const Array_Of_Long & row_to_col,
3095 const Array_Of_Long & col_to_row, C total)
3096 {
3097 const size_t m = c.size(), n = c[0].size();
3098 if (row_to_col.size() != m or col_to_row.size() != n)
3099 return "the arrays have " + std::to_string(row_to_col.size()) + " and "
3100 + std::to_string(col_to_row.size()) + " entries";
3101 long long sum = 0;
3102 size_t assigned = 0;
3103 for (size_t i = 0; i < m; ++i)
3104 {
3105 const long j = row_to_col[i];
3106 if (j == -1)
3107 continue;
3108 if (j < 0 or size_t(j) >= n or col_to_row[size_t(j)] != long(i))
3109 return "the row " + std::to_string(i) + " has the column " + std::to_string(j);
3110 sum += c[i][size_t(j)];
3111 ++assigned;
3112 }
3113 if (assigned != std::min(m, n))
3114 return std::to_string(assigned) + " rows assigned, not " + std::to_string(std::min(m, n));
3115 if (C(sum) != total)
3116 return "the pairs cost " + std::to_string(sum) + ", not " + text(total);
3117 return "";
3118 }
3119}
3120
3121template <class C>
3122class ExhaustiveAssignment : public ::testing::Test {};
3123
3125using Cost_Types = ::testing::Types<int, long, double>;
3126
3128
3129TYPED_TEST(ExhaustiveAssignment, HungarianMatchesTheOracle)
3130{
3131 using C = TypeParam;
3132 Check function("hungarian_assignment()");
3133 Check object("Hungarian_Assignment");
3134 Check most("hungarian_max_assignment()");
3135
3136 for_each_assignment_matrix(false, [&] (const Matrix & c)
3137 {
3138 const size_t m = c.size(), n = c[0].size();
3139 Spec shown;
3140 shown.n = int(m);
3141 const std::string what = "the costs " + matrix_text(c) + ": ";
3142 DynMatrix<C> cost(m, n);
3143 cost.allocate();
3144 for (size_t i = 0; i < m; ++i)
3145 for (size_t j = 0; j < n; ++j)
3146 cost(i, j) = C(c[i][j]);
3147 const long long want = best_assignment(c);
3148
3149 function.run();
3150 {
3151 const auto r = hungarian_assignment(cost);
3152 if (r.total_cost != C(want))
3153 function.fail(shown, what + "costs " + text(r.total_cost) + ", not "
3154 + std::to_string(want));
3155 else if (auto e = assignment_error(c, r.row_to_col, r.col_to_row, r.total_cost);
3156 not e.empty())
3157 function.fail(shown, what + e);
3158 else if (r.get_pairs().size() != std::min(m, n) or r.orig_rows != m or r.orig_cols != n)
3159 function.fail(shown, what + "get_pairs() or the sizes are wrong");
3160 }
3161
3162 object.run();
3163 {
3164 const Hungarian_Assignment<C> h(cost);
3165 bool ok = h.get_total_cost() == C(want) and h.rows() == m and h.cols() == n
3166 and h.dimension() == std::max(m, n)
3167 and assignment_error(c, h.get_row_assignments(), h.get_col_assignments(),
3168 h.get_total_cost()).empty()
3169 and h.get_assignments().size() == std::min(m, n);
3170 for (size_t i = 0; i < m and ok; ++i)
3171 ok = h.get_assignment(i) == h.get_row_assignments()[i];
3172 try
3173 {
3174 (void) h.get_assignment(m);
3175 ok = false;
3176 }
3177 catch (const std::out_of_range &) {}
3178 if (not ok)
3179 object.fail(shown, what + "a wrong answer from a query");
3180 }
3181
3182 most.run();
3183 const auto r = hungarian_max_assignment(cost);
3184 const long long best = best_assignment(c, true);
3185 if (r.total_cost != C(best))
3186 most.fail(shown, what + "gives " + text(r.total_cost) + ", not " + std::to_string(best));
3187 else if (auto e = assignment_error(c, r.row_to_col, r.col_to_row, r.total_cost);
3188 not e.empty())
3189 most.fail(shown, what + e);
3190 });
3191 function.expect();
3192 object.expect();
3193 most.expect();
3194}
3195
3196TYPED_TEST(ExhaustiveAssignment, AssignmentByFlowMatchesTheOracle)
3197{
3198 using C = TypeParam;
3199 Check check("solve_assignment()");
3200 for_each_assignment_matrix(true, [&] (const Matrix & c)
3201 {
3202 Spec shown;
3203 shown.n = int(c.size());
3204 std::vector<std::vector<C>> cost(c.size());
3205 for (size_t i = 0; i < c.size(); ++i)
3206 for (long long x : c[i])
3207 cost[i].push_back(C(x));
3208 check.run();
3209 const auto r = solve_assignment(cost);
3210 const long long want = best_assignment(c);
3211 std::vector<long> row_to_col(c.size(), -1), col_to_row(c.size(), -1);
3212 for (auto it = r.assignments.get_it(); it.has_curr(); it.next_ne())
3213 {
3214 const auto [i, j] = it.get_curr();
3215 if (i < c.size() and j < c.size())
3216 {
3217 row_to_col[i] = long(j);
3218 col_to_row[j] = long(i);
3219 }
3220 }
3221 if (not r.feasible or r.total_cost != C(want))
3222 check.fail(shown, "the costs " + matrix_text(c) + ": feasible " + std::to_string(r.feasible)
3223 + " and cost " + text(r.total_cost) + ", not " + std::to_string(want));
3224 else if (auto e = assignment_error(c, row_to_col, col_to_row, r.total_cost); not e.empty())
3225 check.fail(shown, "the costs " + matrix_text(c) + ": " + e);
3226 else if (r.assignments.size() != c.size())
3227 check.fail(shown, "the costs " + matrix_text(c) + ": a pair twice");
3228 });
3229 {
3230 check.run();
3231 const auto r = solve_assignment(std::vector<std::vector<C>>{});
3232 if (not r.feasible or not r.assignments.is_empty())
3233 check.fail(Spec(), "no workers: not feasible, or pairs");
3234 }
3235 check.expect();
3236}
3237
3238TEST(ExhaustiveAssignmentLimits, HungarianWithCostsNearTheLimits)
3239{
3240 constexpr int Max = std::numeric_limits<int>::max();
3241 // int keeps its potentials in long long: an optimum that fits is exact,
3242 // with rows of costs of max() / 2 or more too, which the infinity of int
3243 // took for no column, and one that does not fit, which overflowed the
3244 // potentials of int, throws overflow_error
3245 Check check("Hungarian_Assignment<int>, costs that fit");
3246 Check beyond("Hungarian_Assignment<int>, a row of costs from max() / 2");
3247 Check overflow("Hungarian_Assignment<int>, an optimum beyond max()");
3248
3249 const std::vector<Matrix> cases = {
3250 {{1000000000, 1000000000}, {1000000000, 1000000000}},
3251 {{1000000000, 100000000}, {1000000000, 1000000000}},
3252 {{700000000, 700000000, 700000000}, {700000000, 700000000, 700000000},
3253 {700000000, 700000000, 700000000}},
3254 {{Max, 0}, {0, Max}},
3255 {{Max / 2, 0}},
3256 {{Max / 2 + 1}},
3257 {{Max, Max}, {0, 0}},
3258 {{1000000000, 1000000000, 1000000000}, {1000000000, 1000000000, 1000000000},
3259 {1000000000, 1000000000, 1000000000}}};
3260 for (const auto & c : cases)
3261 {
3262 bool row_beyond = false;
3263 for (const auto & row : c)
3264 row_beyond = row_beyond or *std::min_element(row.begin(), row.end()) >= Max / 2;
3265 const long long want = best_assignment(c);
3266 DynMatrix<int> cost(c.size(), c[0].size());
3267 cost.allocate();
3268 for (size_t i = 0; i < c.size(); ++i)
3269 for (size_t j = 0; j < c[i].size(); ++j)
3270 cost(i, j) = int(c[i][j]);
3271 if (want > Max)
3272 {
3273 overflow.run();
3274 try
3275 {
3276 const auto r = hungarian_assignment(cost);
3277 overflow.fail(Spec(), "the costs " + matrix_text(c) + ": gives "
3278 + std::to_string(r.total_cost) + ", not overflow_error");
3279 }
3280 catch (const std::overflow_error &)
3281 {
3282 // what it must do
3283 }
3284 catch (const std::exception & e)
3285 {
3286 overflow.fail(Spec(), "the costs " + matrix_text(c) + ": throws " + e.what());
3287 }
3288 continue;
3289 }
3290 Check & which = row_beyond ? beyond : check;
3291 which.run();
3292 try
3293 {
3294 const auto r = hungarian_assignment(cost);
3295 if (r.total_cost != want)
3296 which.fail(Spec(), "the costs " + matrix_text(c) + ": " + std::to_string(r.total_cost)
3297 + ", not " + std::to_string(want));
3298 }
3299 catch (const std::exception & e)
3300 {
3301 which.fail(Spec(), "the costs " + matrix_text(c) + ": throws " + e.what());
3302 }
3303 }
3304 check.expect();
3305 beyond.expect();
3306 overflow.expect();
3307}
3308
3309namespace
3310{
3314 long long best_transport(const std::vector<long long> & sup, const std::vector<long long> & dem,
3315 const Matrix & c)
3316 {
3317 if (std::accumulate(sup.begin(), sup.end(), 0LL)
3318 != std::accumulate(dem.begin(), dem.end(), 0LL))
3319 return -1;
3320 const size_t m = sup.size(), n = dem.size();
3321 std::vector<long long> x(m * n, 0);
3322 long long best = -1;
3323 while (true)
3324 {
3325 bool ok = true;
3326 for (size_t i = 0; i < m and ok; ++i)
3327 {
3328 long long row = 0;
3329 for (size_t j = 0; j < n; ++j)
3330 row += x[i * n + j];
3331 ok = row == sup[i];
3332 }
3333 for (size_t j = 0; j < n and ok; ++j)
3334 {
3335 long long col = 0;
3336 for (size_t i = 0; i < m; ++i)
3337 col += x[i * n + j];
3338 ok = col == dem[j];
3339 }
3340 if (ok)
3341 {
3342 long long cost = 0;
3343 for (size_t k = 0; k < x.size(); ++k)
3344 cost += x[k] * c[k / n][k % n];
3345 if (best < 0 or cost < best)
3346 best = cost;
3347 }
3348 size_t k = 0;
3349 while (k < x.size() and ++x[k] > std::min(sup[k / n], dem[k % n]))
3350 x[k++] = 0;
3351 if (k == x.size())
3352 return best;
3353 }
3354 }
3355}
3356
3357TYPED_TEST(ExhaustiveAssignment, TransportationMatchesTheOracle)
3358{
3359 using C = TypeParam;
3360 Check check("solve_transportation()");
3361 for (size_t m = 1; m <= 2; ++m)
3362 for (size_t n = 1; n <= 2; ++n)
3363 for_each_matrix(1, m + n, {0, 1, 2}, [&] (const Matrix & amounts)
3364 {
3365 const std::vector<long long> sup(amounts[0].begin(), amounts[0].begin() + long(m));
3366 const std::vector<long long> dem(amounts[0].begin() + long(m), amounts[0].end());
3367 for_each_matrix(m, n, {0, 1, 3}, [&] (const Matrix & c)
3368 {
3369 check.run();
3370 std::vector<C> s, d;
3371 for (auto x : sup)
3372 s.push_back(C(x));
3373 for (auto x : dem)
3374 d.push_back(C(x));
3375 std::vector<std::vector<C>> cost(m);
3376 for (size_t i = 0; i < m; ++i)
3377 for (auto x : c[i])
3378 cost[i].push_back(C(x));
3379 const auto r = solve_transportation(s, d, cost);
3380 const long long want = best_transport(sup, dem, c);
3381 const std::string what = "supplies " + matrix_text({sup}) + ", demands "
3382 + matrix_text({dem}) + ", costs " + matrix_text(c) + ": ";
3383 if (r.feasible != (want >= 0) or (want >= 0 and r.total_cost != C(want)))
3384 {
3385 check.fail(Spec(), what + "feasible " + std::to_string(r.feasible) + " and cost "
3386 + text(r.total_cost) + ", not " + std::to_string(want));
3387 return;
3388 }
3389 if (want < 0)
3390 return;
3391 C total{0};
3392 for (size_t i = 0; i < m; ++i)
3393 {
3394 C row{0};
3395 for (size_t j = 0; j < n; ++j)
3396 {
3397 row += r.shipments[i][j];
3398 total += r.shipments[i][j] * cost[i][j];
3399 }
3400 if (row != s[i])
3401 check.fail(Spec(), what + "a supply is not shipped");
3402 }
3403 for (size_t j = 0; j < n; ++j)
3404 {
3405 C col{0};
3406 for (size_t i = 0; i < m; ++i)
3407 col += r.shipments[i][j];
3408 if (col != d[j])
3409 check.fail(Spec(), what + "a demand is not met");
3410 }
3411 if (total != r.total_cost)
3412 check.fail(Spec(), what + "the shipments cost " + text(total));
3413 });
3414 });
3415 check.expect();
3416}
3417
3418TEST(ExhaustiveAssignmentLimits, TransportationOfTenths)
3419{
3420 // The totals of the supplies and of the demands are equal, but some, as
3421 // {0.1, 0.2} and {0.3}, only but for rounding
3422 Check check("solve_transportation(), with tenths");
3423 for (size_t m = 1; m <= 2; ++m)
3424 for (size_t n = 1; n <= 2; ++n)
3425 for_each_matrix(1, m + n, {1, 2, 3}, [&] (const Matrix & amounts)
3426 {
3427 const std::vector<long long> sup(amounts[0].begin(), amounts[0].begin() + long(m));
3428 const std::vector<long long> dem(amounts[0].begin() + long(m), amounts[0].end());
3429 if (std::accumulate(sup.begin(), sup.end(), 0LL)
3430 != std::accumulate(dem.begin(), dem.end(), 0LL))
3431 return;
3432 std::vector<double> s, d;
3433 for (auto x : sup)
3434 s.push_back(double(x) / 10);
3435 for (auto x : dem)
3436 d.push_back(double(x) / 10);
3437 Check & c = check;
3438 c.run();
3439 const std::vector<std::vector<double>> cost(m, std::vector<double>(n, 1.0));
3440 const auto r = solve_transportation(s, d, cost);
3441 mpq_class shipped = 0; // each unit costs 1
3442 for (double x : s)
3443 shipped += mpq_class(x);
3444 if (not r.feasible or not near(r.total_cost, shipped))
3445 c.fail(Spec(), "supplies " + matrix_text({sup}) + " and demands " + matrix_text({dem})
3446 + " in tenths: feasible " + std::to_string(r.feasible) + ", cost "
3447 + text(r.total_cost));
3448 });
3449 check.expect();
3450}
3451
3452namespace
3453{
3457 long long best_transshipment(const Spec & s, const std::vector<long long> & cost,
3458 const std::vector<long long> & d)
3459 {
3460 std::vector<long long> f(s.arcs.size(), 0);
3461 long long best = -1;
3462 while (true)
3463 {
3464 std::vector<long long> net(size_t(s.n), 0);
3465 for (size_t i = 0; i < f.size(); ++i)
3466 {
3467 net[size_t(s.arcs[i][0])] += f[i];
3468 net[size_t(s.arcs[i][1])] -= f[i];
3469 }
3470 if (net == d)
3471 {
3472 long long c = 0;
3473 for (size_t i = 0; i < f.size(); ++i)
3474 c += f[i] * cost[i];
3475 if (best < 0 or c < best)
3476 best = c;
3477 }
3478 size_t i = 0;
3479 while (i < f.size() and ++f[i] > s.w[i])
3480 f[i++] = 0;
3481 if (i == f.size())
3482 return best;
3483 }
3484 }
3485}
3486
3487TYPED_TEST(ExhaustiveMinCost, TransshipmentMatchesTheOracle)
3488{
3489 using Net = TypeParam;
3490 using F = typename Net::Flow_Type;
3491 Check check("solve_transshipment()");
3492
3493 for_each_spec(class_domain(), true, [&] (const Spec & raw)
3494 {
3495 const Spec s = structural(raw);
3496 const auto cost = structural_costs(s);
3497 std::vector<long long> values = {-1, 0, 1};
3498 Spec nodes_as_arcs; // the demands, one per node, through an assignment
3499 nodes_as_arcs.n = s.n;
3500 nodes_as_arcs.arcs.assign(size_t(s.n), {0, 0});
3501 for_each_assignment(nodes_as_arcs, values, [&] (const Spec & dem)
3502 {
3503 const std::vector<long long> & d = dem.w;
3504 const long long total = std::accumulate(d.begin(), d.end(), 0LL);
3505 const bool nothing = std::all_of(d.begin(), d.end(), [] (long long x) { return x == 0; });
3506 Check & c = check;
3507 Built_Net<Net> b(s, s.w, cost);
3508 const size_t nodes = b.net.get_num_nodes(), arcs = b.net.get_num_arcs();
3509 std::map<typename Net::Node *, F> demand;
3510 for (int v = 0; v < s.n; ++v)
3511 demand[b.nodes[size_t(v)]] = amount<F>(d[size_t(v)]);
3512 const std::string what = "demands " + matrix_text({d}) + ", " + costs_text(cost);
3513 c.run();
3515 try
3516 {
3517 r = solve_transshipment(b.net, [&] (typename Net::Node * p) { return demand[p]; });
3518 }
3519 catch (const std::exception & e)
3520 {
3521 c.fail(s, what + "throws " + e.what());
3522 return;
3523 }
3524 const long long want = total != 0 ? -1 : nothing ? 0 : best_transshipment(s, cost, d);
3525 if (r.feasible != (want >= 0))
3526 {
3527 c.fail(s, what + (want >= 0 ? "says infeasible" : "says feasible"));
3528 return;
3529 }
3530 if (b.net.get_num_nodes() != nodes or b.net.get_num_arcs() != arcs)
3531 {
3532 c.fail(s, what + "leaves the super nodes");
3533 return;
3534 }
3535 if (want <= 0 and nothing)
3536 return;
3537 if (want < 0)
3538 return;
3539 long long supply = 0;
3540 for (long long x : d)
3541 supply += std::max(x, 0LL);
3542 if (not is_amount(r.total_flow, supply) or not is_cost(r.total_cost, want))
3543 {
3544 c.fail(s, what + "ships " + text(r.total_flow) + " at " + text(r.total_cost)
3545 + ", not " + text(amount<F>(supply)) + " at " + text(cost_amount<F>(want)));
3546 return;
3547 }
3548 // The flows of the network are that transshipment
3549 for (int v = 0; v < s.n; ++v)
3550 {
3551 auto p = b.nodes[size_t(v)];
3552 if (b.net.get_out_flow(p) - b.net.get_in_flow(p) != demand[p])
3553 {
3554 c.fail(s, what + "the flows left do not meet the demand of "
3555 + std::to_string(v));
3556 return;
3557 }
3558 }
3559 if (b.net.flow_cost() != r.total_cost)
3560 c.fail(s, what + "the flows left cost " + text(b.net.flow_cost()));
3561 });
3562 });
3563 check.expect();
3564}
3565
3566// ======================================================================
3567// The applications of net_apps.H
3568
3569namespace
3570{
3573 bool circulation_exists(const Spec & s, const std::vector<long long> & lower,
3574 const std::vector<long long> & d)
3575 {
3576 std::vector<long long> f = lower;
3577 while (true)
3578 {
3579 std::vector<long long> net(size_t(s.n), 0);
3580 for (size_t i = 0; i < f.size(); ++i)
3581 {
3582 net[size_t(s.arcs[i][1])] += f[i];
3583 net[size_t(s.arcs[i][0])] -= f[i];
3584 }
3585 if (net == d)
3586 return true;
3587 size_t i = 0;
3588 while (i < f.size() and ++f[i] > s.w[i])
3589 f[i] = lower[i], ++i;
3590 if (i == f.size())
3591 return false;
3592 }
3593 }
3594}
3595
3596TEST(ExhaustiveNetApps, CirculationsMatchTheOracle)
3597{
3599 Check check("solve_circulation()");
3600 Check restored("solve_circulation(), the network after");
3601
3602 for_each_spec(class_domain(), true, [&] (const Spec & raw)
3603 {
3604 const Spec s = structural(raw);
3605 Spec per_node;
3606 per_node.n = s.n;
3607 per_node.arcs.assign(size_t(s.n), {0, 0});
3608 for_each_assignment(per_node, {-1, 0, 1}, [&] (const Spec & dem)
3609 {
3610 for_each_assignment(s, {0, 1}, [&] (const Spec & low)
3611 {
3612 const auto & d = dem.w;
3613 const auto & lower = low.w;
3614 Built_Net<Net> b(s);
3615 std::map<Net::Node *, long> demand;
3616 std::map<Net::Arc *, long> lb;
3617 for (int v = 0; v < s.n; ++v)
3618 demand[b.nodes[size_t(v)]] = long(d[size_t(v)]);
3619 for (size_t i = 0; i < b.arcs.size(); ++i)
3620 lb[b.arcs[i]] = long(lower[i]);
3621 const std::string what = "demands " + matrix_text({d}) + ", lower bounds "
3622 + matrix_text({lower}) + ": ";
3623 check.run();
3625 try
3626 {
3627 r = solve_circulation(b.net, [&] (Net::Node * p) { return demand[p]; },
3628 [&] (Net::Arc * a) { return lb[a]; });
3629 }
3630 catch (const std::exception & e)
3631 {
3632 check.fail(s, what + "throws " + e.what());
3633 return;
3634 }
3635 const bool want = circulation_exists(s, lower, d);
3636 if (r.feasible != want)
3637 check.fail(s, what + (want ? "says infeasible" : "says feasible"));
3638 else if (want)
3639 {
3640 // The flows that it gives meet the bounds and the demands
3641 std::vector<long> in(size_t(s.n), 0), out(size_t(s.n), 0);
3642 std::string e;
3643 for (size_t i = 0; i < b.arcs.size() and e.empty(); ++i)
3644 {
3645 auto a = b.arcs[i];
3646 const long f = r.flow.contains(a) ? r.flow.find(a) : -1;
3647 if (f < lower[i] or f > s.w[i])
3648 e = "the arc " + std::to_string(i) + " gets " + std::to_string(f);
3649 out[size_t(s.arcs[i][0])] += f;
3650 in[size_t(s.arcs[i][1])] += f;
3651 }
3652 for (int v = 0; v < s.n and e.empty(); ++v)
3653 if (in[size_t(v)] - out[size_t(v)] != d[size_t(v)])
3654 e = "the node " + std::to_string(v) + " gets in - out = "
3655 + std::to_string(in[size_t(v)] - out[size_t(v)]);
3656 if (not e.empty())
3657 check.fail(s, what + "the flows: " + e);
3658 }
3659
3660 restored.run();
3661 bool same = b.net.get_num_nodes() == size_t(s.n)
3662 and b.net.get_num_arcs() == s.num_arcs();
3663 for (size_t i = 0; i < b.arcs.size() and same; ++i)
3664 same = b.arcs[i]->cap == s.w[i] and b.arcs[i]->flow == 0;
3665 if (not same)
3666 restored.fail(s, what + "the network is not as it was");
3667 });
3668 });
3669 });
3670 check.expect();
3671 restored.expect();
3672}
3673
3674TEST(ExhaustiveNetApps, ProjectSelectionsMatchTheOracle)
3675{
3676 Check check("solve_project_selection()");
3677 auto run = [&] (const Spec & s, const Spec & p)
3678 {
3679 // Project i requires project j for each arc i -> j
3680 std::vector<Project<long>> projects;
3681 for (int i = 0; i < s.n; ++i)
3682 {
3683 std::vector<size_t> pre;
3684 for (const auto & a : s.arcs)
3685 if (a[0] == i)
3686 pre.push_back(size_t(a[1]));
3687 projects.emplace_back(size_t(i), long(p.w[size_t(i)]), pre);
3688 }
3689 long best = 0;
3690 for (unsigned long set = 0; set < (1UL << s.n); ++set)
3691 {
3692 bool closed = true;
3693 for (const auto & a : s.arcs)
3694 closed = closed and (((set >> a[0]) & 1UL) == 0 or ((set >> a[1]) & 1UL) != 0);
3695 long profit = 0;
3696 for (int i = 0; i < s.n; ++i)
3697 profit += ((set >> i) & 1UL) ? long(p.w[size_t(i)]) : 0;
3698 if (closed)
3699 best = std::max(best, profit);
3700 }
3701 check.run();
3702 const auto r = solve_project_selection(projects);
3703 std::set<size_t> chosen(r.selected.begin(), r.selected.end());
3704 long profit = 0, revenue = 0, cost = 0;
3705 bool closed = chosen.size() == r.selected.size();
3706 for (size_t i : chosen)
3707 {
3708 profit += long(p.w[i]);
3709 revenue += std::max(0L, long(p.w[i]));
3710 cost += std::max(0L, -long(p.w[i]));
3711 for (size_t j : projects[i].prerequisites)
3712 closed = closed and chosen.count(j) > 0;
3713 }
3714 const std::string what = "profits " + matrix_text({p.w}) + ": ";
3715 if (r.max_profit != best)
3716 check.fail(s, what + "the profit is " + std::to_string(r.max_profit) + ", not "
3717 + std::to_string(best));
3718 else if (not closed or profit != best or r.total_revenue != revenue
3719 or r.total_cost != cost)
3720 check.fail(s, what + "the selection is not closed, or not of that profit");
3721 };
3722 // Project i requires j for each arc i -> j: every digraph of 3 nodes and
3723 // 3 arcs with each assignment of the profits -2, -1, 1 and 2, and random
3724 // ones of 5 and 6 projects
3725 for_each_spec(domain(3, 3), true, [&] (const Spec & s)
3726 {
3727 if (s.n == 0)
3728 return;
3729 Spec per_node;
3730 per_node.n = s.n;
3731 per_node.arcs.assign(size_t(s.n), {0, 0});
3732 for_each_assignment(per_node, {-2, -1, 1, 2}, [&] (const Spec & p) { run(s, p); });
3733 });
3734 std::mt19937 rng(seed(61));
3735 for (int k = 0; k < (heavy() ? 2000 : 200); ++k)
3736 {
3737 const int n = 5 + int(rng() % 2);
3738 Spec s = random_spec(rng, n, int(rng() % 8), true);
3739 Spec p;
3740 p.n = n;
3741 p.arcs.assign(size_t(n), {0, 0});
3742 random_weights(rng, p, -3, 3);
3743 run(s, p);
3744 }
3745 check.expect();
3746}
3747
3748namespace
3749{
3753 bool eliminated(const std::vector<Team> & t, size_t x)
3754 {
3755 const int top = t[x].wins + t[x].remaining;
3756 std::vector<std::pair<size_t, size_t>> pairs;
3757 for (size_t i = 0; i < t.size(); ++i)
3758 for (size_t j = i + 1; j < t.size(); ++j)
3759 if (i != x and j != x)
3760 pairs.push_back({i, j});
3761 // Each pair splits its games: k won by the first
3762 std::vector<int> k(pairs.size(), 0);
3763 while (true)
3764 {
3765 std::vector<int> w(t.size());
3766 for (size_t i = 0; i < t.size(); ++i)
3767 w[i] = t[i].wins;
3768 for (size_t p = 0; p < pairs.size(); ++p)
3769 {
3770 const int g = t[pairs[p].first].against[pairs[p].second];
3771 w[pairs[p].first] += k[p];
3772 w[pairs[p].second] += g - k[p];
3773 }
3774 bool first = true;
3775 for (size_t i = 0; i < t.size(); ++i)
3776 first = first and (i == x or w[i] <= top);
3777 if (first)
3778 return false;
3779 size_t p = 0;
3780 while (p < pairs.size() and ++k[p] > t[pairs[p].first].against[pairs[p].second])
3781 k[p++] = 0;
3782 if (p == pairs.size())
3783 return true;
3784 }
3785 }
3786
3789 bool proves(const std::vector<Team> & t, size_t x, const std::vector<size_t> & r)
3790 {
3791 if (r.empty())
3792 return false;
3793 long total = 0;
3794 for (size_t i : r)
3795 {
3796 if (i == x or i >= t.size())
3797 return false;
3798 total += t[i].wins;
3799 for (size_t j : r)
3800 if (i < j)
3801 total += t[i].against[j];
3802 }
3803 return total > long(r.size()) * (t[x].wins + t[x].remaining);
3804 }
3805}
3806
3807TEST(ExhaustiveNetApps, BaseballEliminationsMatchTheOracle)
3808{
3809 Check check("check_baseball_elimination()");
3810 Check certificate("check_baseball_elimination(), the certificate");
3811
3812 auto run = [&] (const std::vector<Team> & t)
3813 {
3814 Spec shown;
3815 shown.n = int(t.size());
3816 for (size_t x = 0; x < t.size(); ++x)
3817 {
3818 std::string what = "wins";
3819 for (const auto & team : t)
3820 what += " " + std::to_string(team.wins);
3821 what += ", games";
3822 for (size_t i = 0; i < t.size(); ++i)
3823 for (size_t j = i + 1; j < t.size(); ++j)
3824 what += " " + std::to_string(t[i].against[j]);
3825 what += ", team " + std::to_string(x) + ": ";
3826 check.run();
3827 const auto r = check_baseball_elimination(t, x);
3828 const bool want = eliminated(t, x);
3829 if (r.eliminated != want or r.max_possible_wins != t[x].wins + t[x].remaining)
3830 {
3831 check.fail(shown, what + (want ? "says not eliminated" : "says eliminated"));
3832 continue;
3833 }
3834 if (want)
3835 {
3836 certificate.run();
3837 if (not proves(t, x, r.certificate))
3838 certificate.fail(shown, what + "the certificate proves nothing");
3839 }
3840 }
3841 };
3842
3843 // Every league of 3 teams with up to 2 wins and up to 2 games between
3844 // each pair, and random ones of 4 and 5 teams
3845 for (int w0 = 0; w0 <= 2; ++w0)
3846 for (int w1 = 0; w1 <= 2; ++w1)
3847 for (int w2 = 0; w2 <= 2; ++w2)
3848 for (int g01 = 0; g01 <= 2; ++g01)
3849 for (int g02 = 0; g02 <= 2; ++g02)
3850 for (int g12 = 0; g12 <= 2; ++g12)
3851 {
3852 std::vector<Team> t(3);
3853 const int w[] = {w0, w1, w2};
3854 const int g[3][3] = {{0, g01, g02}, {g01, 0, g12}, {g02, g12, 0}};
3855 for (size_t i = 0; i < 3; ++i)
3856 {
3857 t[i].wins = w[i];
3858 t[i].against.assign(g[i], g[i] + 3);
3859 t[i].remaining = g[i][0] + g[i][1] + g[i][2];
3860 }
3861 run(t);
3862 }
3863 std::mt19937 rng(seed(51));
3864 for (int k = 0; k < (heavy() ? 2000 : 200); ++k)
3865 {
3866 const size_t n = 4 + rng() % 2;
3867 std::vector<Team> t(n);
3868 for (auto & team : t)
3869 {
3870 team.wins = int(rng() % 4);
3871 team.against.assign(n, 0);
3872 }
3873 for (size_t i = 0; i < n; ++i)
3874 for (size_t j = i + 1; j < n; ++j)
3875 t[i].against[j] = t[j].against[i] = int(rng() % 3);
3876 for (size_t i = 0; i < n; ++i)
3877 t[i].remaining = std::accumulate(t[i].against.begin(), t[i].against.end(), 0)
3878 + int(rng() % 2);
3879 run(t);
3880 }
3881 check.expect();
3882 certificate.expect();
3883}
3884
3885TEST(ExhaustiveNetApps, SegmentationsMatchTheOracle)
3886{
3887 Check check("segment_image()");
3888 const std::vector<std::pair<size_t, size_t>> grids = {{1, 1}, {1, 2}, {2, 1}, {1, 3}, {2, 2}};
3889 for (const auto & grid : grids)
3890 {
3891 // Not structured bindings: the lambdas below take them, and Clang 14
3892 // does not let a lambda take a binding
3893 const size_t rows = grid.first, cols = grid.second;
3894 const size_t pixels = rows * cols;
3895 const std::vector<long long> values = pixels == 4 ? std::vector<long long>{0, 2}
3896 : std::vector<long long>{0, 1, 2};
3897 for (long long smooth : {0LL, 1LL})
3898 for_each_matrix(1, 2 * pixels, values, [&] (const Matrix & m)
3899 {
3900 std::vector<std::vector<std::array<double, 2>>> data(
3901 rows, std::vector<std::array<double, 2>>(cols));
3902 for (size_t p = 0; p < pixels; ++p)
3903 data[p / cols][p % cols] = {double(m[0][2 * p]), double(m[0][2 * p + 1])};
3904 auto energy = [&] (unsigned long labels)
3905 {
3906 double e = 0;
3907 for (size_t p = 0; p < pixels; ++p)
3908 e += data[p / cols][p % cols][(labels >> p) & 1UL];
3909 for (size_t p = 0; p < pixels; ++p)
3910 {
3911 const unsigned long here = (labels >> p) & 1UL;
3912 if (p % cols + 1 < cols and here != ((labels >> (p + 1)) & 1UL))
3913 e += double(smooth);
3914 if (p + cols < pixels and here != ((labels >> (p + cols)) & 1UL))
3915 e += double(smooth);
3916 }
3917 return e;
3918 };
3919 double best = std::numeric_limits<double>::max();
3920 for (unsigned long labels = 0; labels < (1UL << pixels); ++labels)
3921 best = std::min(best, energy(labels));
3922 check.run();
3923 const auto r = segment_image(rows, cols, data, double(smooth));
3924 unsigned long got = 0;
3925 bool shaped = r.labels.size() == rows;
3926 for (size_t i = 0; i < rows and shaped; ++i)
3927 {
3928 shaped = r.labels[i].size() == cols;
3929 for (size_t j = 0; j < cols and shaped; ++j)
3930 {
3931 shaped = r.labels[i][j] == 0 or r.labels[i][j] == 1;
3932 got |= (unsigned long) (r.labels[i][j] == 1) << (i * cols + j);
3933 }
3934 }
3935 Spec shown;
3936 shown.n = int(pixels);
3937 const std::string what = std::to_string(rows) + " x " + std::to_string(cols)
3938 + ", smoothness " + std::to_string(smooth) + ", costs " + matrix_text(m) + ": ";
3939 if (not shaped)
3940 check.fail(shown, what + "the labels are not of the image");
3941 else if (r.energy != best or energy(got) != best)
3942 check.fail(shown, what + "the energy is " + text(r.energy) + " for labels of "
3943 + text(energy(got)) + ", not " + text(best));
3944 });
3945 }
3946 check.expect();
3947}
3948
3949namespace
3950{
3955 bool survey_exists(const std::vector<SurveyQuestion> & q, const std::vector<SurveyRespondent> & r)
3956 {
3957 std::vector<std::pair<size_t, size_t>> pairs;
3958 for (size_t i = 0; i < r.size(); ++i)
3959 {
3960 const auto & e = r[i].eligible_questions;
3961 for (size_t j : std::set<size_t>(e.begin(), e.end()))
3962 if (j < q.size())
3963 pairs.push_back({i, j});
3964 }
3965 for (unsigned long set = 0; set < (1UL << pairs.size()); ++set)
3966 {
3967 std::vector<int> by_q(q.size(), 0), by_r(r.size(), 0);
3968 for (size_t k = 0; k < pairs.size(); ++k)
3969 if ((set >> k) & 1UL)
3970 {
3971 ++by_r[pairs[k].first];
3972 ++by_q[pairs[k].second];
3973 }
3974 bool ok = true;
3975 for (size_t j = 0; j < q.size() and ok; ++j)
3976 ok = by_q[j] >= q[j].min_responses and by_q[j] <= q[j].max_responses;
3977 for (size_t i = 0; i < r.size() and ok; ++i)
3978 ok = by_r[i] >= r[i].min_questions and by_r[i] <= r[i].max_questions;
3979 if (ok)
3980 return true;
3981 }
3982 return false;
3983 }
3984}
3985
3986TEST(ExhaustiveNetApps, SurveysMatchTheOracle)
3987{
3988 Check check("design_survey()");
3989
3990 const std::vector<std::pair<int, int>> bounds = {{0, 1}, {1, 1}, {0, 2}, {1, 2}};
3991 for (size_t nq = 1; nq <= 2; ++nq)
3992 for (size_t nr = 1; nr <= 2; ++nr)
3993 {
3994 // The bounds of each question and respondent, and the set of
3995 // questions of each respondent
3996 const size_t knobs = nq + 2 * nr;
3997 std::vector<size_t> pick(knobs, 0);
3998 while (true)
3999 {
4000 std::vector<SurveyQuestion> q;
4001 std::vector<SurveyRespondent> r;
4002 for (size_t j = 0; j < nq; ++j)
4003 q.push_back({j, bounds[pick[j]].first, bounds[pick[j]].second});
4004 for (size_t i = 0; i < nr; ++i)
4005 {
4006 const auto [lo, hi] = bounds[pick[nq + 2 * i]];
4007 std::vector<size_t> eligible;
4008 for (size_t j = 0; j < nq; ++j)
4009 if ((pick[nq + 2 * i + 1] >> j) & 1U)
4010 eligible.push_back(j);
4011 r.push_back({i, lo, hi, eligible});
4012 }
4013 Check & c = check;
4014 c.run();
4015 const auto res = design_survey(q, r);
4016 const bool want = survey_exists(q, r);
4017 std::string what = std::to_string(nq) + " questions";
4018 for (const auto & x : q)
4019 what += " [" + std::to_string(x.min_responses) + ","
4020 + std::to_string(x.max_responses) + "]";
4021 what += ", respondents";
4022 for (const auto & x : r)
4023 {
4024 what += " [" + std::to_string(x.min_questions) + ","
4025 + std::to_string(x.max_questions) + "] of {";
4026 for (size_t j : x.eligible_questions)
4027 what += std::to_string(j);
4028 what += "}";
4029 }
4030 what += ": ";
4031 if (res.feasible != want)
4032 c.fail(Spec(), what + (want ? "says infeasible" : "says feasible"));
4033 else if (want)
4034 {
4035 // The pairs it gives keep every bound
4036 std::vector<int> by_q(nq, 0), by_r(nr, 0);
4037 bool ok = true;
4038 std::set<std::pair<size_t, size_t>> seen;
4039 for (auto [ri, qj] : res.assignments)
4040 {
4041 const auto & e = r[ri < nr ? ri : 0].eligible_questions;
4042 ok = ok and ri < nr and qj < nq and seen.insert({ri, qj}).second
4043 and std::find(e.begin(), e.end(), qj) != e.end();
4044 if (ok)
4045 {
4046 ++by_r[ri];
4047 ++by_q[qj];
4048 }
4049 }
4050 for (size_t j = 0; j < nq and ok; ++j)
4051 ok = by_q[j] >= q[j].min_responses and by_q[j] <= q[j].max_responses;
4052 for (size_t i = 0; i < nr and ok; ++i)
4053 ok = by_r[i] >= r[i].min_questions and by_r[i] <= r[i].max_questions;
4054 if (not ok)
4055 c.fail(Spec(), what + "the answers break a bound");
4056 }
4057 size_t k = 0;
4058 while (k < knobs)
4059 {
4060 const size_t limit = k < nq or (k - nq) % 2 == 0 ? bounds.size() : (1U << nq);
4061 if (++pick[k] < limit)
4062 break;
4063 pick[k++] = 0;
4064 }
4065 if (k == knobs)
4066 break;
4067 }
4068 }
4069 check.expect();
4070}
4071
4072// ======================================================================
4073// Capacities of the nodes, supplies and demands
4074
4075namespace
4076{
4080 long long node_capacity_max_flow(const Spec & s, const std::vector<long long> & node_cap,
4081 int a, int z)
4082 {
4083 long long total = 1;
4084 for (long long w : s.w)
4085 total += w;
4086 Spec x;
4087 x.n = 2 * s.n;
4088 for (int v = 0; v < s.n; ++v)
4089 {
4090 x.arcs.push_back({v, s.n + v});
4091 x.w.push_back(node_cap[size_t(v)] < 0 ? total : node_cap[size_t(v)]);
4092 }
4093 for (size_t i = 0; i < s.arcs.size(); ++i)
4094 {
4095 x.arcs.push_back({s.n + s.arcs[i][0], s.arcs[i][1]});
4096 x.w.push_back(s.w[i]);
4097 }
4098 return max_flow_units(x, a, s.n + z);
4099 }
4100}
4101
4102template <class Net>
4103class ExhaustiveNodeCapacities : public ::testing::Test {};
4104
4106 ::testing::Types<Net_Cap_Graph<Net_Cap_Node<int, long>, Net_Arc<int, long>>,
4108
4110
4111TYPED_TEST(ExhaustiveNodeCapacities, AuxiliaryNetworksMatchTheOracle)
4112{
4113 using Net = TypeParam;
4114 using F = typename Net::Flow_Type;
4115 Check flow("compute_aux_net(), dinic_maximum_flow() and update()");
4116 // The augmenting paths must keep the cookies of the arcs of the
4117 // auxiliary network, which update() follows; they run with one of each
4118 // three assignments of the capacities of the nodes
4119 Check paths("compute_aux_net(), edmonds_karp_maximum_flow() and update()");
4120 Check node_flows("update(), the flows of the nodes");
4121 Check total("get_total_flow()");
4122 Check freed("free_aux_net() and reset_flows()");
4123
4124 for_each_spec(class_domain(), true, [&] (const Spec & raw)
4125 {
4126 const Spec s = structural(raw);
4127 Spec per_node;
4128 per_node.n = s.n;
4129 per_node.arcs.assign(size_t(s.n), {0, 0});
4130 // -1 for a node without limit
4131 size_t assignment = 0;
4132 for_each_assignment(per_node, {-1, 0, 1}, [&] (const Spec & caps)
4133 {
4134 const bool with_paths = assignment++ % 3 == 0;
4135 for (auto [a, z] : ends_of(s))
4136 {
4137 if (a == z)
4138 continue;
4139 Built_Net<Net> b(s);
4140 for (int v = 0; v < s.n; ++v)
4141 if (caps.w[size_t(v)] >= 0)
4142 Net::set_node_cap(b.nodes[size_t(v)], amount<F>(caps.w[size_t(v)]));
4143 b.pin(a, z);
4144 const std::string what = where(b, a, z) + "node capacities "
4145 + matrix_text({caps.w}) + ": ";
4146 const long long want = node_capacity_max_flow(s, caps.w, a, z);
4147
4148 if (with_paths)
4149 {
4150 Built_Net<Net> c(s);
4151 for (int v = 0; v < s.n; ++v)
4152 if (caps.w[size_t(v)] >= 0)
4153 Net::set_node_cap(c.nodes[size_t(v)], amount<F>(caps.w[size_t(v)]));
4154 c.pin(a, z);
4155 paths.run();
4156 auto aux = c.net.compute_aux_net();
4158 bool mapped = true;
4159 for (typename Net::Aux_Net::Arc_Iterator it(*aux); it.has_curr(); it.next_ne())
4160 mapped = mapped and ARC_COOKIE(it.get_curr()) != nullptr;
4161 if (not mapped)
4162 paths.fail(s, what + "an arc of the auxiliary network lost its cookie");
4163 else
4164 {
4165 c.net.update();
4166 if (auto e = max_flow_error(c, c.value(), want); not e.empty())
4167 paths.fail(s, what + e);
4168 }
4169 }
4170
4171 flow.run();
4172 auto aux = b.net.compute_aux_net();
4173 if (not (aux->is_single_source() and aux->is_single_sink()))
4174 {
4175 flow.fail(s, what + "the auxiliary network has no single source and sink");
4176 continue;
4177 }
4178 dinic_maximum_flow(*aux);
4179 b.net.update();
4180 if (auto e = max_flow_error(b, b.value(), want); not e.empty())
4181 {
4182 flow.fail(s, what + e);
4183 continue;
4184 }
4185
4186 node_flows.run();
4187 bool kept = b.net.check_node_capacities();
4188 for (int v = 0; v < s.n and kept; ++v)
4189 {
4190 auto p = b.nodes[size_t(v)];
4191 const F through = std::max(b.net.get_in_flow(p), b.net.get_out_flow(p));
4192 kept = p->in_flow == through and p->out_flow == through;
4193 }
4194 if (not kept)
4195 node_flows.fail(s, what + "a node has not its flow, or passes its capacity");
4196
4197 total.run();
4198 if (b.net.get_total_flow() != b.value())
4199 total.fail(s, what + "gives " + text(b.net.get_total_flow()) + " for a flow of "
4200 + text(b.value()));
4201
4202 freed.run();
4203 b.net.free_aux_net();
4204 const F value = b.value();
4205 b.net.reset_flows();
4206 bool zero = not b.net.has_aux_net() and is_amount(value, want);
4207 for (auto arc : b.arcs)
4208 zero = zero and arc->flow == F{0};
4209 for (int v = 0; v < s.n; ++v)
4210 zero = zero and b.nodes[size_t(v)]->in_flow == F{0};
4211 if (not zero)
4212 freed.fail(s, what + "the flows or the auxiliary network are left");
4213 }
4214 });
4215 });
4216 flow.expect();
4217 paths.expect();
4218 node_flows.expect();
4219 total.expect();
4220 freed.expect();
4221}
4222
4223TEST(ExhaustiveSupplyDemand, TheAuxiliaryNetworkMatchesTheOracle)
4224{
4227 // A node supplies, or demands, at most its out_cap, or in_cap, which
4228 // are unlimited unless set; they are set here to the capacities of its
4229 // arcs, or left unset
4230 Check aux("compute_aux_net()");
4231 Check feasible("is_feasible(), after a maximum flow");
4232 Check trivial("is_feasible(), without supplies or without demands");
4233 Check lists("non_feasible_nodes(), against is_feasible() and the flows of the network");
4234 Check freed("free_aux_net()");
4235
4236 // What non_feasible_nodes() must give: without one of the super nodes,
4237 // every node that supplies and every node that demands; with the two,
4238 // those whose balance of flow over the arcs of the network, without
4239 // those of the super nodes, is not their supply or their demand; and two
4240 // empty lists if and only if is_feasible(). Returns what is wrong, if
4241 // something is
4242 auto lists_error = [] (Built_Net<Net> & b, const Spec & sup) -> std::string
4243 {
4244 DynDlist<Net::Node *> supplies, demands;
4245 b.net.non_feasible_nodes(supplies, demands);
4246 if ((supplies.is_empty() and demands.is_empty()) != b.net.is_feasible())
4247 return "the lists of non_feasible_nodes() and is_feasible() disagree";
4248 const bool both = b.net.get_super_source() != nullptr and b.net.get_super_sink() != nullptr;
4249 size_t want_supplies = 0, want_demands = 0;
4250 for (size_t v = 0; v < b.nodes.size(); ++v)
4251 {
4252 const long w = long(sup.w[v]);
4253 if (w == 0)
4254 continue;
4255 auto p = b.nodes[v];
4256 long shipped = 0; // what leaves p less what enters it
4257 for (Net::Node_Arc_Iterator it(p); it.has_curr(); it.next_ne())
4258 {
4259 auto a = it.get_curr();
4260 auto src = b.net.get_src_node(a);
4261 auto tgt = b.net.get_tgt_node(a);
4262 if (src == b.net.get_super_source() or tgt == b.net.get_super_sink())
4263 continue;
4264 if (src == p)
4265 shipped += a->flow;
4266 if (tgt == p)
4267 shipped -= a->flow;
4268 }
4269 const bool unmet = not both or shipped != w;
4270 bool listed = false;
4271 for (auto it = (w > 0 ? supplies : demands).get_it(); it.has_curr(); it.next_ne())
4272 listed = listed or it.get_curr() == p;
4273 if (listed != unmet)
4274 return "the node " + std::to_string(v) + (unmet ? " is not in its list" : " is in its list");
4275 (w > 0 ? want_supplies : want_demands) += unmet;
4276 }
4277 if (supplies.size() != want_supplies or demands.size() != want_demands)
4278 return "a list has a node that is not of it, or one twice";
4279 return "";
4280 };
4281
4282 for_each_spec(class_domain(), true, [&] (const Spec & raw)
4283 {
4284 const Spec s = structural(raw);
4285 Spec per_node;
4286 per_node.n = s.n;
4287 per_node.arcs.assign(size_t(s.n), {0, 0});
4288 for_each_assignment(per_node, {-1, 0, 1}, [&] (const Spec & sup)
4289 {
4290 const bool any = std::any_of(sup.w.begin(), sup.w.end(),
4291 [] (long long x) { return x != 0; });
4292 for (bool set : {false, true})
4293 {
4294 const std::string what = "supplies " + matrix_text({sup.w})
4295 + (set ? ", the capacities of the nodes set: " : ": ");
4296 Built_Net<Net> b(s);
4297 bool fits = true;
4298 for (int v = 0; v < s.n; ++v)
4299 {
4300 auto p = b.nodes[size_t(v)];
4301 p->supply_flow = long(sup.w[size_t(v)]);
4302 if (set)
4303 {
4304 p->out_cap = b.net.get_out_cap(p);
4305 p->in_cap = b.net.get_in_cap(p);
4306 }
4307 fits = fits and p->supply_flow <= p->out_cap and -p->supply_flow <= p->in_cap;
4308 }
4309 aux.run();
4310 try
4311 {
4312 b.net.compute_aux_net();
4313 if (not fits)
4314 aux.fail(s, what + "takes a supply above the capacity of its node");
4315 }
4316 catch (const std::range_error &)
4317 {
4318 if (fits)
4319 aux.fail(s, what + "throws range_error");
4320 continue;
4321 }
4322 if (not any)
4323 {
4324 if (b.net.exist_aux_net() or b.net.get_num_nodes() != size_t(s.n))
4325 aux.fail(s, what + "adds super nodes without supplies or demands");
4326 continue;
4327 }
4328
4329 // Feasible if the flows from the supplies to the demands fill
4330 // all the arcs of the super nodes
4331 long long supply = 0, demand = 0;
4332 for (long long x : sup.w)
4333 (x > 0 ? supply : demand) += std::abs(x);
4334 Spec x = s;
4335 const int from = x.n++, to = x.n++;
4336 for (int v = 0; v < s.n; ++v)
4337 if (sup.w[size_t(v)] > 0)
4338 {
4339 x.arcs.push_back({from, v});
4340 x.w.push_back(sup.w[size_t(v)]);
4341 }
4342 else if (sup.w[size_t(v)] < 0)
4343 {
4344 x.arcs.push_back({v, to});
4345 x.w.push_back(-sup.w[size_t(v)]);
4346 }
4347 const bool want = supply == demand and supply > 0
4348 and max_flow_units(x, from, to) == supply;
4349
4350 if (supply == 0 or demand == 0)
4351 {
4352 // Without a super source, or without a super sink:
4353 // nothing can be shipped
4354 trivial.run();
4355 if (b.net.is_feasible())
4356 trivial.fail(s, what + "says feasible");
4357 // a flow may fill the arcs of its only super node, to a
4358 // sink of the network or from a source of it: nothing
4359 // is shipped all the same
4360 if (b.net.is_single_source() and b.net.is_single_sink())
4361 {
4363 trivial.run();
4364 if (b.net.is_feasible())
4365 trivial.fail(s, what + "says feasible after a flow");
4366 }
4367 lists.run();
4368 if (const std::string why = lists_error(b, sup); not why.empty())
4369 lists.fail(s, what + why);
4370 }
4371 else if (not (b.net.is_single_source() and b.net.is_single_sink()))
4372 aux.fail(s, what + std::to_string(b.net.get_src_nodes().size()) + " sources and "
4373 + std::to_string(b.net.get_sink_nodes().size()) + " sinks");
4374 else
4375 {
4376 feasible.run();
4378 if (b.net.is_feasible() != want)
4379 feasible.fail(s, what + (want ? "says infeasible" : "says feasible"));
4380 lists.run();
4381 if (const std::string why = lists_error(b, sup); not why.empty())
4382 lists.fail(s, what + why);
4383 }
4384
4385 freed.run();
4386 b.net.free_aux_net();
4387 if (b.net.exist_aux_net() or b.net.get_num_nodes() != size_t(s.n)
4388 or b.net.get_num_arcs() != s.num_arcs())
4389 freed.fail(s, what + "the network is not as it was");
4390 }
4391 });
4392 });
4393 aux.expect();
4394 feasible.expect();
4395 trivial.expect();
4396 lists.expect();
4397 freed.expect();
4398}
4399
4400// ======================================================================
4401// Copies
4402
4403namespace
4404{
4408 template <class Net, class Node_Extra, class Arc_Extra>
4409 std::vector<double> contents(const Net & net, Node_Extra node_extra, Arc_Extra arc_extra)
4410 {
4411 std::vector<double> r;
4412 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
4413 {
4414 r.push_back(it.get_curr()->get_info());
4415 r.push_back(node_extra(it.get_curr()));
4416 }
4417 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
4418 {
4419 auto a = it.get_curr();
4420 r.push_back(net.get_src_node(a)->get_info());
4421 r.push_back(net.get_tgt_node(a)->get_info());
4422 r.push_back(double(a->cap));
4423 r.push_back(double(a->flow));
4424 r.push_back(arc_extra(a));
4425 }
4426 return r;
4427 }
4428
4434 template <class Net, class Node_Extra, class Arc_Extra, class Prepare>
4435 void check_copies(Check & ctor, Check & assign, Check & cookie, Check & move,
4436 Node_Extra node_extra, Arc_Extra arc_extra, Prepare prepare)
4437 {
4438 for_each_spec(domain(3, 2), true, [&] (const Spec & raw)
4439 {
4440 const Spec s = structural(raw);
4441 Built_Net<Net> b(s);
4442 if (s.n >= 2)
4443 {
4444 b.pin(0, s.n - 1);
4445 put_initial_flow(b);
4446 }
4447 prepare(b);
4448 const auto want = contents(b.net, node_extra, arc_extra);
4449
4450 ctor.run();
4451 {
4452 const Net copy(b.net);
4453 if (contents(copy, node_extra, arc_extra) != want)
4454 ctor.fail(s, "the copy is not the network");
4455 }
4456
4457 assign.run();
4458 cookie.run();
4459 {
4460 Built_Net<Net> other(structural(raw));
4461 int mark = 0;
4462 other.net.get_cookie() = &mark;
4463 other.net = b.net;
4464 if (contents(other.net, node_extra, arc_extra) != want)
4465 assign.fail(s, "the network assigned is not the network");
4466 if (other.net.get_cookie() != &mark)
4467 cookie.fail(s, "the cookie of the target is lost");
4468 }
4469
4470 move.run();
4471 {
4472 Built_Net<Net> fresh(s);
4473 if (s.n >= 2)
4474 {
4475 fresh.pin(0, s.n - 1);
4476 put_initial_flow(fresh);
4477 }
4478 prepare(fresh);
4479 const auto before = contents(fresh.net, node_extra, arc_extra);
4480 Net moved(std::move(fresh.net));
4481 Net target;
4482 target = std::move(moved);
4483 if (contents(target, node_extra, arc_extra) != before)
4484 move.fail(s, "the network moved is not the network");
4485 }
4486 });
4487 }
4488
4489 template <class P>
4490 double nothing(P) { return 0; }
4491}
4492
4493TEST(ExhaustiveNetworkCopies, CopiesKeepTheNetwork)
4494{
4499
4500 Check plain_ctor("Net_Graph(const Net_Graph &)");
4501 Check plain_assign("Net_Graph::operator=(const Net_Graph &)");
4502 // operator=() copies and swaps, and the target keeps its cookie
4503 Check plain_cookie("Net_Graph::operator=(const Net_Graph &), the cookie");
4504 Check plain_move("Net_Graph(Net_Graph &&) and operator=(Net_Graph &&)");
4505 check_copies<Plain>(plain_ctor, plain_assign, plain_cookie, plain_move,
4506 nothing<Plain::Node *>, nothing<Plain::Arc *>, [] (auto &) {});
4507
4508 Check cost_ctor("Net_Cost_Graph(const Net_Cost_Graph &)");
4509 Check cost_assign("Net_Cost_Graph::operator=(const Net_Cost_Graph &)");
4510 Check cost_cookie("Net_Cost_Graph::operator=(const Net_Cost_Graph &), the cookie");
4511 Check cost_move("Net_Cost_Graph(Net_Cost_Graph &&) and operator=(Net_Cost_Graph &&)");
4512 check_copies<Cost>(cost_ctor, cost_assign, cost_cookie, cost_move, nothing<Cost::Node *>,
4513 [] (Cost::Arc * a) { return double(a->cost); },
4514 [] (Built_Net<Cost> & b)
4515 {
4516 long c = 1;
4517 for (auto a : b.arcs)
4518 a->cost = c++;
4519 });
4520
4521 // The node fields, small numbers, as one number of a few digits each
4522 auto digits = [] (std::initializer_list<long> fields)
4523 {
4524 double r = 0;
4525 for (long x : fields)
4526 r = 100 * r + double(x);
4527 return r;
4528 };
4529
4530 Check cap_ctor("Net_Cap_Graph(const Net_Cap_Graph &), the capacities and flows of the nodes");
4531 Check cap_assign("Net_Cap_Graph::operator=(const Net_Cap_Graph &), the capacities and flows"
4532 " of the nodes");
4533 Check cap_cookie("Net_Cap_Graph::operator=(const Net_Cap_Graph &), the cookie");
4534 Check cap_move("Net_Cap_Graph(Net_Cap_Graph &&) and operator=(Net_Cap_Graph &&)");
4535 check_copies<Cap>(cap_ctor, cap_assign, cap_cookie, cap_move,
4536 [&] (Cap::Node * p) { return digits({p->max_cap, p->in_flow, p->out_flow}); },
4537 nothing<Cap::Arc *>,
4538 [] (Built_Net<Cap> & b)
4539 {
4540 long c = 1;
4541 for (auto p : b.nodes)
4542 {
4543 Cap::set_node_cap(p, c);
4544 p->in_flow = c + 10;
4545 p->out_flow = c + 20;
4546 ++c;
4547 }
4548 });
4549
4550 Check sup_ctor("Net_Sup_Dem_Graph(const Net_Sup_Dem_Graph &), the supplies, capacities and"
4551 " flows of the nodes");
4552 Check sup_assign("Net_Sup_Dem_Graph::operator=(const Net_Sup_Dem_Graph &), the supplies,"
4553 " capacities and flows of the nodes");
4554 Check sup_cookie("Net_Sup_Dem_Graph::operator=(const Net_Sup_Dem_Graph &), the cookie");
4555 Check sup_move("Net_Sup_Dem_Graph(Net_Sup_Dem_Graph &&) and its move assignment");
4556 check_copies<Sup>(sup_ctor, sup_assign, sup_cookie, sup_move,
4557 [&] (Sup::Node * p)
4558 {
4559 return digits({p->supply_flow, p->out_cap, p->in_cap, p->in_flow,
4560 p->out_flow});
4561 },
4562 nothing<Sup::Arc *>,
4563 [] (Built_Net<Sup> & b)
4564 {
4565 long c = 1;
4566 for (auto p : b.nodes)
4567 {
4568 p->supply_flow = c;
4569 p->out_cap = c + 10;
4570 p->in_cap = c + 20;
4571 p->in_flow = c + 30;
4572 p->out_flow = c + 40;
4573 ++c;
4574 }
4575 });
4576
4577 for (const Check * c : {&plain_ctor, &plain_assign, &plain_cookie, &plain_move, &cost_ctor,
4578 &cost_assign, &cost_cookie, &cost_move, &cap_ctor, &cap_assign,
4579 &cap_cookie, &cap_move, &sup_ctor, &sup_assign, &sup_cookie, &sup_move})
4580 c->expect();
4581}
4582
4583// ======================================================================
4584// Networks when memory runs out
4585
4586namespace
4587{
4589 template <class Make, class Op>
4590 size_t allocations_of(Make make, Op op)
4591 {
4592 auto st = make();
4593 const size_t before = allocations;
4594 op(*st);
4595 return allocations - before;
4596 }
4597
4603 template <class Make, class Op, class After, class Leave_Out>
4604 void for_each_failure(Make make, Op op, After after, Leave_Out leave_out)
4605 {
4606 const size_t points = allocations_of(make, op);
4607 for (size_t k = 1; k <= points; ++k)
4608 {
4609 if (leave_out(k))
4610 continue;
4611 auto st = make();
4612 bool threw = false;
4613 {
4614 Fail_At fail(k);
4615 try
4616 {
4617 op(*st);
4618 }
4619 catch (const std::bad_alloc &)
4620 {
4621 threw = true;
4622 }
4623 }
4624 after(*st, k, threw);
4625 }
4626 }
4627
4628 template <class Make, class Op, class After>
4629 void for_each_failure(Make make, Op op, After after)
4630 {
4631 for_each_failure(make, op, after, [] (size_t) { return false; });
4632 }
4633
4636 template <class Net>
4637 std::vector<long> net_state(const Net & net)
4638 {
4639 std::vector<long> r = {long(net.get_num_nodes()), long(net.get_num_arcs()),
4640 long(net.get_src_nodes().size()), long(net.get_sink_nodes().size()),
4641 long(net.with_super_source), long(net.with_super_sink)};
4642 for (auto it = net.get_src_nodes().get_it(); it.has_curr(); it.next_ne())
4643 r.push_back(it.get_curr()->get_info());
4644 for (auto it = net.get_sink_nodes().get_it(); it.has_curr(); it.next_ne())
4645 r.push_back(1000 + it.get_curr()->get_info());
4646 std::sort(r.begin() + 6, r.end());
4647 return r;
4648 }
4649
4652 template <class Net>
4653 bool ends_kept(const Net & net)
4654 {
4655 for (typename Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
4656 {
4657 auto p = it.get_curr();
4658 bool in = false, out = false;
4659 for (typename Net::Node_Arc_Iterator j(p); j.has_curr(); j.next_ne())
4660 {
4661 in = in or net.get_tgt_node(j.get_curr()) == p;
4662 out = out or net.get_src_node(j.get_curr()) == p;
4663 }
4664 if (net.is_source(p) == in or net.is_sink(p) == out)
4665 return false;
4666 }
4667 return true;
4668 }
4669}
4670
4671class ExhaustiveFlowMemory : public ::testing::Test
4672{
4673protected:
4674 void SetUp() override
4675 {
4677 GTEST_SKIP() << "ThreadSanitizer replaces the global operator new";
4678 }
4679};
4680
4681TEST_F(ExhaustiveFlowMemory, SuperNodesWhenMemoryRunsOut)
4682{
4684 using B = Built_Net<Net>;
4685 // A failure leaves the network as it was
4686 Check source("make_super_source(), a failed allocation");
4687 Check sink("make_super_sink(), a failed allocation");
4688 Check nodes("make_super_nodes(), a failed allocation");
4689 // A failure leaves the super node, maybe with fewer arcs, and the sets
4690 // of sources and sinks right; another call goes on
4691 Check unmake("unmake_super_source() and unmake_super_sink(), a failed allocation");
4692 // Even after one that took some arcs of the super node, whose ends are
4693 // sources, or sinks, again: the network keeps its super node
4694 Check again("unmake_super_source() and unmake_super_sink(), another call after a failed one");
4695
4696 for_each_spec(domain(3, 3), true, [&] (const Spec & raw)
4697 {
4698 const Spec s = structural(raw);
4699 // Not structured bindings, which the lambdas below could not take with
4700 // Clang 14
4701 const auto ends = ends_by_arcs(s);
4702 const auto & sources = ends.first;
4703 const auto & sinks = ends.second;
4704 auto make = [&] { return std::make_unique<B>(s); };
4705 const auto before = net_state(B(s).net);
4706 auto after = [&] (Check & check)
4707 {
4708 return [&] (B & b, size_t k, bool threw)
4709 {
4710 check.run();
4711 if (threw and net_state(b.net) != before)
4712 check.fail(s, "the allocation " + std::to_string(k)
4713 + " fails, and the network is not as it was");
4714 };
4715 };
4716 if (sources.size() > 1)
4717 for_each_failure(make, [] (B & b) { b.net.make_super_source(); }, after(source));
4718 if (sinks.size() > 1)
4719 for_each_failure(make, [] (B & b) { b.net.make_super_sink(); }, after(sink));
4720 if (sources.empty() or sinks.empty() or (sources.size() < 2 and sinks.size() < 2))
4721 return;
4722
4723 for_each_failure(make, [] (B & b) { b.net.make_super_nodes(); }, after(nodes));
4724
4725 // The super nodes made, each undone with a failure
4726 auto made = [&] { auto b = make(); b->net.make_super_nodes(); return b; };
4727 for (int which = 0; which < 2; ++which)
4728 {
4729 auto op = [which] (B & b)
4730 {
4731 if (which == 0)
4732 b.net.unmake_super_source();
4733 else
4734 b.net.unmake_super_sink();
4735 };
4736 const auto undone = [&]
4737 {
4738 auto b = made();
4739 op(*b);
4740 return net_state(b->net);
4741 }();
4742 for_each_failure(made, op, [&] (B & b, size_t k, bool threw)
4743 {
4744 unmake.run();
4745 const std::string at = "the allocation " + std::to_string(k) + " fails";
4746 if (not ends_kept(b.net))
4747 {
4748 unmake.fail(s, at + ", and the sources or sinks are wrong");
4749 return;
4750 }
4751 if (not threw)
4752 return;
4753 again.run();
4754 op(b);
4755 if (net_state(b.net) != undone)
4756 again.fail(s, at + ", and another call does not undo the super node");
4757 });
4758 }
4759 });
4760 for (const Check * c : {&source, &sink, &nodes, &unmake, &again})
4761 c->expect();
4762}
4763
4764TEST_F(ExhaustiveFlowMemory, SuppliesWhenMemoryRunsOut)
4765{
4767 // Two supplies and two demands, with each auxiliary network that a
4768 // network may have: the two super nodes (0), the super source alone (1)
4769 // and the super sink alone (2). The arc of a super node is the only one
4770 // that enters a supply, or that leaves a demand: when it goes, its end is
4771 // a source, or a sink, again, which allocates; and a super node has two
4772 // arcs, so that its removal may fail with one of them gone
4773 struct Shipment
4774 {
4775 Net net;
4776 Net from; // another one, to copy
4777 Net::Net_Class plain; // and one that is not of supplies
4778 Net::Node * source = nullptr;
4779 Net::Node * sink = nullptr;
4780
4781 explicit Shipment(const int aux)
4782 {
4783 auto s1 = net.insert_node(0, aux == 2 ? 0 : 10);
4784 auto s2 = net.insert_node(1, aux == 2 ? 0 : 5);
4785 auto t1 = net.insert_node(2, aux == 1 ? 0 : -10);
4786 auto t2 = net.insert_node(3, aux == 1 ? 0 : -5);
4787 net.insert_arc(s1, t1, 20);
4788 net.insert_arc(s2, t2, 20);
4789 net.compute_aux_net();
4790 source = net.get_super_source();
4791 sink = net.get_super_sink();
4792 auto x = from.insert_node(0, 3);
4793 auto y = from.insert_node(1, -3);
4794 from.insert_arc(x, y, 6);
4795 auto u = plain.insert_node(0);
4796 auto v = plain.insert_node(1);
4797 plain.insert_arc(u, v, 1);
4798 }
4799 };
4800 // What every operation must leave, also when it fails: the network
4801 // remembers the super nodes that it has, and no other. Here, where no
4802 // other node comes or goes, it has its four nodes and those
4803 auto kept = [] (const Net & net)
4804 {
4805 size_t found = 0;
4806 for (Net::Node_Iterator it(net); it.has_curr(); it.next_ne())
4807 if (it.get_curr() == net.get_super_source() or it.get_curr() == net.get_super_sink())
4808 ++found;
4809 const size_t remembered = size_t(net.get_super_source() != nullptr)
4810 + size_t(net.get_super_sink() != nullptr);
4811 return found == remembered and net.get_num_nodes() == 4 + remembered;
4812 };
4813 const char * const names[] = {"remove_node() of the super source", "remove_node() of the super sink",
4814 "free_aux_net()", "a copy assignment through the base",
4815 "copy_graph() into the network"};
4816 size_t failures[5] = {0, 0, 0, 0, 0};
4817 const size_t arcs_made[3] = {6, 4, 4}; // those of the network and of its super nodes
4818 size_t partial = 0; // removals that failed with an arc gone
4819 for (int aux = 0; aux < 3; ++aux)
4820 for (int which = 0; which < 5; ++which)
4821 {
4822 {
4823 const Shipment probe(aux);
4824 if ((which == 0 and probe.source == nullptr) or (which == 1 and probe.sink == nullptr))
4825 continue; // it has no such super node
4826 }
4827 auto make = [aux] { return std::make_unique<Shipment>(aux); };
4828 for_each_failure(make,
4829 [which] (Shipment & sh)
4830 {
4831 if (which == 0)
4832 sh.net.remove_node(sh.source);
4833 else if (which == 1)
4834 sh.net.remove_node(sh.sink);
4835 else if (which == 2)
4836 sh.net.free_aux_net();
4837 else if (which == 3)
4838 static_cast<Net::Net_Class &>(sh.net) = sh.plain;
4839 else
4840 copy_graph(sh.net, sh.from);
4841 },
4842 [&] (Shipment & sh, size_t k, bool threw)
4843 {
4844 const std::string at = std::string(names[which]) + ", the auxiliary network "
4845 + std::to_string(aux) + ", the allocation " + std::to_string(k) + " fails";
4846 EXPECT_TRUE(threw) << at;
4847 if (not threw)
4848 return;
4849 ++failures[which];
4850 if (which == 4)
4851 {
4852 // copy_graph() empties the network that it could not fill
4853 EXPECT_EQ(sh.net.get_num_nodes(), 0u) << at;
4854 EXPECT_FALSE(sh.net.exist_aux_net()) << at;
4855 return;
4856 }
4857 // the removal that failed left the super node in the
4858 // network, and remembered, maybe with an arc less
4859 ASSERT_TRUE(kept(sh.net)) << at;
4860 if (which < 3 and sh.net.get_num_arcs() < arcs_made[aux])
4861 ++partial;
4862 if (which == 0 or which == 3)
4863 {
4864 EXPECT_EQ(sh.net.get_super_source(), sh.source) << at;
4865 }
4866 if (which == 1 or which == 3)
4867 {
4868 EXPECT_EQ(sh.net.get_super_sink(), sh.sink) << at;
4869 }
4870 // and another call goes on
4871 sh.net.free_aux_net();
4872 EXPECT_FALSE(sh.net.exist_aux_net()) << at;
4873 EXPECT_EQ(sh.net.get_num_nodes(), 4u) << at;
4874 EXPECT_EQ(sh.net.get_num_arcs(), 2u) << at;
4875 });
4876 }
4877 for (int which = 0; which < 5; ++which)
4878 EXPECT_GT(failures[which], 0u) << names[which] << ": no allocation failed, nothing was checked";
4879 EXPECT_GT(partial, 0u) << "no removal failed with an arc of the super node gone";
4880}
4881
4882TEST_F(ExhaustiveFlowMemory, CopiesWhenMemoryRunsOut)
4883{
4886 // A copy that fails leaves the target empty, even when memory stays
4887 // out, though removing an arc of a network allocates
4888 Check single("copy_graph(), into a network, a failed allocation");
4889 Check persistent("copy_graph(), into a network, without memory");
4890 Check inter_single("inter_copy_graph(), into a network, a failed allocation");
4891 Check inter_persistent("inter_copy_graph(), into a network, without memory");
4892
4893 struct Pair
4894 {
4895 Built_Net<Net> to;
4896 Built_Net<Net> from;
4897 Pair(const Spec & a, const Spec & b) : to(a), from(b) {}
4898 };
4899 struct Inter_Pair
4900 {
4901 Built_Net<Net> to;
4902 Built_Net<Other> from;
4903 Inter_Pair(const Spec & a, const Spec & b) : to(a), from(b) {}
4904 };
4905
4906 Spec target;
4907 target.n = 3;
4908 target.arcs = {{0, 1}, {1, 2}};
4909 target = structural(target);
4910 for_each_spec(domain(3, 2), true, [&] (const Spec & raw)
4911 {
4912 const Spec s = structural(raw);
4913 auto make = [&] { return std::make_unique<Pair>(target, s); };
4914 for_each_failure(make, [] (Pair & p) { copy_graph(p.to.net, p.from.net); },
4915 [&] (Pair & p, size_t k, bool threw)
4916 {
4917 single.run();
4918 if (threw and (p.to.net.get_num_nodes() != 0
4919 or p.to.net.get_num_arcs() != 0))
4920 single.fail(s, "the allocation " + std::to_string(k)
4921 + " fails, and the target is not empty");
4922 });
4923 auto make_inter = [&] { return std::make_unique<Inter_Pair>(target, s); };
4924 for_each_failure(make_inter, [] (Inter_Pair & p) { inter_copy_graph(p.to.net, p.from.net); },
4925 [&] (Inter_Pair & p, size_t k, bool threw)
4926 {
4927 inter_single.run();
4928 if (threw and (p.to.net.get_num_nodes() != 0
4929 or p.to.net.get_num_arcs() != 0))
4930 inter_single.fail(s, "the allocation " + std::to_string(k)
4931 + " fails, and the target is not empty");
4932 });
4933
4934 // No memory from the first allocation on
4935 for (Check * c : {&persistent, &inter_persistent})
4936 {
4937 Pair p(target, s);
4938 Inter_Pair q(target, s);
4939 bool threw = false;
4940 {
4941 No_Memory none;
4942 try
4943 {
4944 if (c == &persistent)
4945 copy_graph(p.to.net, p.from.net);
4946 else
4947 inter_copy_graph(q.to.net, q.from.net);
4948 }
4949 catch (const std::bad_alloc &)
4950 {
4951 threw = true;
4952 }
4953 }
4954 const auto & to = c == &persistent ? p.to.net : q.to.net;
4955 c->run();
4956 if (not threw)
4957 c->fail(s, "copies without memory");
4958 else if (to.get_num_nodes() != 0 or to.get_num_arcs() != 0)
4959 c->fail(s, "the target keeps " + std::to_string(to.get_num_nodes()) + " nodes and "
4960 + std::to_string(to.get_num_arcs()) + " arcs");
4961 }
4962 });
4963 single.expect();
4964 persistent.expect();
4965 inter_single.expect();
4966 inter_persistent.expect();
4967}
4968
4969TEST_F(ExhaustiveFlowMemory, NodeCapacitiesWhenMemoryRunsOut)
4970{
4972 // The copy assignment gives the strong guarantee: a copy that fails
4973 // leaves the network as it was, with its auxiliary network
4974 Check assign("Net_Cap_Graph::operator=(const Net_Cap_Graph &), a failed allocation");
4975 // free_aux_net(), the destructor and the move assignment free the
4976 // auxiliary network without allocating, as removing the arcs of a
4977 // network would, so that nothing can fail there
4978 Check freeing("free_aux_net(), without allocating");
4979 Check dtor("~Net_Cap_Graph(), with its auxiliary network, without allocating");
4980 Check move("Net_Cap_Graph::operator=(Net_Cap_Graph &&), without allocating");
4981
4982 struct Two
4983 {
4984 Built_Net<Net> x;
4985 Built_Net<Net> y;
4986 Two(const Spec & a, const Spec & b) : x(a), y(b)
4987 {
4988 long c = 1;
4989 for (auto p : x.nodes)
4990 Net::set_node_cap(p, c++);
4991 x.net.compute_aux_net();
4992 }
4993 };
4994
4995 Spec other;
4996 other.n = 2;
4997 other.arcs = {{0, 1}};
4998 other = structural(other);
4999 for_each_spec(domain(3, 2), true, [&] (const Spec & raw)
5000 {
5001 const Spec s = structural(raw);
5002 auto make = [&] { return std::make_unique<Two>(s, other); };
5003 const auto before = [&]
5004 {
5005 auto t = make();
5006 return contents(t->x.net, [] (Net::Node * p) { return double(p->max_cap); },
5007 nothing<Net::Arc *>);
5008 }();
5009 for_each_failure(make, [] (Two & t) { t.x.net = t.y.net; },
5010 [&] (Two & t, size_t k, bool threw)
5011 {
5012 assign.run();
5013 const auto now = contents(t.x.net, [] (Net::Node * p)
5014 { return double(p->max_cap); },
5015 nothing<Net::Arc *>);
5016 if (threw and (now != before or not t.x.net.has_aux_net()))
5017 assign.fail(s, "the allocation " + std::to_string(k)
5018 + " fails, and the network is not as it was");
5019 });
5020 freeing.run();
5021 if (const size_t k = allocations_of(make, [] (Two & t) { t.x.net.free_aux_net(); }); k != 0)
5022 freeing.fail(s, "makes " + std::to_string(k) + " allocations");
5023 struct Owned
5024 {
5025 std::unique_ptr<Two> two;
5026 Owned(const Spec & a, const Spec & b) : two(std::make_unique<Two>(a, b)) {}
5027 };
5028 dtor.run();
5029 if (const size_t k = allocations_of([&] { return std::make_unique<Owned>(s, other); },
5030 [] (Owned & o) { o.two.reset(); });
5031 k != 0)
5032 dtor.fail(s, "makes " + std::to_string(k) + " allocations");
5033 move.run();
5034 if (const size_t k = allocations_of(make, [] (Two & t) { t.x.net = std::move(t.y.net); });
5035 k != 0)
5036 move.fail(s, "makes " + std::to_string(k) + " allocations");
5037 });
5038 assign.expect();
5039 freeing.expect();
5040 dtor.expect();
5041 move.expect();
5042}
5043
5044namespace
5045{
5047
5054 struct Removal_Watched_Net : Long_Cost_Net
5055 {
5056 bool failed_in_removal = false;
5057
5058 void remove_node(Node * p) override
5059 {
5060 try
5061 {
5062 Long_Cost_Net::remove_node(p);
5063 }
5064 catch (const std::bad_alloc &)
5065 {
5066 failed_in_removal = true;
5067 throw;
5068 }
5069 }
5070 };
5071}
5072
5073TEST_F(ExhaustiveFlowMemory, CheapestFlowsWhenMemoryRunsOut)
5074{
5075 using Net = Long_Cost_Net;
5076 using Watched = Removal_Watched_Net;
5077 using F = Net::Flow_Type;
5078 // A throw leaves the flows as they were, though Dijkstra allocates its
5079 // heap after the flows of a path have changed
5080 Check ssp("successive_shortest_paths(), a failed allocation");
5081 // A throw leaves the network as it was, unless the failure came where
5082 // the super nodes are removed, outside any destructor: then they may
5083 // stay, with the network and its sources and sinks right
5084 Check transshipment("solve_transshipment(), a failed allocation");
5085 Check removal("solve_transshipment(), a failed allocation in the removal of its super nodes");
5086
5087 small_structural_specs<Net>()([&] (const Spec & s)
5088 {
5089 if (s.n < 2)
5090 return;
5091 const auto cost = structural_costs(s);
5092 auto make = [&]
5093 {
5094 auto b = std::make_unique<Built_Net<Net>>(s, s.w, cost);
5095 b->pin(0, s.n - 1);
5096 return b;
5097 };
5098 for_each_failure(make, [] (Built_Net<Net> & b) { successive_shortest_paths(b.net); },
5099 [&] (Built_Net<Net> & b, size_t k, bool threw)
5100 {
5101 ssp.run();
5102 bool zero = true;
5103 for (auto a : b.arcs)
5104 zero = zero and a->flow == F{0};
5105 if (threw and not zero)
5106 ssp.fail(s, "the allocation " + std::to_string(k)
5107 + " fails, and the flows changed");
5108 });
5109
5110 // Node 0 supplies one unit to the last node, which needs it, if the
5111 // network can ship it
5112 std::vector<long long> d(size_t(s.n), 0);
5113 d[0] = 1;
5114 d[size_t(s.n - 1)] = -1;
5115 if (best_transshipment(s, cost, d) < 0)
5116 return;
5117 auto plain = [&] { return std::make_unique<Built_Net<Watched>>(s, s.w, cost); };
5118 auto demand_of = [d] (const Built_Net<Watched> & b)
5119 {
5120 return [&b, d] (Watched::Node * p)
5121 {
5122 for (int v = 0; v < int(b.nodes.size()); ++v)
5123 if (b.nodes[size_t(v)] == p)
5124 return amount<F>(d[size_t(v)]);
5125 return F{0};
5126 };
5127 };
5128 for_each_failure(plain,
5129 [&] (Built_Net<Watched> & b) { solve_transshipment(b.net, demand_of(b)); },
5130 [&] (Built_Net<Watched> & b, size_t k, bool threw)
5131 {
5132 const std::string at = "the allocation " + std::to_string(k) + " fails";
5133 if (b.net.failed_in_removal)
5134 {
5135 // The nodes and arcs of the network stay
5136 removal.run();
5137 const std::set<Watched::Node *> nodes(b.nodes.begin(),
5138 b.nodes.end());
5139 const std::set<Watched::Arc *> arcs(b.arcs.begin(), b.arcs.end());
5140 size_t kept_nodes = 0, kept_arcs = 0;
5141 for (Node_Iterator<Watched> it(b.net); it.has_curr(); it.next_ne())
5142 kept_nodes += nodes.count(it.get_curr());
5143 for (Arc_Iterator<Watched> it(b.net); it.has_curr(); it.next_ne())
5144 kept_arcs += arcs.count(it.get_curr());
5145 if (not threw)
5146 removal.fail(s, at + " in a removal, and nothing throws");
5147 else if (kept_nodes != nodes.size() or kept_arcs != arcs.size())
5148 removal.fail(s, at + ", and nodes or arcs of the network go");
5149 else if (not ends_kept(b.net))
5150 removal.fail(s, at + ", and the sources or sinks are wrong");
5151 return;
5152 }
5153 transshipment.run();
5154 if (threw and (b.net.get_num_nodes() != size_t(s.n)
5155 or b.net.get_num_arcs() != s.num_arcs()))
5156 transshipment.fail(s, at + ", and the super nodes stay");
5157 });
5158 });
5159 ssp.expect();
5160 transshipment.expect();
5161 removal.expect();
5162}
5163
5164// ======================================================================
5165// Johnson, with integer weights next to the limits
5166
5167TEST(ExhaustiveJohnson, IntegerDistancesThatFitDoNotOverflow)
5168{
5170 constexpr long long Max = std::numeric_limits<int>::max();
5171 Check build("Johnson(g)");
5172 // A reweighted arc, w + h(u) - h(v), passes max() when h(v) < h(u),
5173 // though no distance does
5174 Check build_over("Johnson(g), a reweighted arc beyond max()");
5175 Check distances("Johnson::get_distance()");
5176 // Dijkstra adds the reweighted arcs, and a sum d(s, u) + w + h(s) -
5177 // h(v) may pass max(), though d(s, v) fits
5178 Check distances_over("Johnson::get_distance(), a reweighted sum beyond max()");
5179 Check negative("Johnson(g), with a negative cycle");
5180
5181 auto run = [&] (const Spec & s)
5182 {
5183 bool neg = false;
5184 const auto d = oracle::shortest_distances(s, true, neg);
5185 GT g;
5186 std::vector<GT::Node *> nodes;
5187 for (int i = 0; i < s.n; ++i)
5188 nodes.push_back(g.insert_node(i));
5189 for (size_t i = 0; i < s.arcs.size(); ++i)
5190 g.insert_arc(nodes[size_t(s.arcs[i][0])], nodes[size_t(s.arcs[i][1])], int(s.w[i]));
5191 if (neg)
5192 {
5193 negative.run();
5194 try
5195 {
5196 Johnson<GT> j(g);
5197 negative.fail(s, "does not throw");
5198 }
5199 catch (const std::domain_error &) {}
5200 catch (const std::exception & e)
5201 {
5202 negative.fail(s, std::string("throws ") + e.what());
5203 }
5204 return;
5205 }
5206
5207 // The potentials: the distances from a node joined to all by arcs of 0
5208 std::vector<long long> h(size_t(s.n), 0);
5209 for (int u = 0; u < s.n; ++u)
5210 for (int v = 0; v < s.n; ++v)
5211 if (d[size_t(u)][size_t(v)] != oracle::Inf)
5212 h[size_t(v)] = std::min(h[size_t(v)], d[size_t(u)][size_t(v)]);
5213 bool over = false;
5214 for (size_t i = 0; i < s.arcs.size(); ++i)
5215 over = over or s.w[i] + h[size_t(s.arcs[i][0])] - h[size_t(s.arcs[i][1])] > Max;
5216 Check & c = over ? build_over : build;
5217 c.run();
5218 std::unique_ptr<Johnson<GT>> j;
5219 try
5220 {
5221 j = std::make_unique<Johnson<GT>>(g);
5222 }
5223 catch (const std::exception & e)
5224 {
5225 c.fail(s, std::string("throws ") + e.what());
5226 return;
5227 }
5228
5229 for (int a = 0; a < s.n; ++a)
5230 {
5231 bool sum_over = false;
5232 for (size_t i = 0; i < s.arcs.size(); ++i)
5233 {
5234 const int u = s.arcs[i][0], v = s.arcs[i][1];
5235 if (d[size_t(a)][size_t(u)] != oracle::Inf)
5236 sum_over = sum_over or d[size_t(a)][size_t(u)] + s.w[i] + h[size_t(a)]
5237 - h[size_t(v)] > Max;
5238 }
5239 Check & dc = sum_over ? distances_over : distances;
5240 dc.run();
5241 for (int z = 0; z < s.n; ++z)
5242 {
5243 const long long want = d[size_t(a)][size_t(z)];
5244 const std::string at = "from " + std::to_string(a) + " to " + std::to_string(z)
5245 + ": ";
5246 try
5247 {
5248 const long long got = j->get_distance(nodes[size_t(a)], nodes[size_t(z)]);
5249 if (want == oracle::Inf ? got != Max : want > Max or got != want)
5250 {
5251 dc.fail(s, at + "gives " + std::to_string(got) + ", not "
5252 + (want == oracle::Inf ? "max()" : std::to_string(want)));
5253 break;
5254 }
5255 }
5256 catch (const std::overflow_error & e)
5257 {
5258 if (want != oracle::Inf and want <= Max)
5259 {
5260 dc.fail(s, at + "throws " + e.what() + " for " + std::to_string(want));
5261 break;
5262 }
5263 }
5264 }
5265 }
5266 };
5267
5268 // Small weights, on every digraph of 3 nodes and 3 arcs
5269 for_each_spec(domain(3, 3), true, [&] (const Spec & s)
5270 {
5271 for_each_assignment(s, {-1, 0, 2}, run);
5272 });
5273 // Weights next to the limits, on every one of 3 nodes and 2 arcs
5274 Domain d = domain(3, 2);
5275 for_each_spec(d, true, [&] (const Spec & s)
5276 {
5277 for_each_assignment(s, {-10, 1, Max - 5}, run);
5278 });
5279 build.expect();
5280 build_over.expect();
5281 distances.expect();
5282 distances_over.expect();
5283 negative.expect();
5284}
5285
5286// ======================================================================
5287// The members of the networks, and their residual networks
5288
5289TYPED_TEST(ExhaustiveMaxFlow, MembersKeepTheirContracts)
5290{
5291 using Net = TypeParam;
5292 using F = typename Net::Flow_Type;
5293 Check sums("get_in_cap(), get_out_cap(), get_in_flow(), get_out_flow() and the degrees");
5294 Check lists("out_arcs(), in_arcs(), out_nodes() and in_nodes()");
5295 Check checks("check_node(), check_network() and flow_value()");
5296 Check setters("set_cap(), set_flow(), get_cap(), get_flow() and reset()");
5297
5298 small_structural_specs<Net>()([&] (const Spec & s)
5299 {
5300 for (auto [a, z] : ends_of(s))
5301 {
5302 Built_Net<Net> b(s);
5303 b.pin(a, z);
5304 put_initial_flow(b);
5305
5306 sums.run();
5307 lists.run();
5308 for (typename Net::Node_Iterator it(b.net); it.has_curr(); it.next_ne())
5309 {
5310 auto p = it.get_curr();
5311 F in_cap{0}, out_cap{0}, in_flow{0}, out_flow{0};
5312 size_t in = 0, out = 0;
5313 std::multiset<typename Net::Arc *> ins, outs;
5314 std::multiset<typename Net::Node *> from, to;
5315 for (auto arc : b.arcs)
5316 {
5317 if (b.net.get_tgt_node(arc) == p)
5318 {
5319 in_cap += arc->cap;
5320 in_flow += arc->flow;
5321 ++in;
5322 ins.insert(arc);
5323 from.insert(b.net.get_src_node(arc));
5324 }
5325 if (b.net.get_src_node(arc) == p)
5326 {
5327 out_cap += arc->cap;
5328 out_flow += arc->flow;
5329 ++out;
5330 outs.insert(arc);
5331 to.insert(b.net.get_tgt_node(arc));
5332 }
5333 }
5334 if (b.net.get_in_cap(p) != in_cap or b.net.get_out_cap(p) != out_cap
5335 or b.net.get_in_flow(p) != in_flow or b.net.get_out_flow(p) != out_flow
5336 or b.net.get_in_degree(p) != in or b.net.get_out_degree(p) != out)
5337 sums.fail(s, where(b, a, z) + "a wrong sum or degree at the node " + name_of(p));
5338 auto as_set = [] (const auto & l)
5339 {
5340 std::multiset<std::remove_cvref_t<decltype(l.get_first())>> r;
5341 for (auto j = l.get_it(); j.has_curr(); j.next_ne())
5342 r.insert(j.get_curr());
5343 return r;
5344 };
5345 if (as_set(b.net.in_arcs(p)) != ins or as_set(b.net.out_arcs(p)) != outs
5346 or as_set(b.net.in_nodes(p)) != from or as_set(b.net.out_nodes(p)) != to)
5347 lists.fail(s, where(b, a, z) + "a wrong list at the node " + name_of(p));
5348 }
5349
5350 // A valid flow passes, and the value is that of the source
5351 checks.run();
5352 if (s.n >= 2 and (not b.net.check_network() or b.net.flow_value() != b.value()))
5353 checks.fail(s, where(b, a, z) + "the flow to start from is refused");
5354 else if (s.n >= 2)
5355 for (auto arc : b.arcs)
5356 if (b.net.get_src_node(arc) != b.net.get_tgt_node(arc)
5357 and arc->cap > arc->flow and b.net.get_tgt_node(arc) != b.snk)
5358 {
5359 // One more unit on an arc into an inner node breaks it
5360 const F before = arc->flow;
5361 arc->flow = std::min(arc->cap, before + amount<F>(1));
5362 if (b.net.check_node(b.net.get_tgt_node(arc)) or b.net.check_network())
5363 checks.fail(s, where(b, a, z) + "an unbalanced flow passes");
5364 arc->flow = before;
5365 break;
5366 }
5367
5368 setters.run();
5369 for (auto arc : b.arcs)
5370 {
5371 const F cap = arc->cap, flow = arc->flow;
5372 bool ok = b.net.get_cap(arc) == cap and b.net.get_flow(arc) == flow;
5373 try
5374 {
5375 b.net.set_flow(arc, cap + amount<F>(1));
5376 ok = false;
5377 }
5378 catch (const std::out_of_range &) {}
5379 try
5380 {
5381 if (flow > F{0})
5382 {
5383 b.net.set_cap(arc, flow - amount<F>(1));
5384 ok = false;
5385 }
5386 }
5387 catch (const std::out_of_range &) {}
5388 ok = ok and arc->cap == cap and arc->flow == flow;
5389 b.net.set_cap(arc, cap + amount<F>(1));
5390 b.net.set_flow(arc, cap);
5391 ok = ok and arc->cap == cap + amount<F>(1) and arc->flow == cap;
5392 b.net.set_flow(arc, flow);
5393 b.net.set_cap(arc, cap);
5394 if (not ok)
5395 setters.fail(s, where(b, a, z) + "a setter does not keep its contract");
5396 }
5397 {
5398 // insert_arc() refuses a flow above the capacity, and the
5399 // network stays as it was
5400 const size_t arcs = b.net.get_num_arcs();
5401 const auto sources = b.net.get_src_nodes().size();
5402 const auto sinks = b.net.get_sink_nodes().size();
5403 bool threw = false;
5404 try
5405 {
5406 if constexpr (Cost_Network<Net>)
5407 b.net.Net_Graph<typename Net::Node, typename Net::Arc>::insert_arc(
5408 b.src, b.snk, amount<F>(1), amount<F>(2));
5409 else
5410 b.net.insert_arc(b.src, b.snk, amount<F>(1), amount<F>(2));
5411 }
5412 catch (const std::overflow_error &)
5413 {
5414 threw = true;
5415 }
5416 if (not threw or b.net.get_num_arcs() != arcs or b.net.get_src_nodes().size() != sources
5417 or b.net.get_sink_nodes().size() != sinks)
5418 setters.fail(s, where(b, a, z) + "insert_arc() takes a flow above the capacity");
5419 }
5420 b.net.reset();
5421 for (auto arc : b.arcs)
5422 if (arc->flow != F{0})
5423 {
5424 setters.fail(s, where(b, a, z) + "reset() leaves a flow");
5425 break;
5426 }
5427 }
5428 });
5429 sums.expect();
5430 lists.expect();
5431 checks.expect();
5432 setters.expect();
5433}
5434
5435TYPED_TEST(ExhaustiveMinCost, ResidualNetworksMirrorTheFlow)
5436{
5437 using Net = TypeParam;
5438 using F = typename Net::Flow_Type;
5439 Check preflow("preflow_create_residual_net() and update_flow()");
5440 Check cost("build_residual_net(), check_residual_net() and residual_to_net()");
5441
5442 small_structural_specs<Net>()([&] (const Spec & s)
5443 {
5444 for (auto [a, z] : ends_of(s))
5445 {
5446 if (a == z)
5447 continue;
5448 Built_Net<Net> b(s, s.w, structural_costs(s));
5449 b.pin(a, z);
5450 put_initial_flow(b);
5451 const auto flows = b.flows();
5452
5453 preflow.run();
5454 {
5455 auto [rnet, rs, rt] = preflow_create_residual_net(b.net);
5456 bool ok = rnet.get_num_nodes() == b.net.get_num_nodes()
5457 and rnet.get_num_arcs() == 2 * b.net.get_num_arcs()
5458 and NODE_COOKIE(b.src) == static_cast<void *>(rs)
5459 and NODE_COOKIE(b.snk) == static_cast<void *>(rt);
5460 size_t images = 0;
5461 using Rnet = PP_Res_Net<Net>;
5462 for (typename Rnet::Arc_Iterator it(rnet); it.has_curr() and ok; it.next_ne())
5463 {
5464 auto r = it.get_curr();
5465 if (r->is_residual())
5466 continue;
5467 ++images;
5468 void * from = b.net.get_src_node(r->img), * to = b.net.get_tgt_node(r->img);
5469 ok = r->cap == r->img->cap and r->flow == r->img->flow and r->dup->dup == r
5470 and r->dup->flow == r->cap - r->flow
5471 and NODE_COOKIE(rnet.get_src_node(r)) == from
5472 and NODE_COOKIE(rnet.get_tgt_node(r)) == to;
5473 }
5474 b.net.reset();
5475 update_flow(rnet);
5476 if (not ok or images != b.net.get_num_arcs() or b.flows() != flows)
5477 preflow.fail(s, where(b, a, z) + "the residual network does not mirror the flow");
5478 }
5479
5480 cost.run();
5481 {
5482 Residual_Net<F> rnet;
5484 auto rs = build_residual_net(b.net, rnet, map);
5485 bool ok = check_residual_net(rnet) and rnet.get_num_arcs() == 2 * b.net.get_num_arcs()
5486 and rs == mapped_node<Net, Residual_Net<F>>(b.src)
5487 and map.size() == b.net.get_num_arcs();
5488 for (auto arc : b.arcs)
5489 {
5490 auto r = static_cast<typename Residual_Net<F>::Arc *>(map.find(arc));
5491 ok = ok and not r->is_residual and r->cap == arc->cap and r->flow == arc->flow
5492 and r->cost == arc->cost and r->img->is_residual and r->img->cost == -arc->cost
5493 and r->img->flow == arc->cap - arc->flow;
5494 }
5495 b.net.reset();
5496 residual_to_net<Net>(map);
5497 if (not ok or b.flows() != flows)
5498 cost.fail(s, where(b, a, z) + "the residual network does not mirror the flow");
5499 }
5500 }
5501 });
5502 preflow.expect();
5503 cost.expect();
5504}
Hungarian (Kuhn-Munkres) algorithm for the optimal assignment problem.
Johnson's algorithm for all-pairs shortest paths.
A global operator new that a test can make fail.
#define ALEPH_ALLOCATION_FAILURE_UNDER_TSAN
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t size_t col
Definition ca-c-api.h:116
size_t cols
Definition ca-c-api.h:105
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
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
Generic key-value map implemented on top of a binary search tree.
Data & find(const Key &key)
Find the value associated with key.
Dynamic matrix with sparse storage.
Definition tpl_dynMat.H:122
void allocate()
Pre-allocate memory for the entire matrix.
Definition tpl_dynMat.H:271
Dynamic set backed by balanced binary search trees with automatic memory management.
const size_t & size() const
Returns the cardinality of the set.
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
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
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
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Implementation of the Hungarian (Munkres) algorithm.
Definition Hungarian.H:143
Johnson's algorithm for all-pairs shortest paths.
Definition Johnson.H:216
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Sparse matrix with generic row and column domains.
Definition al-matrix.H:70
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Capacitated network with node capacity constraints.
Network graph with supply and demand nodes.
Node with supply/demand flow value.
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
bool has_current_node() const noexcept
Return true if the iterator has a current node.
Definition tpl_graph.H:4512
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
size_t size() const noexcept
Return the path length in nodes.
Definition tpl_graph.H:3987
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
Minimal std::expected-style result type for C++20.
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
void empty()
Clears all entries and resets to default capacity.
Definition hashDry.H:933
The failures of one property over a domain.
void expect() const
Expects what the mark says, and prints the first failures.
void fail(const Spec &s, const std::string &what)
Counts a failure on spec, with what went wrong.
void run() noexcept
Counts a run of the property.
#define TEST(name)
static mt19937 rng
pair< size_t, string > P
#define N
Definition fib.C:294
static Tree_Node< int > * chain(size_t n)
__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
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
__gmp_expr< mpq_t, mpq_t > mpq_class
Definition gmpfrxx.h:2270
::testing::Types< int, long, double > Cost_Types
The types of the costs: integers and floating.
TYPED_TEST_SUITE(ExhaustiveMaxFlow, Flow_Nets)
::testing::Types< Net_Graph< Net_Node< int >, Net_Arc< int, int > >, Net_Graph< Net_Node< int >, Net_Arc< int, double > >, Net_Cost_Graph< Net_Cost_Node< int >, Net_Cost_Arc< Empty_Class, long > > > Flow_Nets
The networks of integers, of floating flows and of costs.
::testing::Types< Net_Graph< Net_Node< int >, Net_Arc< int, int > >, Net_Graph< Net_Node< int >, Net_Arc< int, double > > > Capacity_Nets
The networks of integers and of floating flows.
TEST_F(ExhaustiveFlowMemory, SuperNodesWhenMemoryRunsOut)
TYPED_TEST(ExhaustiveMaxFlow, AugmentingPathsMatchTheOracle)
::testing::Types< Net_Cost_Graph< Net_Cost_Node< int >, Net_Cost_Arc< Empty_Class, long > >, Net_Cost_Graph< Net_Cost_Node< int >, Net_Cost_Arc< Empty_Class, double > > > Cost_Nets
The networks with costs, of integers and of floating flows.
::testing::Types< Net_Cap_Graph< Net_Cap_Node< int, long >, Net_Arc< int, long > >, Net_Cap_Graph< Net_Cap_Node< int, double >, Net_Arc< int, double > > > Node_Cap_Nets
Every small multigraph, on every kind of graph, for the tests.
Answers computed from a Spec of graph_harness.H, without Aleph.
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define ARC_COOKIE(p)
Return the arc cookie
void inter_copy_graph(GTT &gtgt, const GTS &gsrc, const bool cookie_map=false)
Copy between different types of graphs.
Definition tpl_graph.H:4884
Hungarian_Result< Cost_Type > hungarian_max_assignment(const DynMatrix< Cost_Type > &cost)
Compute maximum-profit assignment (free function).
Definition Hungarian.H:648
Hungarian_Result< Cost_Type > hungarian_assignment(const DynMatrix< Cost_Type > &cost)
Compute minimum-cost assignment (free function).
Definition Hungarian.H:607
#define NODE_COOKIE(p)
Return the node cookie
void copy_graph(GT &gtgt, const GT &gsrc, bool cookie_map=false)
Explicit copy of graph.
Definition tpl_graph.H:4794
FFT< double > F
static mpfr_t y
Definition mpfr_mul_d.c:3
@ R
Recovered (and immune).
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
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
Residual_Net< typenameNet::Flow_Type >::Node * build_residual_net(const Net &net, Residual_Net< typename Net::Flow_Type > &rnet, DynMapTree< void *, void * > &arcs)
Build a residual network from a flow network.
FlowStatistics< typename Net::Flow_Type > compute_flow_statistics(const Net &net)
Compute statistics about the current flow in a network.
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
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
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
BaseballEliminationResult check_baseball_elimination(const std::vector< Team > &teams, size_t team_idx)
Check if a team is mathematically eliminated from winning.
Definition net_apps.H:562
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
FlowDecomposition< Net > decompose_flow(const Net &net)
Decompose network flow into paths and cycles.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
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
Net::Flow_Type increase_flow(Net &net, const Path< Net > &path)
Increase flow along an augmenting path.
Definition tpl_net.H:1714
void expect(std::ifstream &input_stream, const std::string &expected)
Expect and consume a specific string/keyword.
std::tuple< size_t, double > max_flow_min_cost_by_cycle_canceling(Net &net, double it_factor=0.4, size_t step=10)
Compute maximum flow at minimum cost using cycle canceling.
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
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.
size_t max_flow_min_cost_by_network_simplex(Net &net)
Compute maximum flow at minimum cost using Network Simplex.
TransportationResult< Cost_Type > solve_transportation(const std::vector< Cost_Type > &supplies, const std::vector< Cost_Type > &demands, const std::vector< std::vector< Cost_Type > > &costs)
Solve the transportation problem using min-cost flow.
std::tuple< bool, typename Net::Flow_Type, DynList< Parc< Net > > > SemiPath
Semi-path tuple:
Definition tpl_net.H:1198
ProjectSelectionResult< Value_Type > solve_project_selection(const std::vector< Project< Value_Type > > &projects)
Solve project selection problem using max-flow.
Definition net_apps.H:397
Operation for_each(Itor beg, const Itor &end, Operation op)
Apply an operation to each element in a range.
Definition ahAlgo.H:76
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
SegmentationResult segment_image(size_t rows, size_t cols, const std::vector< std::vector< std::array< Value_Type, 2 > > > &data_cost, Value_Type smoothness)
Segment image using graph cuts.
Definition net_apps.H:735
SurveyDesignResult design_survey(const std::vector< SurveyQuestion > &questions, const std::vector< SurveyRespondent > &respondents)
Design survey assignment using network flow.
Definition net_apps.H:890
TransshipmentResult< typename Net::Flow_Type > solve_transshipment(Net &net, GetDemand get_demand)
Solve minimum cost transshipment problem.
CirculationResult< typename Net::Flow_Type > solve_circulation(Net &net, GetDemand get_demand, GetLower get_lower)
Solve a circulation problem with demands.
Definition net_apps.H:151
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
std::pair< typename Net::Flow_Type, typename Net::Flow_Type > successive_shortest_paths(Net &net)
Compute minimum cost maximum flow using Successive Shortest Paths.
bool check_residual_net(const Res_Net &net)
Verify residual network consistency.
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
AssignmentResult< Cost_Type > solve_assignment(const std::vector< std::vector< Cost_Type > > &costs)
Solve the assignment problem using min-cost flow.
bool none(const Container &container, Operation &operation)
Return true if no element satisfies operation.
std::tuple< typename Net::Arc *, bool > Parc
Arc entry for a semi-path.
Definition tpl_net.H:1188
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
double add(double a, double b)
size_t for_each_spec(const Domain &d, bool directed, F &&f)
Calls f(spec) with every spec of d, smallest first, and returns how many there were.
Spec random_spec(std::mt19937 &rng, int n, int m, bool directed, bool loops=true, bool parallel=true)
A random spec of n nodes and m arcs, with loops and parallel arcs if asked; parallel is ignored when ...
Domain domain(int max_nodes, int max_arcs)
The domain of max_nodes nodes and max_arcs arcs, of one more of each in heavy mode,...
bool heavy()
Whether the mode is heavy, which asks for the larger domains.
void random_weights(std::mt19937 &rng, Spec &s, long long lo, long long hi)
Gives each arc of s a weight from lo to hi.
constexpr long long Inf
No distance, in the matrices of the oracles.
std::vector< std::vector< long long > > shortest_distances(const Spec &s, bool directed, bool &neg)
Floyd on a matrix of long long: the shortest distances, Inf where there is no path,...
long long max_flow(const Spec &s, int src, int snk)
The maximum flow from src to snk, by Edmonds-Karp on the matrix of the capacities w (loops carry noth...
STL namespace.
Network flow applications.
#define LL
Definition ran_array.c:24
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
Functor wrapper for capacity scaling.
Result of a circulation problem.
Definition net_apps.H:89
Functor wrapper for flow decomposition.
Functor wrapper for Dinic's algorithm.
Functor wrapper for edmonds_karp_maximum_flow().
Definition tpl_net.H:2347
Functor wrapper for fifo_preflow_maximum_flow().
Definition tpl_net.H:2680
Result of flow decomposition.
DynList< FlowCycle< Net > > cycles
Cycles (if any)
Flow_Type total_flow() const noexcept
Total flow (sum of path flows).
size_t num_paths() const noexcept
Number of paths.
size_t num_cycles() const noexcept
Number of cycles.
DynList< FlowPath< Net > > paths
Source-to-sink paths.
Statistics about a network flow.
size_t num_saturated_arcs
Arcs with flow = capacity.
size_t num_empty_arcs
Arcs with flow = 0.
Flow_Type total_capacity
Sum of all capacities.
Flow_Type total_flow
Total flow value.
size_t num_partial_arcs
Arcs with 0 < flow < capacity.
double utilization
flow / capacity ratio
Functor wrapper for ford_fulkerson_maximum_flow().
Definition tpl_net.H:2320
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Functor wrapper for HLPP.
Functor wrapper for heap_preflow_maximum_flow().
Definition tpl_net.H:2718
Functor wrapper for maximum flow minimum cost algorithm.
Functor wrapper for Network Simplex algorithm.
Functor wrapper for min_cut().
Definition tpl_net.H:2838
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
Arc type for maximum flow minimum cost networks.
Definition tpl_netcost.H:96
Capacitated flow network with costs associated to arcs.
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
Flow_Type get_out_flow(Node *node) const noexcept
Return total outgoing flow of node.
Definition tpl_net.H:399
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
Definition tpl_net.H:750
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
Definition tpl_net.H:595
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
bool is_source(Node *node) const noexcept
Return true if node is a source.
Definition tpl_net.H:417
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
bool with_super_source
True if the network has a super-source.
Definition tpl_net.H:1150
ArcT Arc
Arc type.
Definition tpl_net.H:322
Flow_Type get_in_flow(Node *node) const noexcept
Return total incoming flow of node.
Definition tpl_net.H:408
bool is_sink(Node *node) const noexcept
Return true if node is a sink.
Definition tpl_net.H:423
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Definition tpl_net.H:328
NodeT Node
Node type.
Definition tpl_net.H:325
Functor wrapper for random_preflow_maximum_flow().
Definition tpl_net.H:2770
Functor wrapper for SSP algorithm.
Result of transshipment problem.
Which multigraphs for_each_spec() gives.
bool loops
arcs from a node to itself
bool reversed
also the arcs in the reverse order
A small multigraph: its nodes are 0 .
std::vector< long long > w
size_t num_arcs() const noexcept
std::vector< std::array< int, 2 > > arcs
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
ValueArg< size_t > seed
Definition testHash.C:53
void assign(BinTree< int >::Node *node, int, int)
static int * k
int random(int l, int r)
Gsl_Compatible_Rng r
Advanced maximum flow algorithms.
Advanced minimum cost flow algorithms.
Network flow graph structures.
Supply-demand network flow algorithms.
Network flow graph with capacities.
Maximum flow minimum cost network algorithms.
DynList< int > l