38#include <gtest/gtest.h>
96 SingleArcNet build_single_arc(
Net &net,
int cap,
int flow = 0)
101 sn.st = net.
insert_arc(sn.s, sn.t, cap, flow);
106TEST(NetGraphBasics, SourcesSinksUpdateOnArcOperations)
132TEST(NetGraphBasics, DisconnectConnectArcUpdatesSets)
150TEST(NetGraphSuperNodes, MakeAndUnmakeSuperSource)
173 bool has_self =
false;
176 if (it.get_tgt_node_ne() == super_source)
179 EXPECT_FALSE(has_self);
186TEST(NetGraphSuperNodes, MakeAndUnmakeSuperSink)
208 bool has_self =
false;
211 if (it.get_tgt_node_ne() == super_sink)
214 EXPECT_FALSE(has_self);
221TEST(NetGraphFlowAlgorithms, FordFulkersonAndEdmondsKarp)
224 build_simple_net(net1);
230 build_simple_net(net2);
236TEST(NetGraphFlowAlgorithms, PreflowVariants)
239 build_simple_net(net1);
244 build_simple_net(net2);
249 build_simple_net(net3);
259 void build_matching_net(
Net & net)
263 std::vector<Net::Node *> left, right;
264 for (
int i = 0; i < 4; ++i)
266 for (
int i = 0; i < 4; ++i)
268 for (
auto *
l : left)
269 net.insert_arc(s,
l, 1, 0);
270 for (
auto *
l : left)
271 for (auto *
r : right)
272 net.insert_arc(
l,
r, 1, 0);
273 for (
auto *
r : right)
274 net.insert_arc(
r, t, 1, 0);
277 std::vector<int> arc_flows(
Net & net)
279 std::vector<int> flows;
281 flows.push_back(it.get_curr_ne()->flow);
289TEST(NetGraphFlowAlgorithms, RandomPreflowWithASeedRepeatsItsPushes)
291 std::set<std::vector<int>> seen;
292 for (
unsigned long seed : {7ul, 8ul, 9ul, 10ul, 11ul, 12ul, 13ul, 14ul})
295 build_matching_net(net1);
296 build_matching_net(net2);
300 const auto flows = arc_flows(net1);
301 EXPECT_EQ(flows, arc_flows(net2)) <<
"seed " <<
seed;
304 EXPECT_GT(seen.size(), 1u);
307TEST(NetGraphAugmentingPaths, IncreaseFlowOnPath)
310 auto nodes = build_single_arc(net, 4);
316 EXPECT_EQ(
nodes.st->flow, 4);
319TEST(NetGraphAugmentingPaths, SemiPathAndIncreaseFlow)
322 auto nodes = build_single_arc(net, 4);
332 EXPECT_EQ(
nodes.st->flow, 4);
335TEST(NetGraphResidualHelpers, RemainingFlowAndFilter)
338 auto nodes = build_single_arc(net, 10, 3);
340 EXPECT_FALSE(is_residual<Net>(
nodes.s,
nodes.st));
341 EXPECT_TRUE(is_residual<Net>(
nodes.t,
nodes.st));
342 EXPECT_EQ(remaining_flow<Net>(
nodes.s,
nodes.st), 7);
343 EXPECT_EQ(remaining_flow<Net>(
nodes.t,
nodes.st), 3);
347 EXPECT_TRUE(from_src(
nodes.st));
348 EXPECT_TRUE(from_tgt(
nodes.st));
351 EXPECT_FALSE(from_src(
nodes.st));
354 EXPECT_FALSE(from_tgt(
nodes.st));
357TEST(NetGraphResidualNet, UpdateFlowFromResidual)
360 build_single_arc(net, 10, 4);
363 auto &rnet = std::get<0>(residual);
367 for (
typename Rnet::Arc_Iterator it(rnet); it.has_curr(); it.next_ne())
369 auto arc = it.get_curr();
370 if (arc->img !=
nullptr)
378 ASSERT_NE(original,
nullptr);
380 EXPECT_EQ(original->flow, 7);
383TEST(NetGraphMinCut, ComputesCutCapacity)
386 auto nodes = build_simple_net(net);
393 auto value = min_cut<Net, Edmonds_Karp_Maximum_Flow>(net, vs, vt, cuts, cutt);
400 cut_cap += it.get_curr()->cap;
402 EXPECT_EQ(cut_cap,
value);
408TEST(NetGraphBasics, AnArcWithMoreFlowThanCapacityIsNotInserted)
414 EXPECT_THROW(net.
insert_arc(s, t, 2, 3), std::overflow_error);
415 EXPECT_THROW(net.
insert_arc(s, t, 2, -1), std::overflow_error);
422 EXPECT_EQ(arc->flow, 2);
430TEST(NetGraphBasics, CopiesANetworkWithAnArithmeticArcInfo)
435 auto a = net.insert_node(2);
436 auto t = net.insert_node(3);
437 net.insert_arc(s, a, 5.0, 2.0, 7);
438 net.insert_arc(a, t, 4.0, 1.5, 8);
441 ASSERT_EQ(
copy.get_num_nodes(), 3u);
442 ASSERT_EQ(
copy.get_num_arcs(), 2u);
443 EXPECT_TRUE(
copy.is_single_source());
444 EXPECT_TRUE(
copy.is_single_sink());
445 double cap = 0, flow = 0;
447 for (Info_Net::Arc_Iterator it(
copy); it.has_curr(); it.next_ne())
449 cap += it.get_curr()->cap;
450 flow += it.get_curr()->flow;
451 info += it.get_curr()->get_info();
454 EXPECT_EQ(flow, 3.5);
459 EXPECT_EQ(assigned.get_num_arcs(), 2u);
461 auto zero =
copy.insert_arc(
copy.get_first_node(),
copy.get_first_node());
462 EXPECT_EQ(zero->cap, 0.0);
463 EXPECT_EQ(zero->get_info(), 0);
469TEST(NetGraphAugmentingPaths, ASemiPathHasTheSlackItWasAskedFor)
471 for (
bool light_first : {
true,
false})
473 SCOPED_TRACE(light_first ?
"light arc first" :
"heavy arc first");
476 auto a = net.insert_node(1);
477 auto t = net.insert_node(2);
479 net.insert_arc(s, a, 1, 0);
480 auto heavy = net.insert_arc(s, a, 5, 0);
482 net.insert_arc(s, a, 1, 0);
483 net.insert_arc(a, t, 4, 0);
489 ASSERT_EQ(path.
size(), 2u);
490 EXPECT_EQ(get<0>(path.
get_first()), heavy);
493 EXPECT_EQ(
nodes.size(), 3u);
504 Double_Net random_double_network(
unsigned seed)
506 std::mt19937 gen(
seed);
507 std::uniform_real_distribution<double> real(0.01, 10.0);
509 std::vector<Double_Net::Node *> v;
510 const int n = 4 + int(gen() % 20);
511 for (
int i = 0; i < n; ++i)
512 v.push_back(net.insert_node(i));
513 auto cap = [&]() {
return seed % 2 ? real(gen) : 0.1 * double(1 + gen() % 9); };
514 for (
int i = 0; i + 1 < n; ++i)
515 net.insert_arc(v[i], v[i + 1], cap(), 0.0);
516 for (
int k = 0,
m =
int(gen() % 80);
k <
m; ++
k)
518 const int a = int(gen() % (n - 1)), b = 1 + int(gen() % (n - 1));
520 net.insert_arc(v[a], v[b], cap(), 0.0);
526 bool flows_within_capacities(Double_Net & net)
528 for (Double_Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
529 if (
auto a = it.get_curr(); a->flow < 0 or a->flow > a->cap)
539TEST(NetGraphAugmentingPaths, FloatingFlowsStayWithinTheirCapacities)
544 Double_Net ff_net = random_double_network(
seed);
545 Double_Net ek_net = random_double_network(
seed);
546 Double_Net dinic_net = random_double_network(
seed);
547 ASSERT_TRUE(ff_net.is_single_source()
and ff_net.is_single_sink());
553 EXPECT_NEAR(ff, dinic, 1e-9 * std::max(1.0, dinic));
554 EXPECT_NEAR(ek, dinic, 1e-9 * std::max(1.0, dinic));
555 EXPECT_TRUE(flows_within_capacities(ff_net));
556 EXPECT_TRUE(flows_within_capacities(ek_net));
557 EXPECT_TRUE(ff_net.check_network());
558 EXPECT_TRUE(ek_net.check_network());
569TEST(NetGraphInfiniteFlows, EqualInfiniteFlowsBalanceAndUnequalOnesDoNot)
571 const double inf = std::numeric_limits<double>::infinity();
573 auto s = net.insert_node(0);
574 auto a = net.insert_node(1);
575 auto t = net.insert_node(2);
576 auto sa = net.insert_arc(s, a, inf);
577 auto at = net.insert_arc(a, t, inf);
578 auto st = net.insert_arc(s, t, 2.5);
582 EXPECT_TRUE(net.check_node(a));
583 EXPECT_TRUE(net.check_network());
584 EXPECT_EQ(net.flow_value(), inf);
587 EXPECT_FALSE(net.check_node(a));
588 EXPECT_FALSE(net.check_network());
594TEST(NetGraphInfiniteFlows, TheAugmentingPathsReturnAnInfiniteMaximumFlow)
596 const double inf = std::numeric_limits<double>::infinity();
597 for (
int algo = 0; algo < 2; ++algo)
600 auto s = net.insert_node(0);
601 auto a = net.insert_node(1);
602 auto t = net.insert_node(2);
603 net.insert_arc(s, a, inf);
604 net.insert_arc(a, t, inf);
605 net.insert_arc(s, t, 2.5);
608 EXPECT_EQ(
value, inf) << (algo == 0 ?
"ford_fulkerson" :
"edmonds_karp");
609 EXPECT_TRUE(net.check_network()) << (algo == 0 ?
"ford_fulkerson" :
"edmonds_karp");
621 struct Told_Net :
Net
624 int disconnections = 0;
626 void swapped() noexcept
override { ++swaps; }
638TEST(NetGraphDerived, ASwapTellsItsTwoNetworks)
641 build_single_arc(one, 5);
645 EXPECT_EQ(one.swaps, 1);
646 EXPECT_EQ(two.swaps, 1);
647 EXPECT_EQ(two.get_num_arcs(), 1U);
649 base = std::move(
static_cast<Net &
>(two));
650 EXPECT_EQ(one.swaps, 2);
651 EXPECT_EQ(two.swaps, 2);
652 EXPECT_EQ(one.get_num_arcs(), 1U);
656 EXPECT_EQ(one.swaps, 3);
657 EXPECT_EQ(two.swaps, 2);
659 Net taken(std::move(base));
660 EXPECT_EQ(one.swaps, 4);
665TEST(NetGraphDerived, ASwapWithItselfTellsNothing)
668 build_single_arc(net, 5);
672 EXPECT_EQ(net.swaps, 0);
673 EXPECT_EQ(net.get_num_nodes(), 2U);
674 EXPECT_EQ(net.get_num_arcs(), 1U);
678TEST(NetGraphDerived, ADisconnectionThroughTheBaseIsThatOfTheDerivedNetwork)
681 auto sn = build_single_arc(net, 5);
685 EXPECT_EQ(net.disconnections, 1);
686 EXPECT_EQ(net.get_num_arcs(), 0U);
689 EXPECT_EQ(net.get_num_arcs(), 1U);
721 static constexpr bool apart =
false;
746 static constexpr bool apart =
true;
767 catch (
const std::domain_error &)
780 static constexpr bool apart =
true;
806 static constexpr bool apart =
false;
825 bool sound(
const B &net)
828 for (
typename B::Node_Iterator it(net); it.has_curr(); it.next_ne())
830 for (
typename B::Arc_Iterator it(net); it.has_curr(); it.next_ne())
832 if (
nodes != net.get_num_nodes() or
arcs != net.get_num_arcs())
834 auto is_node = [&net] (
typename B::Node *p)
836 for (
typename B::Node_Iterator it(net); it.has_curr(); it.next_ne())
837 if (it.get_curr() == p)
841 for (
auto it = net.get_src_nodes().get_it(); it.has_curr(); it.next_ne())
842 if (not is_node(it.get_curr()))
844 for (
auto it = net.get_sink_nodes().get_it(); it.has_curr(); it.next_ne())
845 if (not is_node(it.get_curr()))
852 void fill_chain(B &net)
854 auto x = net.insert_node();
855 auto y = net.insert_node();
856 auto z = net.insert_node();
857 net.insert_arc(x,
y, 1.0, 0.0);
858 net.insert_arc(
y, z, 1.0, 0.0);
862 class NetDerivedChanged :
public ::testing::Test
872TYPED_TEST(NetDerivedChanged, ItKnowsThatItsNodesWentThroughTheBase)
876 using K = Kept_By<N>;
877 const char *
const ways[] = {
"a copy assignment",
"a move assignment",
"a swap()",
"a move construction",
878 "a swap() with another one that keeps the same"};
881 for (
const bool gone : {
false,
true})
882 for (
int way = 0; way < 5; ++way)
884 SCOPED_TRACE(std::string(ways[way]) + (gone ?
", and the other network gone" :
""));
888 auto plain = std::make_unique<B>();
890 auto other = std::make_unique<N>();
895 base = std::move(*plain);
899 *plain = B(std::move(base));
901 base.swap(
static_cast<B &
>(*other));
908 const bool used = K::use(net);
913 EXPECT_TRUE(sound(base));
918 const bool other_used = K::use(*other);
921 EXPECT_FALSE(other_used);
924 EXPECT_TRUE(sound(*plain));
925 EXPECT_TRUE(sound(
static_cast<B &
>(*other)));
932TYPED_TEST(NetDerivedChanged, ItUsesNothingThatIsGoneAfterAChangeThroughTheBase)
936 using K = Kept_By<N>;
937 const char *
const ways[] = {
"nothing",
"a swap() with itself",
"an assignment to itself",
"a move to itself",
938 "remove_node() of its first node",
"remove_arc() of its first arc",
939 "an arc disconnected and freed",
"clear_graph()",
"copy_graph() into it"};
940 for (
int way = 0; way < 9; ++way)
942 SCOPED_TRACE(ways[way]);
952 base =
static_cast<const B &
>(same);
954 base = std::move(same);
956 base.remove_node(base.get_first_node());
958 base.remove_arc(base.get_first_arc());
961 auto a = base.get_first_arc();
962 base.disconnect_arc(a);
970 const bool used = K::use(net);
975 EXPECT_TRUE(sound(base));
976 EXPECT_TRUE(sound(plain));
size_t size_t int32_t value
Generic directed graph (digraph) wrapper template.
Dynamic doubly linked list with O(1) size and bidirectional access.
Iterator on the items of list.
Doubly-linked list (defined in tpl_dynList.H).
T & get_first()
Return the first item of the list.
size_t size() const noexcept
Return the number of items of the list, in constant time.
Dynamic set backed by balanced binary search trees with automatic memory management.
const size_t & size() const
Returns the cardinality of the set.
bool contains(const Key &key) const
Checks if a key exists in 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.
bool has_curr() const noexcept
constexpr bool is_empty() const noexcept
Number Theoretic Transform over Z / MOD Z.
Capacitated network with node capacity constraints.
bool has_aux_net() const noexcept
Check if auxiliary network has been computed.
void free_aux_net()
Free the auxiliary network.
void update()
Update flow values from auxiliary network to this network.
Node * insert_node(Node *p) override
Aux_Net * compute_aux_net()
Compute the equivalent arc-capacitated auxiliary network.
Network graph with supply and demand nodes.
void non_feasible_nodes(DynDlist< Node * > &supply_list, DynDlist< Node * > &demand_list)
Get lists of nodes with unsatisfied supply/demand.
bool exist_aux_net() const noexcept
Check if the auxiliary network has been computed.
void free_aux_net()
Free the auxiliary network structures.
bool is_feasible() const
Check if the current flow is feasible.
Net_Sup_Dem_Graph * compute_aux_net()
Compute the auxiliary capacitated network.
Node * insert_node(const Node_Type &node_info, const Flow_Type &supply)
Insert a node with info and supply/demand value.
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
void copy_graph(GT >gt, const GT &gsrc, bool cookie_map=false)
Explicit copy of graph.
Main namespace for Aleph-w library functions.
Net::Flow_Type edmonds_karp_maximum_flow(Net &net)
Maximize flow using the Edmonds-Karp algorithm.
Net::Flow_Type random_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a random active-node queue.
Path< Net > find_aumenting_path_dfs(const Net &net, const typename Net::Flow_Type &min_slack)
Find an augmenting path using DFS.
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
Net::Flow_Type heap_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a height-ordered heap.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
void fill(Itor beg, const Itor &end, const T &value)
Fill a range with a value.
Net::Flow_Type increase_flow(Net &net, const Path< Net > &path)
Increase flow along an augmenting path.
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.
and
Check uniqueness with explicit hash + equality functors.
Net::Flow_Type fifo_preflow_maximum_flow(Net &net)
Preflow-push maximum flow using a FIFO queue of active nodes.
Net::Flow_Type ford_fulkerson_maximum_flow(Net &net)
Maximize flow using the Ford-Fulkerson algorithm.
void update_flow(const Rnet &rnet)
Propagate residual arc flows back to their original arcs.
Net_Sup_Dem_Graph< SimpleNode, SimpleArc > SimpleNet
Filtered iterator on all the arcs of a graph.
Arc of a flow network implemented with adjacency lists.
Capacitated flow network with costs associated to arcs.
Flow_Type flow_cost() const
Compute the total cost of flow circulating through the network.
virtual Arc * insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &__cost)
Create and insert an arc in a flow network with costs.
Arc filter for residual traversal in flow networks.
Flow network implemented with adjacency lists.
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 check_network() const
Validate flow-conservation and capacity constraints.
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
Arc * connect_arc(Arc *arc)
Connect a previously disconnected arc.
void remove_arc(Arc *arc) override
Remove arc arc from the network.
virtual void disconnect_arc(Arc *arc)
Disconnect arc arc from the graph without deleting it.
void make_super_source()
Convert a multi-source network into a single super-source network.
void make_super_sink()
Convert a multi-sink network into a single super-sink network.
size_t get_out_degree(Node *p) const noexcept
Return the out-degree of p (number of outgoing arcs).
bool is_source(Node *node) const noexcept
Return true if node is a source.
Node * get_source() const
Return an arbitrary source node.
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.
virtual void swapped() noexcept
What swap() calls on each of its two networks, once their nodes and arcs are exchanged: nothing,...
void unmake_super_sink()
Restore a super-sink network to its original multi-sink form, by removing the super sink that make_su...
Node * get_sink() const
Return an arbitrary sink node.
bool is_sink(Node *node) const noexcept
Return true if node is a sink.
Flow_Type flow_value() const
Return the total flow value of the network: the flow out of its sources, which a valid flow also take...
void unmake_super_source()
Restore a super-source network to its original multi-source form, by removing the super source that m...
size_t get_in_degree(Node *p) const noexcept
Return the in-degree of p (number of incoming arcs).
void swap(Net_Graph &other) noexcept
Swap contents with another network.
Filtered iterator of adjacent arcs of a node.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Dynamic doubly linked list implementation.
Advanced maximum flow algorithms.
Network flow graph structures.
Supply-demand network flow algorithms.
TYPED_TEST(NetDerivedChanged, ItKnowsThatItsNodesWentThroughTheBase)
TYPED_TEST_SUITE(NetDerivedChanged, Derived_Networks)
Network flow graph with capacities.
Maximum flow minimum cost network algorithms.