88#include <gtest/gtest.h>
105using namespace Aleph;
116 template <
typename F>
117 constexpr long long Units_Per_One = std::is_floating_point_v<F> ? 4 : 1;
120 template <
typename F>
121 F amount(
long long units)
123 return F(units) /
F(Units_Per_One<F>);
127 template <
typename F>
128 bool is_amount(
F x,
long long units)
130 return x *
F(Units_Per_One<F>) ==
F(units);
133 template <
typename F>
134 std::string text(
F x)
136 if constexpr (std::is_floating_point_v<F>)
139 std::snprintf(buf,
sizeof buf,
"%.17g",
double(x));
143 return std::to_string(x);
154 typename Net::Node * insert_numbered_node(
Net & net,
int i)
161 constexpr int Added_Source = -1;
162 constexpr int Added_Sink = -2;
175 std::vector<Node *>
nodes;
176 std::vector<Arc *>
arcs;
177 size_t spec_arcs = 0;
178 Node * src =
nullptr;
179 Node * snk =
nullptr;
180 bool added_ends =
false;
182 Built_Net(
const Spec & s,
const std::vector<long long> & cap,
183 const std::vector<long long> & cost = {})
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])],
190 i < cost.size() ? amount<F>(cost[i]) :
F{0}));
191 spec_arcs =
arcs.size();
195 explicit Built_Net(
const Spec & s) : Built_Net(s, s.
w) {}
199 Built_Net(
const Spec & s,
const std::vector<F> & cap, Amounts)
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();
208 Built_Net(
const Built_Net &) =
delete;
209 Built_Net & operator = (
const Built_Net &) =
delete;
213 if constexpr (Cost_Network<Net>)
228 void pin(
int s,
int t)
232 src = snk =
nodes[size_t(s)];
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));
253 std::vector<Node *> others;
255 if (it.get_curr() != src)
256 others.push_back(it.get_curr());
257 for (
Node * p : others)
262 if (it.get_curr() != snk)
263 others.push_back(it.get_curr());
264 for (
Node * p : others)
270 int number(
Arc * a)
const
272 for (
size_t i = 0; i < spec_arcs; ++i)
285 std::vector<F> flows()
const
289 r.push_back(a->flow);
294 void set_flows(
const std::vector<F> & f)
296 for (
size_t i = 0; i <
arcs.size(); ++i)
297 arcs[i]->flow = f[i];
301 template <
class Node>
302 std::string name_of(
Node * p)
304 const int i = p->get_info();
305 return i == Added_Source ?
"s*" : i == Added_Sink ?
"t*" : std::to_string(i);
313 std::string flow_error(
const Built_Net<Net> & b,
bool tolerance =
false)
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);
325 auto p = it.get_curr();
326 if (p == b.src or p == b.snk)
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)))
334 return "the node " + name_of(p) +
" receives " + text(in) +
" and sends " + text(
out);
342 std::string max_flow_error(
const Built_Net<Net> & b,
typename Net::Flow_Type got,
345 if (
auto e = flow_error(b); not e.empty())
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());
357 std::vector<std::pair<int, int>> ends_of(
const Spec & s)
359 std::vector<std::pair<int, int>>
r;
362 for (
int a = 0; a < s.
n; ++a)
363 for (
int z = 0; z < s.
n; ++z)
371 std::string where(
const Built_Net<Net> & b,
int a,
int z)
373 return "from " + std::to_string(a) +
" to " + std::to_string(z)
374 + (b.added_ends ?
" through added ends" :
"") +
": ";
378 Spec with_w(
const Spec & s,
const std::vector<long long> &
w)
387 void for_each_assignment(
const Spec & s,
const std::vector<long long> & values,
F f)
389 std::vector<size_t> pick(s.
arcs.size(), 0);
392 std::vector<long long>
w;
393 for (
size_t k : pick)
394 w.push_back(values[
k]);
397 while (i < pick.size()
and ++pick[i] == values.size())
399 if (i == pick.size())
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);
419 template <
typename N>
420 N exact_max_flow(
const Spec & s,
const std::vector<N> & cap,
int a,
int z)
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)
426 c[size_t(s.
arcs[i][0])][size_t(s.
arcs[i][1])] += cap[i];
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)
437 parent[v] = queue[
h];
438 queue.push_back(
int(v));
440 if (parent[
size_t(z)] == -1)
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)])
447 c[size_t(parent[
size_t(v)])][size_t(v)] -= b;
448 c[size_t(v)][size_t(parent[
size_t(v)])] += b;
456 long long max_flow_units(
const Spec & s,
int a,
int z)
465 long long min_cut_units(
const Spec & s,
int a,
int z)
468 for (
unsigned long set = 0; set < (1UL << s.
n); ++set)
470 if (((set >> a) & 1UL) == 0 or ((set >> z) & 1UL) != 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)
476 best = std::min(best, cut);
493 std::vector<Solver<Net>> augmenting_solvers()
495 return {{
"ford_fulkerson_maximum_flow()", &ford_fulkerson_maximum_flow<Net>},
496 {
"edmonds_karp_maximum_flow()", &edmonds_karp_maximum_flow<Net>}};
500 std::vector<Solver<Net>> preflow_solvers()
502 return {{
"fifo_preflow_maximum_flow()", &fifo_preflow_maximum_flow<Net>},
503 {
"heap_preflow_maximum_flow()", &heap_preflow_maximum_flow<Net>}};
509 std::vector<Solver<Net>> random_preflow_solvers()
511 return {{
"random_preflow_maximum_flow()", &random_preflow_maximum_flow<Net>}};
515 std::vector<Solver<Net>> advanced_solvers()
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>}};
523 std::vector<Solver<Net>> all_solvers()
525 auto r = augmenting_solvers<Net>();
526 for (
auto & x : preflow_solvers<
Net>())
528 for (
auto & x : random_preflow_solvers<
Net>())
530 for (
auto & x : advanced_solvers<
Net>())
538 std::vector<Solver<Net>> functor_solvers()
542 {
"Ford_Fulkerson_Maximum_Flow",
544 {
"Edmonds_Karp_Maximum_Flow",
546 {
"Fifo_Preflow_Maximum_Flow",
548 {
"Heap_Preflow_Maximum_Flow",
550 {
"Random_Preflow_Maximum_Flow",
553 {
"Capacity_Scaling_Maximum_Flow",
564 bool ends_program =
false;
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;
579 template <
class Solvers>
580 explicit Family_Checks(
const Solvers & solvers, std::vector<Known_Class> known_classes = {})
581 : classes(
std::move(known_classes))
583 for (
const auto & s : solvers)
585 names.push_back(s.name);
586 plain.emplace_back(s.name);
592 Check * of(
size_t i,
int k)
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;
608 for (
const auto & c : plain)
610 for (
const auto & [key, c] : known)
617 int no_class(
size_t,
const Built_Net<Net> &)
625 void check_refusal(
const std::vector<Solver<Net>> & solvers,
const Spec & s,
Check & refuse)
628 if (b.net.is_single_source()
and b.net.is_single_sink())
630 for (
const auto & solver : solvers)
636 refuse.
fail(s, solver.name +
" does not throw");
638 catch (
const std::domain_error &) {}
639 catch (
const std::exception & e)
641 refuse.
fail(s, solver.name +
" throws " + e.what());
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)
657 check_refusal(solvers, s, refuse);
658 for (
auto [a, z] : ends_of(s))
662 if (not (b.net.is_single_source()
and b.net.is_single_sink()))
667 refuse.
fail(s, where(b, a, z) +
"the network keeps other sources or sinks");
670 const long long want = max_flow_units(s, a, z);
671 for (
size_t i = 0; i < solvers.size(); ++i)
674 if (
check ==
nullptr)
681 got = solvers[i].run(b.net);
683 catch (
const std::exception & e)
685 check->fail(s, where(b, a, z) +
"throws " + e.what());
688 if (
auto e = max_flow_error(b, got, want); not e.empty())
689 check->fail(s, where(b, a, z) + e);
696 auto structural_specs(
const Domain & d)
706 template <
typename F>
707 std::vector<long long> capacity_class()
709 if constexpr (std::is_floating_point_v<F>)
729 template <
typename F>
730 auto class_specs(
const Domain & d)
736 for_each_assignment(s, capacity_class<F>(), f);
744 auto random_specs(
unsigned first,
unsigned count)
746 return [first,
count] (
auto f)
749 for (
unsigned k = 0;
k <
count; ++
k)
751 const int n = 6 + int(
rng() % 3);
752 const int m = 8 + int(
rng() % 9);
781 constexpr bool in_one_order = std::is_floating_point_v<typename Net::Flow_Type>;
788 Domain max_flow_domain(
bool one_order =
false)
791 d.
reversed = not (one_order or in_one_order<Net>);
799 enum class Flow_Domain { Structural, Capacities };
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)
806 if (which == Flow_Domain::Structural)
807 check_max_flows(solvers, structural_specs(max_flow_domain<Net>(one_order)), checks,
811 check_max_flows(solvers, class_specs<typename Net::Flow_Type>(class_domain()), checks,
813 check_max_flows(solvers, random_specs(seed_base,
heavy() ? 400 : 40), checks, refuse,
822 void check_augmenting_paths(Flow_Domain which)
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>);
833 void check_preflows(Flow_Domain which,
bool random)
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");
840 check_family(solvers, checks, refuse, which,
random ? 13 : 12, no_class<
Net>,
random);
845 void check_advanced(Flow_Domain which)
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>);
856 check_augmenting_paths<TypeParam>(Flow_Domain::Structural);
861 check_preflows<TypeParam>(Flow_Domain::Structural,
false);
866 check_preflows<TypeParam>(Flow_Domain::Structural,
true);
871 check_advanced<TypeParam>(Flow_Domain::Structural);
886 check_augmenting_paths<TypeParam>(Flow_Domain::Capacities);
891 check_preflows<TypeParam>(Flow_Domain::Capacities,
false);
896 check_preflows<TypeParam>(Flow_Domain::Capacities,
true);
901 check_advanced<TypeParam>(Flow_Domain::Capacities);
913 std::vector<typename Net::Node *>
nodes;
914 std::map<typename Net::Node *, size_t> pos;
916 explicit Node_Index(
const Net & net)
920 pos[it.get_curr()] =
nodes.size();
921 nodes.push_back(it.get_curr());
940 Initial_Flow put_initial_flow(Built_Net<Net> & b,
bool cycle =
true)
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; };
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)
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])
965 if (
const size_t z = ix.pos.at(b.snk); seen[z])
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])))
972 value =
static_cast<long long>(neck *
F(Units_Per_One<F>));
977 return {
value,
false};
981 for (
size_t start = 0; start < n; ++start)
983 std::vector<Arc *> stack;
984 std::vector<size_t> on = {start};
985 std::vector<int> state(n, 0);
986 std::vector<size_t>
next(n, 0);
988 while (not on.empty())
990 const size_t u = on.back();
991 bool advanced =
false;
992 for (;
next[u] < b.arcs.size(); ++
next[u])
995 if (ix.pos.at(b.net.get_src_node(a)) != u or left(a) <=
F{0})
997 const size_t v = ix.pos.at(b.net.get_tgt_node(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();
1006 neck =
std::
min(neck, left(x));
1009 return {
value,
true};
1025 if (not stack.empty())
1030 return {
value,
false};
1037 template <
class Net>
1038 auto small_structural_specs()
1041 d.
reversed = not in_one_order<Net>;
1042 return structural_specs(d);
1048 using Net = TypeParam;
1049 const auto solvers = all_solvers<Net>();
1050 Family_Checks checks(solvers);
1052 small_structural_specs<Net>()([&] (
const Spec & s)
1054 for (
auto [a, z] : ends_of(s))
1056 Built_Net<Net> b(s);
1058 if (not (b.net.is_single_source()
and b.net.is_single_sink()))
1060 const long long want = max_flow_units(s, a, z);
1061 for (
size_t i = 0; i < solvers.size(); ++i)
1063 const long long start = put_initial_flow(b).value;
1066 const std::string at = where(b, a, z) +
"from a flow of "
1067 + text(amount<typename Net::Flow_Type>(start)) +
": ";
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);
1074 catch (
const std::exception & e)
1076 check->fail(s, at +
"throws " + e.what());
1086 using Net = TypeParam;
1087 const auto solvers = all_solvers<Net>();
1088 const auto functors = functor_solvers<Net>();
1089 Family_Checks checks(functors);
1091 small_structural_specs<Net>()([&] (
const Spec & s)
1093 for (
auto [a, z] : ends_of(s))
1095 Built_Net<Net> b(s);
1097 if (not (b.net.is_single_source()
and b.net.is_single_sink()))
1099 const long long want = max_flow_units(s, a, z);
1100 for (
size_t i = 0; i < solvers.size(); ++i)
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);
1112 catch (
const std::exception & e)
1114 check->fail(s, where(b, a, z) +
"throws " + e.what());
1127 template <
class Net>
1130 template <
class Net>
1134 template <
class Net>
1138 typename Net::Flow_Type (*run)(
Net &, Node_Set<Net> &, Node_Set<Net> &, Arc_List<Net> &,
1144 template <
class Net>
1145 std::vector<Cutter<Net>> cutters()
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); }}};
1162 template <
class Net>
1163 std::set<typename Net::Node *> residual_reach(
const Built_Net<Net> & b)
1166 std::set<typename Net::Node *>
r = {b.src};
1167 for (
bool grew =
true; grew; )
1170 for (
auto a : b.
arcs)
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;
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)
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())
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";
1208 std::multiset<typename Net::Arc *> want_cuts, want_cutt, got_cuts, got_cutt;
1209 for (
auto a : b.
arcs)
1211 const bool u = s_side.count(b.net.get_src_node(a)), v = s_side.count(b.net.get_tgt_node(a));
1213 want_cuts.insert(a);
1214 else if (v
and not u)
1215 want_cutt.insert(a);
1218 for (
auto it = cuts.get_it(); it.has_curr(); it.next_ne())
1220 got_cuts.insert(it.get_curr());
1221 capacity += it.get_curr()->cap;
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);
1237 using Net = TypeParam;
1238 const auto cuts = cutters<Net>();
1239 Family_Checks checks(cuts);
1241 small_structural_specs<Net>()([&] (
const Spec & s)
1243 for (
auto [a, z] : ends_of(s))
1245 Built_Net<Net> b(s);
1247 if (not (b.net.is_single_source()
and b.net.is_single_sink()) or a == z)
1249 const long long want = min_cut_units(s, a, z);
1250 for (
size_t i = 0; i < cuts.size(); ++i)
1255 Node_Set<Net> vs, vt;
1256 Arc_List<Net> cs, ct;
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);
1263 catch (
const std::exception & e)
1265 check->fail(s, where(b, a, z) +
"throws " + e.what());
1283 template <
class Net>
1285 bool rounded =
false)
1290 std::map<Arc *, F>
sum;
1291 auto same = [rounded] (
F x,
F y)
1293 if constexpr (std::is_floating_point_v<F>)
1296 return std::abs(x -
y) <= 1e-9 * std::max({
F{1}, std::abs(x), std::abs(
y)});
1304 const char * what) -> std::string
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)
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";
1324 for (
auto it = d.
paths.get_it(); it.has_curr(); it.next_ne())
1326 const auto & p = it.get_curr();
1327 if (
auto e = walk(p.arcs, p.nodes, p.flow,
"path"); not e.empty())
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";
1332 for (
auto it = d.
cycles.get_it(); it.has_curr(); it.next_ne())
1334 const auto & c = it.get_curr();
1335 if (
auto e = walk(c.arcs, c.nodes, c.flow,
"cycle"); not e.empty())
1337 if (c.nodes.get_first() != c.nodes.get_last())
1338 return "a cycle is not closed";
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 "
1346 return "total_flow() is " + text(d.
total_flow()) +
", not " + text(b.value());
1348 return "num_paths() or num_cycles() do not count them";
1354 template <
class Net>
1355 std::string statistics_error(
const Built_Net<Net> & b,
1360 size_t saturated = 0, empty = 0, partial = 0;
1361 for (
auto a : b.
arcs)
1364 if (a->flow == a->cap)
1366 else if (a->flow ==
F{0})
1373 +
", not " + text(b.value()) +
" and " + text(capacity);
1376 return "the counts of the arcs are wrong";
1377 const double use = capacity >
F{0} ? double(b.value()) / double(capacity) : 0.0;
1379 return "the utilization is " + text(st.
utilization) +
", not " + text(use);
1391 template <
class Net,
class F>
1392 void for_each_flow_to_decompose(
Check & refuse,
bool reversed,
F f)
1398 std::reverse(
r.arcs.begin(),
r.arcs.end());
1399 const Spec s = structural(
r);
1401 Built_Net<Net> b(s);
1402 if (not (b.net.is_single_source()
and b.net.is_single_sink()))
1408 refuse.
fail(s,
"does not throw");
1410 catch (
const std::domain_error &) {}
1413 for (
auto [a, z] : ends_of(s))
1415 Built_Net<Net> b(s);
1417 if (not (b.net.is_single_source()
and b.net.is_single_sink()))
1419 put_initial_flow(b);
1420 f(s, b, where(b, a, z));
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");
1433 for_each_flow_to_decompose<Net>(refuse,
true, [&] (
const Spec & s, Built_Net<Net> & b,
1434 const std::string & at)
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");
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");
1456 for_each_flow_to_decompose<Net>(refuse,
false, [&] (
const Spec & s, Built_Net<Net> & b,
1457 const std::string & at)
1460 const auto after = b.flows();
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");
1469 functor.
fail(s, at + e);
1473 stats.
fail(s, at + e);
1475 for (
const Check * c : {&function, &functor, &stats, &refuse})
1487 template <
class Net>
1488 bool residual_path(
const Built_Net<Net> & b,
typename Net::Node * u,
typename Net::Node * v,
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; )
1497 for (
auto a : b.
arcs)
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;
1506 return r.count(v) > 0;
1511 template <
class Net>
1512 std::string augmenting_path_error(
const Built_Net<Net> & b,
const Path<Net> & p,
1517 std::vector<typename Net::Node *> ns;
1518 std::vector<typename Net::Arc *> as;
1521 ns.push_back(it.get_current_node_ne());
1522 if (it.has_current_arc())
1523 as.push_back(it.get_current_arc_ne());
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)
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);
1544 template <
class Net>
1545 std::string semi_path_error(
const Built_Net<Net> & b,
const DynList<
Parc<Net>> & sp,
1551 F least = std::numeric_limits<F>::max();
1553 return "the semi-path is empty";
1554 for (
auto it = sp.get_it(); it.has_curr(); it.next_ne())
1556 auto [a, forward] = it.get_curr();
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);
1567 if (b.net.get_tgt_node(a) != at)
1568 return "an arc backward does not enter the node where the semi-path is";
1570 at = b.net.get_src_node(a);
1572 least = std::min(least, keep);
1575 return "the semi-path does not end at the end";
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);
1586 using Net = TypeParam;
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()");
1602 small_structural_specs<Net>()([&] (
const Spec & s)
1604 for (
auto [a, z] : ends_of(s))
1608 Built_Net<Net> b(s);
1610 for (
long long units : {0
LL, 1LL, 2LL})
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);
1623 check.fail(s, at + (want ?
"finds no path" :
"finds a path"));
1625 if (
auto e = augmenting_path_error(b, p, u, v, slack); not e.empty())
1626 check.fail(s, at + e);
1639 F least = std::numeric_limits<F>::max();
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();
1645 if (added != least or b.value() != before + added)
1646 check.fail(s, at +
"adds " + text(added) +
" for a least slack of "
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);
1660 check.fail(s, at + (
expected ?
"finds no semi-path" :
"finds a semi-path"));
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);
1680 semi_fill.
fail(s, at + (want ?
"finds no semi-path" :
"finds a semi-path"));
1683 if (
auto e = semi_path_error(b, sp, u, v, got, slack); not e.empty())
1684 semi_fill.
fail(s, at + e);
1686 else if (got !=
F{0})
1687 semi_fill.
fail(s, at +
"returns " + text(got) +
" without a semi-path");
1695 const auto before = b.flows();
1696 const F value = b.value();
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");
1704 if (b.flows() != before)
1705 round.
fail(s, at +
"decrease_flow() does not undo increase_flow()");
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})
1721 template <
class Net>
1725 for (
auto it = set.
get_it(); it.has_curr(); it.next_ne())
1726 r.insert(it.get_curr()->get_info());
1731 std::pair<std::set<int>, std::set<int>> ends_by_arcs(
const Spec & s)
1733 std::set<int> sources, sinks;
1734 for (
int x = 0; x < s.
n; ++x)
1739 for (
const auto & a : s.
arcs)
1741 sources.erase(a[1]);
1744 return {sources, sinks};
1750 long long super_max_flow(
const Spec & s)
1752 auto [sources, sinks] = ends_by_arcs(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)
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});
1765 if (sinks.size() > 1)
1769 for (
size_t i = 0; i < s.
arcs.size(); ++i)
1770 in += s.
arcs[i][1] == v ? s.
w[i] : 0;
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});
1777 return max_flow_units(x, from, to);
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()");
1789 structural_specs(max_flow_domain<Net>())([&] (
const Spec & s)
1791 const auto [sources, sinks] = ends_by_arcs(s);
1792 if (sources.empty() or sinks.empty())
1795 Built_Net<Net> b(s);
1798 b.net.make_super_nodes();
1799 refuse.
fail(s,
"does not throw");
1801 catch (
const std::domain_error &) {}
1802 catch (
const std::exception & e)
1804 refuse.
fail(s, std::string(
"throws ") + e.what());
1810 Built_Net<Net> b(s);
1813 b.net.make_super_nodes();
1815 catch (
const std::exception & e)
1817 make.
fail(s, std::string(
"throws ") + e.what());
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))
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");
1830 b.src = b.net.get_source();
1831 b.snk = b.net.get_sink();
1833 if (b.number(it.get_curr()) < 0)
1834 b.arcs.push_back(it.get_curr());
1836 if (
auto e = max_flow_error(b, got, super_max_flow(s)); not e.empty())
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");
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");
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");
1883 template <
typename F>
1884 bool is_cost(
F x,
long long units2)
1886 return x *
F(Units_Per_One<F>) *
F(Units_Per_One<F>) ==
F(units2);
1889 template <
typename F>
1890 F cost_amount(
long long units2)
1892 return F(units2) /
F(Units_Per_One<F> * Units_Per_One<F>);
1898 std::pair<long long, long long> brute_min_cost(
const Spec & s,
1899 const std::vector<long long> & cost,
int a,
int z)
1901 std::vector<long long> f(s.
arcs.size(), 0);
1902 long long best_value = -1, best_cost = 0;
1905 std::vector<long long> balance(
size_t(s.
n), 0);
1906 for (
size_t i = 0; i < f.size(); ++i)
1908 balance[size_t(s.
arcs[i][0])] -= f[i];
1909 balance[size_t(s.
arcs[i][1])] += f[i];
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;
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))
1927 while (i < f.size()
and ++f[i] > s.
w[i])
1930 return {best_value, best_cost};
1937 std::pair<long long, long long> ssp_min_cost(
const Spec & s,
const std::vector<long long> & cost,
1940 struct R {
int u, v;
long long cap, cost;
size_t back; };
1942 for (
size_t i = 0; i < s.
arcs.size(); ++i)
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});
1948 long long value = 0, total = 0;
1952 std::vector<size_t> by(
size_t(s.
n),
r.size());
1954 for (
int round = 0; round < s.
n; ++round)
1955 for (
size_t k = 0;
k <
r.size(); ++
k)
1957 and d[
size_t(
r[
k].u)] +
r[
k].cost < d[
size_t(
r[
k].v)])
1959 d[size_t(
r[
k].v)] = d[size_t(
r[
k].u)] +
r[
k].cost;
1960 by[size_t(
r[
k].v)] =
k;
1963 return {
value, total};
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)
1969 r[by[size_t(v)]].cap -= neck;
1970 r[
r[by[size_t(v)]].back].cap += neck;
1973 total += neck * d[size_t(z)];
1981 template <
class Net>
1986 std::pair<F, F> (*run)(
Net &);
1987 std::pair<F, F> (*again)(
Net &);
1988 bool returns =
false;
1993 template <
class Net>
1994 std::vector<Cost_Solver<Net>> cost_solvers()
1997 using P = std::pair<F, F>;
1999 {
"max_flow_min_cost_by_cycle_canceling()",
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);
2007 {
"max_flow_min_cost_by_network_simplex()",
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);
2019 bool is_cycle_canceling(
size_t i) {
return i <= 1; }
2020 bool is_ssp(
size_t i) {
return i == 4; }
2025 template <
class Net>
2026 std::string min_cost_error(
const Built_Net<Net> & b,
const Cost_Solver<Net> & solver,
2029 std::pair<long long, long long> want)
2032 if (
auto e = flow_error(b); not e.empty())
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());
2046 std::string costs_text(
const std::vector<long long> & cost)
2048 std::string
r =
"costs {";
2049 for (
size_t i = 0; i < cost.size(); ++i)
2058 template <
class Net>
2059 bool negative_residual_cycle(
const Built_Net<Net> & b)
2062 std::map<typename Net::Node *, size_t> index;
2064 index.emplace(it.get_curr(), index.size());
2070 std::vector<Residual>
r;
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});
2078 r.push_back({v, u, -a->cost});
2082 const size_t n = index.size();
2083 std::vector<F> d(n,
F{0});
2084 for (
size_t pass = 0; pass < n; ++pass)
2086 bool changed =
false;
2087 for (
const auto & e :
r)
2088 if (d[e.u] + e.cost < d[e.v])
2090 d[e.v] = d[e.u] + e.cost;
2101 std::vector<long long> structural_costs(
const Spec & s)
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]);
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)
2120 const auto solvers = cost_solvers<Net>();
2121 for (
auto [a, z] : ends_of(s))
2125 Built_Net<Net> b(s, s.
w, cost);
2127 const auto want = min_cost(s, cost, a, z);
2128 for (
size_t i = 0; i < solvers.size(); ++i)
2131 if (only >= 0
and is_cycle_canceling(i) != (only == 0))
2133 if (not variants
and (i == 1 or i == 3))
2140 if (is_ssp(i)
and negative_residual_cycle(b))
2142 const auto before = b.flows();
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");
2149 catch (
const std::domain_error &)
2151 if (b.flows() != before)
2152 check->fail(s, where(b, a, z) + costs_text(cost)
2153 +
"throws, and the flows changed");
2155 catch (
const std::exception & e)
2157 check->fail(s, where(b, a, z) + costs_text(cost) +
"throws " + e.what());
2163 const auto got = solvers[i].run(b.net);
2164 if (
auto e = min_cost_error(b, solvers[i], got, want); not e.empty())
2166 check->fail(s, where(b, a, z) + costs_text(cost) + e);
2171 Check * again = second.of(i, 0);
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);
2177 catch (
const std::exception & e)
2179 check->fail(s, where(b, a, z) + costs_text(cost) +
"throws " + e.what());
2187 template <
class Net>
2190 Family_Checks first;
2191 Family_Checks second;
2194 : first(cost_solvers<
Net>()),
2195 second(second_names())
2198 static std::vector<Solver<Net>> second_names()
2200 std::vector<Solver<Net>>
r;
2201 for (
const auto & s : cost_solvers<
Net>())
2202 r.push_back({s.name +
", then its functor",
nullptr});
2220 std::vector<std::pair<Spec, std::vector<long long>>> simplex_witnesses()
2222 std::vector<std::pair<Spec, std::vector<long long>>>
r;
2225 s.
arcs = {{2, 0}, {1, 2}, {0, 1}, {0, 1}};
2227 r.push_back({s, {2, 0, 1, 2}});
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}});
2251 using Net = TypeParam;
2252 Cost_Checks<Net> checks;
2253 small_structural_specs<Net>()([&] (
const Spec & s)
2255 check_min_costs<Net>(s, structural_costs(s), brute_min_cost, checks.first, checks.second,
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)
2269 check_min_costs<Net>(s, structural_costs(s), brute_min_cost, checks.first, checks.second,
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);
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)
2287 check_min_costs<Net>(unit, c.
w, brute_min_cost, checks.first, checks.second,
false,
2301 using Net = TypeParam;
2302 Cost_Checks<Net> checks;
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)
2308 check_min_costs<Net>(unit, c.
w, brute_min_cost, checks.first, checks.second,
false,
2317 using Net = TypeParam;
2318 Cost_Checks<Net> checks;
2320 for (
const auto & [s, cost] : simplex_witnesses())
2321 check_min_costs<Net>(s, cost, ssp_min_cost, checks.first, checks.second);
2324 for (
int k = 0;
k < (
heavy() ? 200 : 20); ++
k)
2330 check_min_costs<Net>(s, c.
w, ssp_min_cost, checks.first, checks.second,
true, -1,
false);
2337 using Net = TypeParam;
2344 const auto solvers = cost_solvers<Net>();
2345 Family_Checks checks(solvers);
2346 small_structural_specs<Net>()([&] (
const Spec & s)
2348 const auto cost = structural_costs(s);
2349 for (
auto [a, z] : ends_of(s))
2353 Built_Net<Net> b(s, s.
w, cost);
2355 const auto want = brute_min_cost(s, cost, a, z);
2356 for (
size_t i = 0; i < solvers.size(); ++i)
2358 if (i == 1 or i == 3)
2360 put_initial_flow(b);
2361 const bool refused = is_ssp(i)
and negative_residual_cycle(b);
2366 const auto before = b.flows();
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");
2374 catch (
const std::domain_error &)
2376 if (b.flows() != before)
2377 check->fail(s, where(b, a, z) + costs_text(cost)
2378 +
"throws, and the flows changed");
2380 catch (
const std::exception & e)
2382 check->fail(s, where(b, a, z) + costs_text(cost) +
"throws " + e.what());
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);
2392 catch (
const std::exception & e)
2394 check->fail(s, where(b, a, z) + costs_text(cost) +
"throws " + e.what());
2408 using Double_Built = Built_Net<Double_Net>;
2411 std::vector<mpq_class> exactly(
const std::vector<double> & x)
2413 std::vector<mpq_class>
r;
2420 bool near(
double x,
const mpq_class & q)
2422 const double e = q.
get_d();
2423 return std::abs(x - e) <= 1e-9 * std::max(1.0, std::abs(e));
2427 mpq_class exact_min_cut(
const Spec & s,
const std::vector<mpq_class> & cap,
int a,
int z)
2430 for (
unsigned long set = 0; set < (1UL << s.
n); ++set)
2432 if (((set >> a) & 1UL) == 0 or ((set >> z) & 1UL) != 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)
2438 if (best < 0 or cut < best)
2448 std::string floating_error(
const Double_Built & b,
double got,
const mpq_class & want)
2450 if (
auto e = flow_error(b,
true); not e.empty())
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());
2461 std::vector<Solver<Double_Net>> floating_solvers()
2463 return all_solvers<Double_Net>();
2470 void for_each_tenths_network(
F f)
2474 for_each_assignment(s, {1, 2, 3}, [&] (
const Spec & t)
2476 std::vector<double> cap;
2477 for (
long long k : t.
w)
2478 cap.push_back(double(
k) / 10);
2486TEST(ExhaustiveFloatingFlow, TenthsStayNearTheExactMaximum)
2488 const auto solvers = floating_solvers();
2489 Family_Checks checks(solvers);
2491 for_each_tenths_network([&] (
const Spec & s,
const std::vector<double> & cap)
2493 const auto exact = exactly(cap);
2494 for (
auto [a, z] : ends_of(s))
2496 Double_Built b(s, cap, Double_Built::Amounts{});
2499 for (
size_t i = 0; i < solvers.size(); ++i)
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);
2513TEST(ExhaustiveFloatingFlow, CutsDecompositionsAndStatisticsOfTenths)
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");
2519 for_each_tenths_network([&] (
const Spec & s,
const std::vector<double> & cap)
2521 const auto exact = exactly(cap);
2522 for (
auto [a, z] : ends_of(s))
2527 Double_Built b(s, cap, Double_Built::Amounts{});
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");
2541 stats.
fail(s, where(b, a, z) +
"the flow is " + text(st.
total_flow));
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");
2552 for (
const Check * c : {&cut, &stats, &decomposition})
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)
2567 const auto exact = exactly(cap);
2568 for (
auto [a, z] : ends)
2570 Double_Built b(s, cap, Double_Built::Amounts{});
2573 for (
size_t i = 0; i < solvers.size(); ++i)
2578 const double got = solvers[i].run(b.net);
2581 e = floating_error(b, got, want);
2582 else if (e = flow_error(b,
true); e.empty())
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());
2591 check->fail(shown, where(b, a, z) + e);
2597TEST(ExhaustiveFloatingFlow, RealsStayNearTheExactMaximum)
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)
2604 check_floating(solvers, checks, s, cap, shown, ends);
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}),
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}});
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,
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,
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},
2652 std::uniform_real_distribution<double> real(0.01, 10.0);
2653 for (
int k = 0;
k < (
heavy() ? 400 : 40); ++
k)
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));
2664TEST(ExhaustiveFloatingFlow, TenthsOnRandomNetworksStayNearTheExactMaximum)
2666 const auto solvers = floating_solvers();
2667 Family_Checks checks(solvers);
2668 auto tenths_of = [] (
const std::vector<long long> &
w)
2670 std::vector<double> cap;
2671 for (
long long k :
w)
2672 cap.push_back(
double(
k) / 10);
2683 small.
arcs = {{1, 3}, {3, 5}, {5, 2}, {4, 3}, {0, 2}, {4, 0}, {0, 1}, {5, 0}, {4, 0}, {0, 1},
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}});
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}});
2700 for (
int k = 0;
k < (
heavy() ? 400 : 40); ++
k)
2704 check_floating(solvers, checks, s, tenths_of(s.
w), s, ends_of(s));
2712 using Double_Cost_Built = Built_Net<Double_Cost_Net>;
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)
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)
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;
2749 const auto [
value, total] = min_cost(tenths, cost, a, z);
2750 for (
size_t i = 0; i < solvers.size(); ++i)
2755 const bool refused = is_ssp(i)
and negative_residual_cycle(b);
2759 const auto got = solvers[i].run(b.net);
2761 e =
"a cycle of negative cost: does not throw";
2762 else if (e = flow_error(b,
true); not e.empty())
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());
2776 catch (
const std::domain_error & x)
2779 e = std::string(
"throws ") + x.what();
2781 catch (
const std::exception & x)
2783 e = std::string(
"throws ") + x.what();
2786 check->fail(tenths, where(b, a, z) + costs_text(cost) + e);
2792TEST(ExhaustiveFloatingFlow, CheapestMaxFlowsOfTenths)
2794 const auto solvers = cost_solvers<Double_Cost_Net>();
2795 Family_Checks checks(solvers);
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)
2808 return std::pair<long long, long long>(10, -80);
2816 for (
int k = 0;
k < (
heavy() ? 2000 : 200); ++
k)
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);
2828 for (
int k = 0;
k < (
heavy() ? 200 : 20); ++
k)
2834 check_tenths_min_costs(solvers, checks, s, c.
w,
w.w, ends_of(s), ssp_min_cost);
2839TEST(ExhaustiveFloatingFlow, PathsCarryTheLeastCapacityExactly)
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)};
2851 for (
int n = 2; n <= 4; ++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)
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{});
2865 for (
size_t i = 0; i < solvers.size(); ++i)
2867 const bool exact = i <= 1 or i == 5 or i == 6;
2868 auto is_least = [&] (
double x)
2870 return exact ? x == least : std::abs(x - least) <= 1e-9 * least;
2875 const double got = solvers[i].run(b.net);
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);
2888 check->fail(shown,
"capacities 3, 3 - ulp, 3 + ulp by 0, 1, 2: " + e);
2897TEST(ExhaustiveFloatingFlow, SmallFlowsBesideLargeCapacitiesStay)
2906 const auto solvers = floating_solvers();
2907 Family_Checks checks(solvers);
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}});
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}});
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}});
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)
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);
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}});
2972 far.arcs = {{2, 0}, {6, 3}, {1, 6}, {1, 4}, {0, 0}, {5, 0}, {1, 1}, {0, 1}, {4, 5}, {0, 6},
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}});
2992 std::uniform_real_distribution<double> exponent(-6.0, 6.0);
2993 for (
int k = 0;
k < (
heavy() ? 300 : 30); ++
k)
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));
3010 using Matrix = std::vector<std::vector<long long>>;
3012 std::string matrix_text(
const Matrix & c)
3014 std::string
r =
"{";
3015 for (
size_t i = 0; i < c.size(); ++i)
3017 r += i == 0 ?
"{" :
" {";
3018 for (
size_t j = 0; j < c[i].size(); ++j)
3028 long long best_assignment(
const Matrix & c,
bool most =
false)
3030 const size_t m = c.size(), n =
m == 0 ? 0 : c[0].size();
3031 const size_t k = std::min(
m, n);
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();
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);
3044 while (std::next_permutation(perm.begin(), perm.end()));
3045 return k == 0 ? 0 : best;
3050 void for_each_matrix(
size_t rows,
size_t cols,
const std::vector<long long> & values,
F f)
3052 std::vector<size_t> pick(
rows *
cols, 0);
3056 for (
size_t k = 0;
k < pick.size(); ++
k)
3060 while (i < pick.size()
and ++pick[i] == values.size())
3062 if (i == pick.size())
3071 void for_each_assignment_matrix(
bool square,
F f)
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);
3079 for (
int k = 0;
k < (
heavy() ? 300 : 40); ++
k)
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;
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)
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";
3102 size_t assigned = 0;
3103 for (
size_t i = 0; i <
m; ++i)
3105 const long j = row_to_col[i];
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)];
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);
3131 using C = TypeParam;
3132 Check function(
"hungarian_assignment()");
3133 Check object(
"Hungarian_Assignment");
3134 Check most(
"hungarian_max_assignment()");
3136 for_each_assignment_matrix(
false, [&] (
const Matrix & c)
3138 const size_t m = c.size(), n = c[0].
size();
3141 const std::string what =
"the costs " + matrix_text(c) +
": ";
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);
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);
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");
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];
3174 (void)
h.get_assignment(
m);
3177 catch (
const std::out_of_range &) {}
3179 object.fail(shown, what +
"a wrong answer from a query");
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);
3189 most.
fail(shown, what + e);
3198 using C = TypeParam;
3200 for_each_assignment_matrix(
true, [&] (
const Matrix & c)
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));
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())
3214 const auto [i, j] = it.get_curr();
3215 if (i < c.size()
and j < c.size())
3217 row_to_col[i] = long(j);
3218 col_to_row[j] = long(i);
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");
3232 if (not
r.feasible or not
r.assignments.is_empty())
3233 check.fail(
Spec(),
"no workers: not feasible, or pairs");
3238TEST(ExhaustiveAssignmentLimits, HungarianWithCostsNearTheLimits)
3240 constexpr int Max = std::numeric_limits<int>::max();
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()");
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}},
3257 {{Max, Max}, {0, 0}},
3258 {{1000000000, 1000000000, 1000000000}, {1000000000, 1000000000, 1000000000},
3259 {1000000000, 1000000000, 1000000000}}};
3260 for (
const auto & c : cases)
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);
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]);
3277 overflow.
fail(
Spec(),
"the costs " + matrix_text(c) +
": gives "
3278 + std::to_string(
r.total_cost) +
", not overflow_error");
3280 catch (
const std::overflow_error &)
3284 catch (
const std::exception & e)
3286 overflow.
fail(
Spec(),
"the costs " + matrix_text(c) +
": throws " + e.what());
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));
3299 catch (
const std::exception & e)
3301 which.
fail(
Spec(),
"the costs " + matrix_text(c) +
": throws " + e.what());
3314 long long best_transport(
const std::vector<long long> & sup,
const std::vector<long long> & dem,
3317 if (std::accumulate(sup.begin(), sup.end(), 0
LL)
3318 != std::accumulate(dem.begin(), dem.end(), 0
LL))
3320 const size_t m = sup.
size(), n = dem.size();
3321 std::vector<long long> x(
m * n, 0);
3322 long long best = -1;
3326 for (
size_t i = 0; i <
m and ok; ++i)
3329 for (
size_t j = 0; j < n; ++j)
3330 row += x[i * n + j];
3333 for (
size_t j = 0; j < n
and ok; ++j)
3336 for (
size_t i = 0; i <
m; ++i)
3337 col += x[i * n + j];
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)
3349 while (
k < x.size()
and ++x[
k] > std::min(sup[
k / n], dem[
k % n]))
3359 using C = TypeParam;
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)
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)
3370 std::vector<C> s, d;
3375 std::vector<std::vector<C>> cost(
m);
3376 for (
size_t i = 0; i <
m; ++i)
3378 cost[i].push_back(C(x));
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)))
3385 check.fail(
Spec(), what +
"feasible " + std::to_string(
r.feasible) +
" and cost "
3386 + text(
r.total_cost) +
", not " + std::to_string(want));
3392 for (
size_t i = 0; i <
m; ++i)
3395 for (
size_t j = 0; j < n; ++j)
3397 row +=
r.shipments[i][j];
3398 total +=
r.shipments[i][j] * cost[i][j];
3401 check.fail(
Spec(), what +
"a supply is not shipped");
3403 for (
size_t j = 0; j < n; ++j)
3406 for (
size_t i = 0; i <
m; ++i)
3407 col +=
r.shipments[i][j];
3409 check.fail(
Spec(), what +
"a demand is not met");
3411 if (total !=
r.total_cost)
3412 check.fail(
Spec(), what +
"the shipments cost " + text(total));
3418TEST(ExhaustiveAssignmentLimits, TransportationOfTenths)
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)
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(), 0
LL)
3430 != std::accumulate(dem.begin(), dem.end(), 0
LL))
3432 std::vector<double> s, d;
3434 s.push_back(
double(x) / 10);
3436 d.push_back(
double(x) / 10);
3439 const std::vector<std::vector<double>> cost(
m, std::vector<double>(n, 1.0));
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));
3457 long long best_transshipment(
const Spec & s,
const std::vector<long long> & cost,
3458 const std::vector<long long> & d)
3460 std::vector<long long> f(s.
arcs.size(), 0);
3461 long long best = -1;
3464 std::vector<long long> net(
size_t(s.
n), 0);
3465 for (
size_t i = 0; i < f.size(); ++i)
3467 net[size_t(s.
arcs[i][0])] += f[i];
3468 net[size_t(s.
arcs[i][1])] -= f[i];
3473 for (
size_t i = 0; i < f.size(); ++i)
3474 c += f[i] * cost[i];
3475 if (best < 0 or c < best)
3479 while (i < f.size()
and ++f[i] > s.
w[i])
3489 using Net = TypeParam;
3495 const Spec s = structural(raw);
3496 const auto cost = structural_costs(s);
3497 std::vector<long long> values = {-1, 0, 1};
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)
3503 const std::vector<long long> & d = dem.
w;
3504 const long long total = std::accumulate(d.begin(), d.end(), 0
LL);
3505 const bool nothing = std::all_of(d.begin(), d.end(), [] (
long long x) { return x == 0; });
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);
3519 catch (
const std::exception & e)
3521 c.
fail(s, what +
"throws " + e.what());
3524 const long long want = total != 0 ? -1 : nothing ? 0 : best_transshipment(s, cost, d);
3525 if (
r.feasible != (want >= 0))
3527 c.
fail(s, what + (want >= 0 ?
"says infeasible" :
"says feasible"));
3530 if (b.net.get_num_nodes() !=
nodes or b.net.get_num_arcs() !=
arcs)
3532 c.
fail(s, what +
"leaves the super nodes");
3535 if (want <= 0
and nothing)
3539 long long supply = 0;
3540 for (
long long x : d)
3541 supply += std::max(x, 0
LL);
3542 if (not is_amount(
r.total_flow, supply) or not is_cost(
r.total_cost, want))
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)));
3549 for (
int v = 0; v < s.
n; ++v)
3551 auto p = b.nodes[size_t(v)];
3552 if (b.net.get_out_flow(p) - b.net.get_in_flow(p) != demand[p])
3554 c.
fail(s, what +
"the flows left do not meet the demand of "
3555 + std::to_string(v));
3559 if (b.net.flow_cost() !=
r.total_cost)
3560 c.
fail(s, what +
"the flows left cost " + text(b.net.flow_cost()));
3573 bool circulation_exists(
const Spec & s,
const std::vector<long long> & lower,
3574 const std::vector<long long> & d)
3576 std::vector<long long> f = lower;
3579 std::vector<long long> net(
size_t(s.
n), 0);
3580 for (
size_t i = 0; i < f.size(); ++i)
3582 net[size_t(s.
arcs[i][1])] += f[i];
3583 net[size_t(s.
arcs[i][0])] -= f[i];
3588 while (i < f.size()
and ++f[i] > s.
w[i])
3589 f[i] = lower[i], ++i;
3596TEST(ExhaustiveNetApps, CirculationsMatchTheOracle)
3600 Check restored(
"solve_circulation(), the network after");
3604 const Spec s = structural(raw);
3607 per_node.
arcs.assign(
size_t(s.
n), {0, 0});
3608 for_each_assignment(per_node, {-1, 0, 1}, [&] (
const Spec & dem)
3610 for_each_assignment(s, {0, 1}, [&] (
const Spec &
low)
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}) +
": ";
3628 [&] (
Net::Arc * a) { return lb[a]; });
3630 catch (
const std::exception & e)
3632 check.fail(s, what +
"throws " + e.what());
3635 const bool want = circulation_exists(s, lower, d);
3636 if (
r.feasible != want)
3637 check.fail(s, what + (want ?
"says infeasible" :
"says feasible"));
3641 std::vector<long> in(
size_t(s.
n), 0),
out(
size_t(s.
n), 0);
3643 for (
size_t i = 0; i < b.arcs.size()
and e.empty(); ++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;
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)]);
3657 check.fail(s, what +
"the flows: " + e);
3661 bool same = b.net.get_num_nodes() == size_t(s.
n)
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;
3666 restored.
fail(s, what +
"the network is not as it was");
3674TEST(ExhaustiveNetApps, ProjectSelectionsMatchTheOracle)
3677 auto run = [&] (
const Spec & s,
const Spec & p)
3680 std::vector<Project<long>> projects;
3681 for (
int i = 0; i < s.
n; ++i)
3683 std::vector<size_t> pre;
3684 for (
const auto & a : s.
arcs)
3686 pre.push_back(
size_t(a[1]));
3687 projects.emplace_back(
size_t(i), long(p.w[
size_t(i)]), pre);
3690 for (
unsigned long set = 0; set < (1UL << s.
n); ++set)
3693 for (
const auto & a : s.
arcs)
3694 closed = closed
and (((set >> a[0]) & 1UL) == 0 or ((set >> a[1]) & 1UL) != 0);
3696 for (
int i = 0; i < s.
n; ++i)
3697 profit += ((set >> i) & 1UL) ?
long(p.w[
size_t(i)]) : 0;
3699 best = std::max(best, profit);
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)
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;
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");
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); });
3735 for (
int k = 0;
k < (
heavy() ? 2000 : 200); ++
k)
3737 const int n = 5 + int(
rng() % 2);
3741 p.
arcs.assign(
size_t(n), {0, 0});
3753 bool eliminated(
const std::vector<Team> & t,
size_t x)
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});
3762 std::vector<int>
k(pairs.size(), 0);
3765 std::vector<int>
w(t.size());
3766 for (
size_t i = 0; i < t.size(); ++i)
3768 for (
size_t p = 0; p < pairs.
size(); ++p)
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];
3775 for (
size_t i = 0; i < t.size(); ++i)
3776 first = first
and (i == x or
w[i] <= top);
3780 while (p < pairs.size()
and ++
k[p] > t[pairs[p].first].against[pairs[p].second])
3782 if (p == pairs.size())
3789 bool proves(
const std::vector<Team> & t,
size_t x,
const std::vector<size_t> &
r)
3796 if (i == x or i >= t.size())
3801 total += t[i].against[j];
3803 return total > long(
r.size()) * (t[x].wins + t[x].remaining);
3807TEST(ExhaustiveNetApps, BaseballEliminationsMatchTheOracle)
3810 Check certificate(
"check_baseball_elimination(), the certificate");
3812 auto run = [&] (
const std::vector<Team> & t)
3815 shown.n = int(t.size());
3816 for (
size_t x = 0; x < t.size(); ++x)
3818 std::string what =
"wins";
3819 for (
const auto & team : t)
3820 what +=
" " + std::to_string(team.wins);
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) +
": ";
3828 const bool want = eliminated(t, x);
3829 if (
r.eliminated != want or
r.max_possible_wins != t[x].wins + t[x].remaining)
3831 check.fail(shown, what + (want ?
"says not eliminated" :
"says eliminated"));
3837 if (not proves(t, x,
r.certificate))
3838 certificate.
fail(shown, what +
"the certificate proves nothing");
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)
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)
3858 t[i].against.assign(g[i], g[i] + 3);
3859 t[i].remaining = g[i][0] + g[i][1] + g[i][2];
3864 for (
int k = 0;
k < (
heavy() ? 2000 : 200); ++
k)
3866 const size_t n = 4 +
rng() % 2;
3867 std::vector<Team> t(n);
3868 for (
auto & team : t)
3870 team.wins = int(
rng() % 4);
3871 team.against.assign(n, 0);
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)
3885TEST(ExhaustiveNetApps, SegmentationsMatchTheOracle)
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)
3893 const size_t rows = grid.first,
cols = grid.second;
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 : {0
LL, 1LL})
3898 for_each_matrix(1, 2 * pixels, values, [&] (
const Matrix &
m)
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)
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)
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);
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));
3924 unsigned long got = 0;
3925 bool shaped =
r.labels.size() ==
rows;
3926 for (
size_t i = 0; i <
rows and shaped; ++i)
3928 shaped =
r.labels[i].size() ==
cols;
3929 for (
size_t j = 0; j <
cols and shaped; ++j)
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);
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) +
": ";
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));
3955 bool survey_exists(
const std::vector<SurveyQuestion> & q,
const std::vector<SurveyRespondent> &
r)
3957 std::vector<std::pair<size_t, size_t>> pairs;
3958 for (
size_t i = 0; i <
r.size(); ++i)
3960 const auto & e =
r[i].eligible_questions;
3961 for (
size_t j :
std::set<size_t>(e.begin(), e.end()))
3963 pairs.push_back({i, j});
3965 for (
unsigned long set = 0; set < (1UL << pairs.size()); ++set)
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)
3971 ++by_r[pairs[
k].first];
3972 ++by_q[pairs[
k].second];
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;
3986TEST(ExhaustiveNetApps, SurveysMatchTheOracle)
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)
3996 const size_t knobs = nq + 2 * nr;
3997 std::vector<size_t> pick(knobs, 0);
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)
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});
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)
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);
4031 if (res.feasible != want)
4032 c.
fail(
Spec(), what + (want ?
"says infeasible" :
"says feasible"));
4036 std::vector<int> by_q(nq, 0), by_r(nr, 0);
4038 std::set<std::pair<size_t, size_t>> seen;
4039 for (
auto [ri, qj] : res.assignments)
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();
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;
4055 c.
fail(
Spec(), what +
"the answers break a bound");
4060 const size_t limit =
k < nq or (
k - nq) % 2 == 0 ? bounds.size() : (1U << nq);
4061 if (++pick[
k] < limit)
4080 long long node_capacity_max_flow(
const Spec & s,
const std::vector<long long> & node_cap,
4083 long long total = 1;
4084 for (
long long w : s.
w)
4088 for (
int v = 0; v < s.
n; ++v)
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)]);
4093 for (
size_t i = 0; i < s.
arcs.size(); ++i)
4096 x.
w.push_back(s.
w[i]);
4098 return max_flow_units(x, a, s.
n + z);
4113 using Net = TypeParam;
4115 Check flow(
"compute_aux_net(), dinic_maximum_flow() and update()");
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()");
4126 const Spec s = structural(raw);
4129 per_node.
arcs.assign(
size_t(s.
n), {0, 0});
4131 size_t assignment = 0;
4132 for_each_assignment(per_node, {-1, 0, 1}, [&] (
const Spec & caps)
4134 const bool with_paths = assignment++ % 3 == 0;
4135 for (
auto [a, z] : ends_of(s))
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)]));
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);
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)]));
4156 auto aux = c.net.compute_aux_net();
4162 paths.
fail(s, what +
"an arc of the auxiliary network lost its cookie");
4166 if (
auto e = max_flow_error(c, c.value(), want); not e.empty())
4167 paths.
fail(s, what + e);
4172 auto aux = b.net.compute_aux_net();
4173 if (not (aux->is_single_source()
and aux->is_single_sink()))
4175 flow.
fail(s, what +
"the auxiliary network has no single source and sink");
4180 if (
auto e = max_flow_error(b, b.value(), want); not e.empty())
4182 flow.
fail(s, what + e);
4187 bool kept = b.net.check_node_capacities();
4188 for (
int v = 0; v < s.
n and kept; ++v)
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;
4195 node_flows.fail(s, what +
"a node has not its flow, or passes its capacity");
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 "
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};
4212 freed.
fail(s, what +
"the flows or the auxiliary network are left");
4223TEST(ExhaustiveSupplyDemand, TheAuxiliaryNetworkMatchesTheOracle)
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()");
4242 auto lists_error = [] (Built_Net<Net> & b,
const Spec & sup) -> std::string
4245 b.net.non_feasible_nodes(supplies, demands);
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)
4252 const long w = long(sup.w[v]);
4255 auto p = b.nodes[v];
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())
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;
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";
4284 const Spec s = structural(raw);
4287 per_node.
arcs.assign(
size_t(s.
n), {0, 0});
4288 for_each_assignment(per_node, {-1, 0, 1}, [&] (
const Spec & sup)
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})
4294 const std::string what =
"supplies " + matrix_text({sup.w})
4295 + (set ?
", the capacities of the nodes set: " :
": ");
4296 Built_Net<Net> b(s);
4298 for (
int v = 0; v < s.
n; ++v)
4300 auto p = b.nodes[size_t(v)];
4301 p->supply_flow = long(sup.w[
size_t(v)]);
4304 p->out_cap = b.net.get_out_cap(p);
4305 p->in_cap = b.net.get_in_cap(p);
4307 fits = fits
and p->supply_flow <= p->out_cap
and -p->supply_flow <= p->in_cap;
4312 b.net.compute_aux_net();
4314 aux.
fail(s, what +
"takes a supply above the capacity of its node");
4316 catch (
const std::range_error &)
4319 aux.
fail(s, what +
"throws range_error");
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");
4331 long long supply = 0, demand = 0;
4332 for (
long long x : sup.w)
4333 (x > 0 ? supply : demand) += std::abs(x);
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)
4339 x.
arcs.push_back({from, v});
4340 x.
w.push_back(sup.w[
size_t(v)]);
4342 else if (sup.w[
size_t(v)] < 0)
4344 x.
arcs.push_back({v, to});
4345 x.
w.push_back(-sup.w[
size_t(v)]);
4347 const bool want = supply == demand
and supply > 0
4348 and max_flow_units(x, from, to) == supply;
4350 if (supply == 0 or demand == 0)
4355 if (b.net.is_feasible())
4356 trivial.
fail(s, what +
"says feasible");
4360 if (b.net.is_single_source()
and b.net.is_single_sink())
4364 if (b.net.is_feasible())
4365 trivial.
fail(s, what +
"says feasible after a flow");
4368 if (
const std::string why = lists_error(b, sup); not why.empty())
4369 lists.
fail(s, what + why);
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");
4378 if (b.net.is_feasible() != want)
4379 feasible.
fail(s, what + (want ?
"says infeasible" :
"says feasible"));
4381 if (
const std::string why = lists_error(b, sup); not why.empty())
4382 lists.
fail(s, what + why);
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");
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)
4411 std::vector<double>
r;
4414 r.push_back(it.get_curr()->get_info());
4415 r.push_back(node_extra(it.get_curr()));
4419 auto a = it.get_curr();
4422 r.push_back(
double(a->cap));
4423 r.push_back(
double(a->flow));
4424 r.push_back(arc_extra(a));
4434 template <
class Net,
class Node_Extra,
class Arc_Extra,
class Prepare>
4436 Node_Extra node_extra, Arc_Extra arc_extra, Prepare prepare)
4440 const Spec s = structural(raw);
4441 Built_Net<Net> b(s);
4445 put_initial_flow(b);
4448 const auto want = contents(b.net, node_extra, arc_extra);
4453 if (contents(
copy, node_extra, arc_extra) != want)
4454 ctor.
fail(s,
"the copy is not the network");
4460 Built_Net<Net> other(structural(raw));
4462 other.net.get_cookie() = &mark;
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");
4472 Built_Net<Net> fresh(s);
4475 fresh.pin(0, s.
n - 1);
4476 put_initial_flow(fresh);
4479 const auto before = contents(fresh.net, node_extra, arc_extra);
4480 Net moved(std::move(fresh.net));
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");
4490 double nothing(
P) {
return 0; }
4493TEST(ExhaustiveNetworkCopies, CopiesKeepTheNetwork)
4500 Check plain_ctor(
"Net_Graph(const Net_Graph &)");
4501 Check plain_assign(
"Net_Graph::operator=(const Net_Graph &)");
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 &) {});
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)
4517 for (
auto a : b.arcs)
4522 auto digits = [] (std::initializer_list<long> fields)
4525 for (
long x : fields)
4526 r = 100 *
r +
double(x);
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"
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)
4541 for (
auto p : b.nodes)
4543 Cap::set_node_cap(p, c);
4544 p->in_flow = c + 10;
4545 p->out_flow = c + 20;
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,
4559 return digits({p->supply_flow, p->out_cap, p->in_cap, p->in_flow,
4562 nothing<Sup::Arc *>,
4563 [] (Built_Net<Sup> & b)
4566 for (
auto p : b.nodes)
4569 p->out_cap = c + 10;
4571 p->in_flow = c + 30;
4572 p->out_flow = c + 40;
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})
4589 template <
class Make,
class Op>
4590 size_t allocations_of(Make make, Op op)
4593 const size_t before = allocations;
4595 return allocations - before;
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)
4606 const size_t points = allocations_of(make, op);
4607 for (
size_t k = 1;
k <= points; ++
k)
4619 catch (
const std::bad_alloc &)
4624 after(*st,
k, threw);
4628 template <
class Make,
class Op,
class After>
4629 void for_each_failure(Make make, Op op, After after)
4631 for_each_failure(make, op, after, [] (
size_t) {
return false; });
4636 template <
class Net>
4637 std::vector<long> net_state(
const Net & net)
4643 r.push_back(it.get_curr()->get_info());
4645 r.push_back(1000 + it.get_curr()->get_info());
4646 std::sort(
r.begin() + 6,
r.end());
4652 template <
class Net>
4653 bool ends_kept(
const Net & net)
4657 auto p = it.get_curr();
4658 bool in =
false,
out =
false;
4677 GTEST_SKIP() <<
"ThreadSanitizer replaces the global operator new";
4684 using B = Built_Net<Net>;
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");
4691 Check unmake(
"unmake_super_source() and unmake_super_sink(), a failed allocation");
4694 Check again(
"unmake_super_source() and unmake_super_sink(), another call after a failed one");
4698 const Spec s = structural(raw);
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);
4708 return [&] (B & b,
size_t k,
bool threw)
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");
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))
4723 for_each_failure(make, [] (B & b) { b.net.make_super_nodes(); }, after(
nodes));
4726 auto made = [&] {
auto b = make(); b->net.make_super_nodes();
return b; };
4727 for (
int which = 0; which < 2; ++which)
4729 auto op = [which] (B & b)
4732 b.net.unmake_super_source();
4734 b.net.unmake_super_sink();
4736 const auto undone = [&]
4740 return net_state(b->net);
4742 for_each_failure(made, op, [&] (B & b,
size_t k,
bool threw)
4745 const std::string at =
"the allocation " + std::to_string(
k) +
" fails";
4746 if (not ends_kept(b.net))
4748 unmake.
fail(s, at +
", and the sources or sinks are wrong");
4755 if (net_state(b.net) != undone)
4756 again.
fail(s, at +
", and another call does not undo the super node");
4760 for (
const Check * c : {&source, &sink, &
nodes, &unmake, &again})
4777 Net::Net_Class plain;
4781 explicit Shipment(
const int aux)
4789 net.compute_aux_net();
4790 source = net.get_super_source();
4791 sink = net.get_super_sink();
4795 auto u = plain.insert_node(0);
4796 auto v = plain.insert_node(1);
4797 plain.insert_arc(u, v, 1);
4803 auto kept = [] (
const Net & net)
4807 if (it.get_curr() == net.get_super_source() or it.get_curr() == net.get_super_sink())
4809 const size_t remembered = size_t(net.get_super_source() !=
nullptr)
4810 + size_t(net.get_super_sink() !=
nullptr);
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};
4819 for (
int aux = 0; aux < 3; ++aux)
4820 for (
int which = 0; which < 5; ++which)
4823 const Shipment probe(aux);
4824 if ((which == 0
and probe.source ==
nullptr) or (which == 1
and probe.sink ==
nullptr))
4827 auto make = [aux] {
return std::make_unique<Shipment>(aux); };
4828 for_each_failure(make,
4829 [which] (Shipment & sh)
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;
4842 [&] (Shipment & sh,
size_t k,
bool threw)
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;
4853 EXPECT_EQ(sh.net.get_num_nodes(), 0u) << at;
4854 EXPECT_FALSE(sh.net.exist_aux_net()) << at;
4859 ASSERT_TRUE(kept(sh.net)) << at;
4860 if (which < 3
and sh.net.get_num_arcs() < arcs_made[aux])
4862 if (which == 0 or which == 3)
4864 EXPECT_EQ(sh.net.get_super_source(), sh.source) << at;
4866 if (which == 1 or which == 3)
4868 EXPECT_EQ(sh.net.get_super_sink(), sh.sink) << at;
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;
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";
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");
4896 Built_Net<Net> from;
4897 Pair(
const Spec & a,
const Spec & b) : to(a), from(b) {}
4902 Built_Net<Other> from;
4903 Inter_Pair(
const Spec & a,
const Spec & b) : to(a), from(b) {}
4908 target.
arcs = {{0, 1}, {1, 2}};
4909 target = structural(target);
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)
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");
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)
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");
4935 for (
Check * c : {&persistent, &inter_persistent})
4938 Inter_Pair q(target, s);
4944 if (c == &persistent)
4949 catch (
const std::bad_alloc &)
4954 const auto & to = c == &persistent ? p.to.net : q.to.net;
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");
4966 inter_persistent.
expect();
4974 Check assign(
"Net_Cap_Graph::operator=(const Net_Cap_Graph &), a failed allocation");
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");
4986 Two(
const Spec & a,
const Spec & b) : x(a),
y(b)
4989 for (
auto p : x.nodes)
4990 Net::set_node_cap(p, c++);
4991 x.net.compute_aux_net();
4997 other.
arcs = {{0, 1}};
4998 other = structural(other);
5001 const Spec s = structural(raw);
5002 auto make = [&] {
return std::make_unique<Two>(s, other); };
5003 const auto before = [&]
5006 return contents(t->x.net, [] (
Net::Node * p) { return double(p->max_cap); },
5007 nothing<Net::Arc *>);
5009 for_each_failure(make, [] (Two & t) { t.x.net = t.y.net; },
5010 [&] (Two & t,
size_t k,
bool threw)
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");
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");
5025 std::unique_ptr<Two> two;
5026 Owned(
const Spec & a,
const Spec & b) : two(std::make_unique<Two>(a, b)) {}
5029 if (
const size_t k = allocations_of([&] {
return std::make_unique<Owned>(s, other); },
5030 [] (Owned & o) { o.two.reset(); });
5032 dtor.
fail(s,
"makes " + std::to_string(
k) +
" allocations");
5034 if (
const size_t k = allocations_of(make, [] (Two & t) { t.x.net = std::move(t.y.net); });
5036 move.
fail(s,
"makes " + std::to_string(
k) +
" allocations");
5054 struct Removal_Watched_Net : Long_Cost_Net
5056 bool failed_in_removal =
false;
5058 void remove_node(
Node * p)
override
5062 Long_Cost_Net::remove_node(p);
5064 catch (
const std::bad_alloc &)
5066 failed_in_removal =
true;
5075 using Net = Long_Cost_Net;
5076 using Watched = Removal_Watched_Net;
5080 Check ssp(
"successive_shortest_paths(), a failed allocation");
5084 Check transshipment(
"solve_transshipment(), a failed allocation");
5085 Check removal(
"solve_transshipment(), a failed allocation in the removal of its super nodes");
5087 small_structural_specs<Net>()([&] (
const Spec & s)
5091 const auto cost = structural_costs(s);
5094 auto b = std::make_unique<Built_Net<Net>>(s, s.
w, cost);
5099 [&] (Built_Net<Net> & b,
size_t k,
bool threw)
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");
5112 std::vector<long long> d(
size_t(s.
n), 0);
5114 d[size_t(s.
n - 1)] = -1;
5115 if (best_transshipment(s, cost, d) < 0)
5117 auto plain = [&] {
return std::make_unique<Built_Net<Watched>>(s, s.
w, cost); };
5118 auto demand_of = [d] (
const Built_Net<Watched> & b)
5120 return [&b, d] (Watched::Node * p)
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)]);
5128 for_each_failure(plain,
5130 [&] (Built_Net<Watched> & b,
size_t k,
bool threw)
5132 const std::string at =
"the allocation " + std::to_string(
k) +
" fails";
5133 if (b.net.failed_in_removal)
5137 const std::set<Watched::Node *>
nodes(b.nodes.begin(),
5139 const std::set<Watched::Arc *>
arcs(b.arcs.begin(), b.arcs.end());
5140 size_t kept_nodes = 0, kept_arcs = 0;
5142 kept_nodes +=
nodes.count(it.get_curr());
5144 kept_arcs +=
arcs.count(it.get_curr());
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");
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");
5160 transshipment.expect();
5170 constexpr long long Max = std::numeric_limits<int>::max();
5171 Check build(
"Johnson(g)");
5174 Check build_over(
"Johnson(g), a reweighted arc beyond max()");
5175 Check distances(
"Johnson::get_distance()");
5178 Check distances_over(
"Johnson::get_distance(), a reweighted sum beyond max()");
5179 Check negative(
"Johnson(g), with a negative cycle");
5181 auto run = [&] (
const Spec & s)
5186 std::vector<GT::Node *>
nodes;
5187 for (
int i = 0; i < s.
n; ++i)
5189 for (
size_t i = 0; i < s.
arcs.size(); ++i)
5197 negative.
fail(s,
"does not throw");
5199 catch (
const std::domain_error &) {}
5200 catch (
const std::exception & e)
5202 negative.
fail(s, std::string(
"throws ") + e.what());
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)
5212 h[size_t(v)] = std::min(
h[
size_t(v)], d[
size_t(u)][
size_t(v)]);
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;
5218 std::unique_ptr<Johnson<GT>> j;
5221 j = std::make_unique<Johnson<GT>>(g);
5223 catch (
const std::exception & e)
5225 c.
fail(s, std::string(
"throws ") + e.what());
5229 for (
int a = 0; a < s.
n; ++a)
5231 bool sum_over =
false;
5232 for (
size_t i = 0; i < s.
arcs.size(); ++i)
5234 const int u = s.
arcs[i][0], v = s.
arcs[i][1];
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;
5239 Check & dc = sum_over ? distances_over : distances;
5241 for (
int z = 0; z < s.
n; ++z)
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)
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)
5251 dc.
fail(s, at +
"gives " + std::to_string(got) +
", not "
5252 + (want ==
oracle::Inf ?
"max()" : std::to_string(want)));
5256 catch (
const std::overflow_error & e)
5260 dc.
fail(s, at +
"throws " + e.what() +
" for " + std::to_string(want));
5271 for_each_assignment(s, {-1, 0, 2}, run);
5277 for_each_assignment(s, {-10, 1, Max - 5}, run);
5291 using Net = TypeParam;
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()");
5298 small_structural_specs<Net>()([&] (
const Spec & s)
5300 for (
auto [a, z] : ends_of(s))
5302 Built_Net<Net> b(s);
5304 put_initial_flow(b);
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)
5317 if (b.net.get_tgt_node(arc) == p)
5320 in_flow += arc->flow;
5323 from.insert(b.net.get_src_node(arc));
5325 if (b.net.get_src_node(arc) == p)
5327 out_cap += arc->cap;
5328 out_flow += arc->flow;
5331 to.insert(b.net.get_tgt_node(arc));
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)
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());
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));
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");
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)
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");
5369 for (
auto arc : b.arcs)
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;
5375 b.net.set_flow(arc, cap + amount<F>(1));
5378 catch (
const std::out_of_range &) {}
5383 b.net.set_cap(arc, flow - amount<F>(1));
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);
5395 setters.
fail(s, where(b, a, z) +
"a setter does not keep its contract");
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();
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));
5410 b.net.insert_arc(b.src, b.snk, amount<F>(1), amount<F>(2));
5412 catch (
const std::overflow_error &)
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");
5421 for (
auto arc : b.arcs)
5422 if (arc->flow !=
F{0})
5424 setters.
fail(s, where(b, a, z) +
"reset() leaves a flow");
5437 using Net = TypeParam;
5439 Check preflow(
"preflow_create_residual_net() and update_flow()");
5440 Check cost(
"build_residual_net(), check_residual_net() and residual_to_net()");
5442 small_structural_specs<Net>()([&] (
const Spec & s)
5444 for (
auto [a, z] : ends_of(s))
5448 Built_Net<Net> b(s, s.
w, structural_costs(s));
5450 put_initial_flow(b);
5451 const auto flows = b.flows();
5456 bool ok = rnet.get_num_nodes() == b.net.get_num_nodes()
5457 and rnet.get_num_arcs() == 2 * b.net.get_num_arcs()
5462 for (
typename Rnet::Arc_Iterator it(rnet); it.has_curr()
and ok; it.next_ne())
5464 auto r = it.get_curr();
5465 if (
r->is_residual())
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
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");
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)
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;
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");
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
size_t size_t int32_t value
size_t size_t int32_t * out
Iterator over the arcs of a node.
bool has_curr() const noexcept
Return true if the iterator is on an arc.
Generic directed graph (digraph) wrapper template.
constexpr bool is_empty() const noexcept
Return true if this (as header node) is empty.
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).
T & get_first()
Return the first item of the list.
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.
void allocate()
Pre-allocate memory for the entire matrix.
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.
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.
SemiPath< Net > find_dec_path(typename Net::Flow_Type min_slack=0.0)
Find a decrementing semi-path with at least min_slack.
constexpr bool is_empty() const noexcept
Implementation of the Hungarian (Munkres) algorithm.
Johnson's algorithm for all-pairs shortest paths.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Sparse matrix with generic row and column domains.
Number Theoretic Transform over Z / MOD Z.
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.
Iterator on nodes and arcs of a path.
bool has_current_node() const noexcept
Return true if the iterator has a current node.
bool has_current_arc() const noexcept
Return true if iterator has current arc.
size_t size() const noexcept
Return the path length in nodes.
bool is_empty() const noexcept
Return true if the path is empty.
Minimal std::expected-style result type for C++20.
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
constexpr size_t size() const noexcept
Returns the number of entries in the table.
void empty()
Clears all entries and resets to default capacity.
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.
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)
__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)
__gmp_expr< mpq_t, mpq_t > mpq_class
::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
DynArray< Graph::Arc * > arcs
#define ARC_COOKIE(p)
Return the arc cookie
void inter_copy_graph(GTT >gt, const GTS &gsrc, const bool cookie_map=false)
Copy between different types of graphs.
Hungarian_Result< Cost_Type > hungarian_max_assignment(const DynMatrix< Cost_Type > &cost)
Compute maximum-profit assignment (free function).
Hungarian_Result< Cost_Type > hungarian_assignment(const DynMatrix< Cost_Type > &cost)
Compute minimum-cost assignment (free function).
#define NODE_COOKIE(p)
Return the node cookie
void copy_graph(GT >gt, const GT &gsrc, bool cookie_map=false)
Explicit copy of graph.
@ 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
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.
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.
Net::Flow_Type edmonds_karp_maximum_flow(Net &net)
Maximize flow using the Edmonds-Karp algorithm.
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.
BaseballEliminationResult check_baseball_elimination(const std::vector< Team > &teams, size_t team_idx)
Check if a team is mathematically eliminated from winning.
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.
SemiPath< Net > find_aumenting_semi_path_bfs(const Net &net, const typename Net::Flow_Type &slack)
Find an augmenting semi-path using BFS.
Net::Flow_Type increase_flow(Net &net, const Path< Net > &path)
Increase flow along an augmenting path.
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.
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.
Path< Net > find_aumenting_path_bfs(const Net &net, const typename Net::Flow_Type &min_slack)
Find an augmenting path using BFS.
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:
ProjectSelectionResult< Value_Type > solve_project_selection(const std::vector< Project< Value_Type > > &projects)
Solve project selection problem using max-flow.
Operation for_each(Itor beg, const Itor &end, Operation op)
Apply an operation to each element in a range.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
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.
SurveyDesignResult design_survey(const std::vector< SurveyQuestion > &questions, const std::vector< SurveyRespondent > &respondents)
Design survey assignment using network flow.
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.
SemiPath< Net > find_decrementing_path_bfs(const Net &net, const typename Net::Flow_Type &slack)
Find a decrementing semi-path using BFS.
void update_flow(const Rnet &rnet)
Propagate residual arc flows back to their original arcs.
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).
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.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
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...
Network flow applications.
Filtered iterator on all the arcs of a graph.
Iterator over arcs of a graph.
Functor wrapper for capacity scaling.
Result of a circulation problem.
Functor wrapper for flow decomposition.
Functor wrapper for Dinic's algorithm.
Functor wrapper for edmonds_karp_maximum_flow().
Functor wrapper for fifo_preflow_maximum_flow().
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().
Arc of graph implemented with double-linked adjacency lists.
Functor wrapper for HLPP.
Functor wrapper for heap_preflow_maximum_flow().
Functor wrapper for maximum flow minimum cost algorithm.
Functor wrapper for Network Simplex algorithm.
Functor wrapper for min_cut().
Arc of a flow network implemented with adjacency lists.
Arc type for maximum flow minimum cost networks.
Capacitated flow network with costs associated to arcs.
Flow network implemented with adjacency lists.
Flow_Type get_out_flow(Node *node) const noexcept
Return total outgoing flow of node.
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
bool with_super_sink
True if the network has a super-sink.
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
bool is_source(Node *node) const noexcept
Return true if node is a source.
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.
bool with_super_source
True if the network has a super-source.
Flow_Type get_in_flow(Node *node) const noexcept
Return total incoming flow of node.
bool is_sink(Node *node) const noexcept
Return true if node is a sink.
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Functor wrapper for random_preflow_maximum_flow().
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)
void assign(BinTree< int >::Node *node, int, int)
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.