Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
net_apps.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
62#ifndef NET_APPS_H
63#define NET_APPS_H
64
65#include <array>
66#include <cmath>
67#include <limits>
68#include <type_traits>
69#include <vector>
70#include <string>
71#include <functional>
72#include <tpl_net.H>
73#include <tpl_maxflow.H>
74#include <tpl_netcost.H>
75#include <tpl_dynSetTree.H>
76#include <tpl_dynListQueue.H>
77
78namespace Aleph {
79
80//==============================================================================
81// CIRCULATION WITH DEMANDS
82//==============================================================================
83
87template <typename Flow_Type>
94
150template <class Net, class GetDemand, class GetLower, template <class> class Maxflow = Dinic_Maximum_Flow>
152 GetLower get_lower)
153{
154 using Node = typename Net::Node;
155 using Arc = typename Net::Arc;
156 using Flow_Type = typename Net::Flow_Type;
157
158 // Whether two totals are the same: exactly, or, for a floating flow,
159 // but for rounding
160 auto same = [](const Flow_Type &a, const Flow_Type &b)
161 {
162 if constexpr (std::is_floating_point_v<Flow_Type>)
163 return std::abs(a - b) <= std::max(std::abs(a), std::abs(b)) * 1e-9;
164 else
165 return a == b;
166 };
167
169
170 // The nodes of the network, before the super nodes, and its arcs, with
171 // their capacities and lower bounds; the flows start at the bounds
172 DynList<Node *> original_nodes;
173 for (Node_Iterator<Net> it(net); it.has_curr(); it.next_ne())
174 original_nodes.append(it.get_curr());
175
176 struct Arc_Bounds
177 {
178 Arc *arc;
179 Flow_Type cap;
180 Flow_Type lower;
181 };
182 DynList<Arc_Bounds> original_arcs;
183 bool bounded = true; // whether 0 <= l(e) <= u(e) on every arc
184 for (Arc_Iterator<Net> it(net); it.has_curr(); it.next_ne())
185 {
186 Arc *arc = it.get_curr();
187 const Flow_Type lb = get_lower(arc);
188 bounded = bounded and lb >= Flow_Type{0} and lb <= arc->cap;
189 original_arcs.append(Arc_Bounds{arc, arc->cap, lb});
190 result.flow[arc] = lb;
191 }
192
193 // An arc u -> v carries its lower bound l at least, which v receives
194 // and u sends: what is left is a flow f' = f - l, within u(e) - l, where
195 // in'(v) - out'(v) = d'(v) = d(v) - l_in(v) + l_out(v). For a floating
196 // flow, an adjusted demand within the rounding of the numbers that
197 // make it, the demand and the lower bounds of the arcs of v, is 0:
198 // lower bounds that balance but for rounding are a circulation. The
199 // capacities do not make d'(v), and a large one beside small bounds
200 // would take a real demand for a residue.
202 Flow_Type need{0}, give{0}; // what the nodes need, and what they give
203 for (Node *v : original_nodes)
204 {
205 Flow_Type d = get_demand(v);
206 [[maybe_unused]] Flow_Type scale = d < Flow_Type{0} ? -d : d;
207 [[maybe_unused]] size_t terms = 1;
208 for (typename Net::Node_Arc_Iterator ait(v); ait.has_curr(); ait.next_ne())
209 {
210 Arc *arc = ait.get_curr();
211 const Flow_Type lb = get_lower(arc);
212 if (net.get_tgt_node(arc) == v)
213 d -= lb;
214 if (net.get_src_node(arc) == v)
215 d += lb;
216 if constexpr (std::is_floating_point_v<Flow_Type>)
217 {
218 scale += lb < Flow_Type{0} ? -lb : lb;
219 ++terms;
220 }
221 }
222 if constexpr (std::is_floating_point_v<Flow_Type>)
223 if (std::abs(d) <= std::numeric_limits<Flow_Type>::epsilon() * Flow_Type(terms + 2) * scale)
224 d = Flow_Type{0};
225 adjusted[v] = d;
226 if (d > Flow_Type{0})
227 need += d;
228 else
229 give -= d;
230 }
231
232 // No flow fits bounds out of order, nor demands whose total is not 0;
233 // without demands left, the lower bounds are the circulation
234 if (not bounded or not same(need, give))
235 return result;
236 if (need == Flow_Type{0})
237 {
238 result.feasible = true;
239 return result;
240 }
241
242 // The network as it was, but for its flows, which are 0; the super
243 // nodes go, with their arcs, outside a destructor, as a removal
244 // allocates in a network
245 Node *super_source = nullptr;
246 Node *super_sink = nullptr;
247 auto restore = [&]
248 {
249 for (auto it = original_arcs.get_it(); it.has_curr(); it.next_ne())
250 {
251 const Arc_Bounds &b = it.get_curr();
252 b.arc->cap = b.cap;
253 b.arc->flow = Flow_Type{0};
254 }
255 if (super_sink != nullptr)
256 {
257 net.remove_node(super_sink);
258 super_sink = nullptr;
259 }
260 if (super_source != nullptr)
261 {
262 net.remove_node(super_source);
263 super_source = nullptr;
264 }
265 };
266
267 try
268 {
269 super_source = net.insert_node();
270 super_sink = net.insert_node();
271
272 // A node that needs flow gets it from the super-sink side, and one
273 // that gives it, from the super-source
274 for (Node *v : original_nodes)
275 if (const Flow_Type d = adjusted[v]; d > Flow_Type{0})
276 net.insert_arc(v, super_sink, d);
277 else if (d < Flow_Type{0})
278 net.insert_arc(super_source, v, -d);
279
280 // The other sources and sinks, through arcs of capacity 0, so that
281 // the network has one source and one sink
282 DynList<Node *> sources, sinks;
283 for (auto it = net.get_src_nodes().get_it(); it.has_curr(); it.next_ne())
284 if (it.get_curr() != super_source)
285 sources.append(it.get_curr());
286 for (auto it = net.get_sink_nodes().get_it(); it.has_curr(); it.next_ne())
287 if (it.get_curr() != super_sink)
288 sinks.append(it.get_curr());
289 for (Node *v : sources)
290 net.insert_arc(super_source, v, Flow_Type{0});
291 for (Node *v : sinks)
292 net.insert_arc(v, super_sink, Flow_Type{0});
293
294 for (auto it = original_arcs.get_it(); it.has_curr(); it.next_ne())
295 {
296 const Arc_Bounds &b = it.get_curr();
297 b.arc->cap = b.cap - b.lower;
298 b.arc->flow = Flow_Type{0};
299 }
300
301 const Flow_Type got = Maxflow<Net>()(net);
302 result.excess_flow = got;
303 result.feasible = same(got, need);
304 if (result.feasible)
305 for (auto it = original_arcs.get_it(); it.has_curr(); it.next_ne())
306 {
307 const Arc_Bounds &b = it.get_curr();
308 result.flow[b.arc] = b.arc->flow + b.lower;
309 }
310 }
311 catch (...)
312 {
313 // If the removal fails too, the super nodes stay, and the first
314 // exception goes on
315 try
316 {
317 restore();
318 }
319 catch (...)
320 {
321 // empty
322 }
323 throw;
324 }
325
326 restore();
327 return result;
328}
329
330//==============================================================================
331// PROJECT SELECTION (MAX PROFIT / CLOSURE)
332//==============================================================================
333
337template <typename Value_Type>
339{
340 size_t id;
341 Value_Type profit;
342 std::vector<size_t> prerequisites;
343 std::string name;
344
345 Project(size_t id_, Value_Type profit_, const std::vector<size_t> &prereqs = {},
346 const std::string &name_ = "")
347 : id(id_), profit(profit_), prerequisites(prereqs), name(name_)
348 {}
349};
350
354template <typename Value_Type>
356{
357 Value_Type max_profit{0};
358 std::vector<size_t> selected;
359 Value_Type total_revenue{0};
360 Value_Type total_cost{0};
361};
362
396template <typename Value_Type>
398{
400 using Node = typename Net::Node;
401
403
404 if (projects.empty())
405 return result;
406
407 Net net;
408 const Value_Type INF = std::numeric_limits<Value_Type>::max() / 2;
409
410 // Create source and sink
411 Node *source = net.insert_node();
412 Node *sink = net.insert_node();
413
414 // Create project nodes
415 std::vector<Node *> project_nodes(projects.size());
416 for (size_t i = 0; i < projects.size(); ++i)
417 project_nodes[i] = net.insert_node();
418
419 // Connect based on profits
420 Value_Type sum_positive{0};
421
422 for (size_t i = 0; i < projects.size(); ++i)
423 {
424 Value_Type p = projects[i].profit;
425
426 // Source to all projects (capacity = profit if positive, 0 otherwise)
427 // This ensures all project nodes are not sources
428 Value_Type source_cap = (p > 0) ? p : Value_Type{0};
429 net.insert_arc(source, project_nodes[i], source_cap);
430 if (p > 0)
431 sum_positive += p;
432
433 // All projects connect to sink (cost projects with capacity = -profit,
434 // others with capacity 0 to ensure proper network structure)
435 Value_Type sink_cap = (p < 0) ? -p : Value_Type{0};
436 net.insert_arc(project_nodes[i], sink, sink_cap);
437
438 // Add prerequisite edges (infinite capacity)
439 for (size_t prereq : projects[i].prerequisites)
440 if (prereq < projects.size())
441 net.insert_arc(project_nodes[i], project_nodes[prereq], INF);
442 }
443
444 // Solve min-cut (via max-flow)
445 Value_Type min_cut = dinic_maximum_flow(net);
446
447 result.max_profit = sum_positive - min_cut;
448
449 // Find selected projects (reachable from source in residual graph)
450 DynSetTree<Node *> reachable;
451
452 // BFS from source in residual graph
454 queue.put(source);
455 reachable.insert(source);
456
457 while (not queue.is_empty())
458 {
459 Node *u = queue.front();
460 queue.get();
461
462 for (typename Net::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
463 {
464 auto arc = it.get_curr();
465 auto v = net.get_connected_node(arc, u);
466
467 if (reachable.contains(v))
468 continue;
469
470 // Check residual capacity
471 Value_Type residual;
472 if (net.get_src_node(arc) == u)
473 residual = arc->cap - arc->flow;
474 else
475 residual = arc->flow;
476
477 if (residual > Value_Type{0})
478 {
479 reachable.insert(v);
480 queue.put(v);
481 }
482 }
483 }
484
485 // Projects reachable from source are selected
486 for (size_t i = 0; i < projects.size(); ++i)
487 if (reachable.contains(project_nodes[i]))
488 {
489 result.selected.push_back(i);
490 if (projects[i].profit > 0)
491 result.total_revenue += projects[i].profit;
492 else
493 result.total_cost += -projects[i].profit;
494 }
495
496 return result;
497}
498
499//==============================================================================
500// BASEBALL ELIMINATION
501//==============================================================================
502
506struct Team
507{
508 std::string name;
509 int wins;
512 std::vector<int> against;
513
514 Team(const std::string &n = "", int w = 0, int l = 0, int r = 0)
515 : name(n), wins(w), losses(l), remaining(r)
516 {}
517};
518
523{
524 bool eliminated{false};
525 std::vector<size_t> certificate;
527};
528
562inline BaseballEliminationResult check_baseball_elimination(const std::vector<Team> &teams,
563 size_t team_idx)
564{
566 using Node = Net::Node;
567
569
570 if (team_idx >= teams.size())
571 return result;
572
573 const Team &x = teams[team_idx];
574 result.max_possible_wins = x.wins + x.remaining;
575
576 // Trivial elimination check
577 for (size_t i = 0; i < teams.size(); ++i)
578 if (i != team_idx and teams[i].wins > result.max_possible_wins)
579 {
580 result.eliminated = true;
581 result.certificate.push_back(i);
582 return result;
583 }
584
585 Net net;
586
587 Node *source = net.insert_node();
588 Node *sink = net.insert_node();
589
590 // Create team nodes (excluding team x)
591 std::vector<Node *> team_nodes(teams.size(), nullptr);
592 for (size_t i = 0; i < teams.size(); ++i)
593 if (i != team_idx)
594 {
595 team_nodes[i] = net.insert_node();
596
597 // Team to sink: capacity = max wins x can have - current wins of
598 // i, which is 0 for a team without room: the arc stays, so that
599 // the team is not a sink
600 net.insert_arc(team_nodes[i], sink, result.max_possible_wins - teams[i].wins);
601 }
602
603 // Create game nodes
604 int total_games = 0;
605 for (size_t i = 0; i < teams.size(); ++i)
606 {
607 if (i == team_idx)
608 continue;
609
610 for (size_t j = i + 1; j < teams.size(); ++j)
611 {
612 if (j == team_idx)
613 continue;
614
615 int games = teams[i].against[j];
616 if (games > 0)
617 {
618 constexpr int INF = 1000000;
619 total_games += games;
620
621 Node *game_node = net.insert_node();
622 net.insert_arc(source, game_node, games);
623 net.insert_arc(game_node, team_nodes[i], INF);
624 net.insert_arc(game_node, team_nodes[j], INF);
625 }
626 }
627 }
628
629 // Without games among the others, x is not eliminated
630 if (total_games == 0)
631 return result;
632
633 // A team without games gets none from the source, by an arc of capacity
634 // 0, so that the network has one source: make_super_source() would feed
635 // it with the capacity of its arc to the sink
636 for (Node *p : team_nodes)
637 if (p != nullptr and net.get_in_degree(p) == 0)
638 net.insert_arc(source, p, 0);
639
640 const int max_flow = dinic_maximum_flow(net);
641
642 result.eliminated = (max_flow < total_games);
643
644 // If eliminated, find certificate (teams in source side of min-cut)
645 if (result.eliminated)
646 {
647 // BFS from source in residual graph
648 DynSetTree<Node *> reachable;
650 queue.put(source);
651 reachable.insert(source);
652
653 while (not queue.is_empty())
654 {
655 Node *u = queue.front();
656 queue.get();
657
658 for (Net::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
659 {
660 const auto arc = it.get_curr();
661 auto v = net.get_connected_node(arc, u);
662
663 if (reachable.contains(v))
664 continue;
665
666 if (const int residual =
667 (net.get_src_node(arc) == u) ? (arc->cap - arc->flow) : arc->flow;
668 residual > 0)
669 {
670 reachable.insert(v);
671 queue.put(v);
672 }
673 }
674 }
675
676 for (size_t i = 0; i < teams.size(); ++i)
677 if (i != team_idx and team_nodes[i] != nullptr and reachable.contains(team_nodes[i]))
678 result.certificate.push_back(i);
679 }
680
681 return result;
682}
683
684//==============================================================================
685// IMAGE SEGMENTATION (BINARY LABELING)
686//==============================================================================
687
692{
693 std::vector<std::vector<int>> labels;
694 double energy{0};
695};
696
734template <typename Value_Type>
736 const std::vector<std::vector<std::array<Value_Type, 2>>> &data_cost,
737 Value_Type smoothness)
738{
740 using Node = typename Net::Node;
741
742 SegmentationResult result;
743 result.labels.resize(rows, std::vector<int>(cols, 0));
744
745 if (rows == 0 or cols == 0)
746 return result;
747
748 Net net;
749
750 // Create source (label 0) and sink (label 1)
751 Node *source = net.insert_node();
752 Node *sink = net.insert_node();
753
754 // Create pixel nodes
755 std::vector<std::vector<Node *>> pixels(rows, std::vector<Node *>(cols));
756 for (size_t i = 0; i < rows; ++i)
757 for (size_t j = 0; j < cols; ++j)
758 pixels[i][j] = net.insert_node();
759
760 // Add data term edges (standard graph cut model for binary labeling)
761 // See: Boykov, Kolmogorov "An Experimental Comparison of Min-Cut/Max-Flow Algorithms"
762 for (size_t i = 0; i < rows; ++i)
763 for (size_t j = 0; j < cols; ++j)
764 {
765 // Source to pixel: capacity = cost of background (label 0)
766 // If this arc is cut, pixel goes to sink side = background
767 net.insert_arc(source, pixels[i][j], data_cost[i][j][0]);
768
769 // Pixel to sink: capacity = cost of foreground (label 1)
770 // If this arc is cut, pixel stays on source side = foreground
771 net.insert_arc(pixels[i][j], sink, data_cost[i][j][1]);
772 }
773
774 // Add smoothness term edges (4-connected)
775 for (size_t i = 0; i < rows; ++i)
776 for (size_t j = 0; j < cols; ++j)
777 {
778 // Right neighbor
779 if (j + 1 < cols)
780 {
781 net.insert_arc(pixels[i][j], pixels[i][j + 1], smoothness);
782 net.insert_arc(pixels[i][j + 1], pixels[i][j], smoothness);
783 }
784
785 // Bottom neighbor
786 if (i + 1 < rows)
787 {
788 net.insert_arc(pixels[i][j], pixels[i + 1][j], smoothness);
789 net.insert_arc(pixels[i + 1][j], pixels[i][j], smoothness);
790 }
791 }
792
793 // Ensure network has single source and sink
794 net.make_super_source();
795 net.make_super_sink();
796
797 // Compute min-cut
798 Value_Type min_cut = dinic_maximum_flow(net);
799 result.energy = static_cast<double>(min_cut);
800
801 // Extract labels (BFS from source in residual graph)
802 DynSetTree<Node *> foreground; // Reachable = foreground (label 1)
803
805 queue.put(source);
806 foreground.insert(source);
807
808 while (not queue.is_empty())
809 {
810 Node *u = queue.front();
811 queue.get();
812
813 for (typename Net::Node_Arc_Iterator it(u); it.has_curr(); it.next_ne())
814 {
815 auto arc = it.get_curr();
816 auto v = net.get_connected_node(arc, u);
817
818 if (foreground.contains(v))
819 continue;
820
821 Value_Type residual = (net.get_src_node(arc) == u) ? (arc->cap - arc->flow) : arc->flow;
822
823 if (residual > Value_Type{0})
824 {
825 foreground.insert(v);
826 queue.put(v);
827 }
828 }
829 }
830
831 // Set labels
832 for (size_t i = 0; i < rows; ++i)
833 for (size_t j = 0; j < cols; ++j)
834 result.labels[i][j] = foreground.contains(pixels[i][j]) ? 1 : 0;
835
836 return result;
837}
838
839//==============================================================================
840// SURVEY DESIGN
841//==============================================================================
842
847{
848 size_t id;
851};
852
857{
858 size_t id;
861 std::vector<size_t> eligible_questions;
862};
863
868{
869 bool feasible{false};
870 std::vector<std::pair<size_t, size_t>> assignments;
871};
872
890inline SurveyDesignResult design_survey(const std::vector<SurveyQuestion> &questions,
891 const std::vector<SurveyRespondent> &respondents)
892{
894 using Node = Net::Node;
895 using Arc = Net::Arc;
896
897 SurveyDesignResult result;
898
899 if (questions.empty() or respondents.empty())
900 return result;
901
902 // The bounds must be in order
903 for (const auto &q : questions)
904 if (q.min_responses < 0 or q.min_responses > q.max_responses)
905 return result;
906 for (const auto &r : respondents)
907 if (r.min_questions < 0 or r.min_questions > r.max_questions)
908 return result;
909
910 // A circulation, with the minimums as lower bounds: from the source to
911 // each respondent, to the questions it may answer, to the sink, and
912 // back to the source
913 Net net;
915
916 Node *source = net.insert_node();
917 Node *sink = net.insert_node();
918
919 std::vector<Node *> question_nodes(questions.size());
920 for (size_t i = 0; i < questions.size(); ++i)
921 {
922 question_nodes[i] = net.insert_node();
923 Arc *a = net.insert_arc(question_nodes[i], sink, questions[i].max_responses);
924 lower.insert(a, questions[i].min_responses);
925 }
926
927 int most = 0; // the most answers there may be
928 std::vector<std::vector<std::pair<size_t, Arc *>>> answers(respondents.size());
929 for (size_t i = 0; i < respondents.size(); ++i)
930 {
931 Node *r = net.insert_node();
932 Arc *a = net.insert_arc(source, r, respondents[i].max_questions);
933 lower.insert(a, respondents[i].min_questions);
934 most += respondents[i].max_questions;
935
936 for (size_t q : respondents[i].eligible_questions)
937 if (q < questions.size())
938 answers[i].push_back({q, net.insert_arc(r, question_nodes[q], 1)});
939 }
940
941 net.insert_arc(sink, source, most);
942
943 auto circulation = solve_circulation(net,
944 [](Node *) { return 0; },
945 [&lower](Arc *a)
946 {
947 auto p = lower.search(a);
948 return p == nullptr ? 0 : p->second;
949 });
950
951 result.feasible = circulation.feasible;
952 if (result.feasible)
953 for (size_t r = 0; r < respondents.size(); ++r)
954 for (const auto &[q, a] : answers[r])
955 if (circulation.flow.find(a) > 0)
956 result.assignments.push_back({r, q});
957
958 return result;
959}
960
961} // namespace Aleph
962
963#endif // NET_APPS_H
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double w
Definition btreepic.C:153
size_t * rows
Definition ca-c-api.h:112
size_t cols
Definition ca-c-api.h:105
Iterator over the arcs of a node.
Definition tpl_agraph.H:354
bool has_curr() const noexcept
Return true if the iterator is on an arc.
Definition tpl_agraph.H:387
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
T & front()
Return a modifiable reference to the oldest item in the queue.
bool is_empty() const noexcept
Return true if this is empty.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Generic key-value map implemented on top of a binary search tree.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Dynamic set backed by balanced binary search trees with automatic memory management.
Key * insert(const Key &key)
Inserts a key into the dynamic 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.
Filtered iterator on the nodes of a graph.
Definition tpl_graph.H:1287
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_connected_node(Arc *arc, Node *node) const noexcept
Return the adjacent node to node through arc.
Definition graph-dry.H:1058
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
double Flow_Type
Main namespace for Aleph-w library functions.
BaseballEliminationResult check_baseball_elimination(const std::vector< Team > &teams, size_t team_idx)
Check if a team is mathematically eliminated from winning.
Definition net_apps.H:562
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
and
Check uniqueness with explicit hash + equality functors.
ProjectSelectionResult< Value_Type > solve_project_selection(const std::vector< Project< Value_Type > > &projects)
Solve project selection problem using max-flow.
Definition net_apps.H:397
SegmentationResult segment_image(size_t rows, size_t cols, const std::vector< std::vector< std::array< Value_Type, 2 > > > &data_cost, Value_Type smoothness)
Segment image using graph cuts.
Definition net_apps.H:735
SurveyDesignResult design_survey(const std::vector< SurveyQuestion > &questions, const std::vector< SurveyRespondent > &respondents)
Design survey assignment using network flow.
Definition net_apps.H:890
CirculationResult< typename Net::Flow_Type > solve_circulation(Net &net, GetDemand get_demand, GetLower get_lower)
Solve a circulation problem with demands.
Definition net_apps.H:151
Net::Flow_Type min_cut(Net &net, DynSetTree< typename Net::Node * > &vs, DynSetTree< typename Net::Node * > &vt, DynList< typename Net::Arc * > &cuts, DynList< typename Net::Arc * > &cutt)
Compute max flow and the corresponding minimum cut.
Definition tpl_net.H:2790
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Result of baseball elimination check.
Definition net_apps.H:523
std::vector< size_t > certificate
Teams that form elimination certificate.
Definition net_apps.H:525
int max_possible_wins
Maximum wins team can achieve.
Definition net_apps.H:526
bool eliminated
Is the team mathematically eliminated?
Definition net_apps.H:524
Result of a circulation problem.
Definition net_apps.H:89
bool feasible
Is there a feasible circulation?
Definition net_apps.H:90
Flow_Type excess_flow
Flow needed to satisfy demands.
Definition net_apps.H:91
DynMapTree< void *, Flow_Type > flow
Flow on each edge (arc pointer -> flow)
Definition net_apps.H:92
Functor wrapper for Dinic's algorithm.
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
Node * insert_node(const Node_Type &node_info)
Insert a new node by copying node_info.
Definition tpl_net.H:750
const DynSetTree< Node * > & get_sink_nodes() const noexcept
Return the set of sink nodes.
Definition tpl_net.H:595
const DynSetTree< Node * > & get_src_nodes() const noexcept
Return the set of source nodes.
Definition tpl_net.H:589
void make_super_source()
Convert a multi-source network into a single super-source network.
Definition tpl_net.H:603
void make_super_sink()
Convert a multi-sink network into a single super-sink network.
Definition tpl_net.H:656
Arc * insert_arc(Node *src_node, Node *tgt_node, const Flow_Type &cap, const Flow_Type &flow, const typename Arc::Arc_Type &arc_info=Arc_Type())
Insert a capacitated arc with an initial flow.
Definition tpl_net.H:799
void remove_node(Node *p) override
Remove node p and all its arcs from the network.
Definition tpl_net.H:933
ArcT Arc
Arc type.
Definition tpl_net.H:322
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Definition tpl_net.H:328
NodeT Node
Node type.
Definition tpl_net.H:325
size_t get_in_degree(Node *p) const noexcept
Return the in-degree of p (number of incoming arcs).
Definition tpl_net.H:387
Result of project selection.
Definition net_apps.H:356
Value_Type max_profit
Maximum achievable profit.
Definition net_apps.H:357
std::vector< size_t > selected
IDs of selected projects.
Definition net_apps.H:358
Value_Type total_cost
Sum of negative profits (costs)
Definition net_apps.H:360
Value_Type total_revenue
Sum of positive profits.
Definition net_apps.H:359
Project with profit and dependencies.
Definition net_apps.H:339
Value_Type profit
Profit (positive) or cost (negative)
Definition net_apps.H:341
size_t id
Unique project ID.
Definition net_apps.H:340
std::string name
Optional name.
Definition net_apps.H:343
std::vector< size_t > prerequisites
IDs of prerequisite projects.
Definition net_apps.H:342
Project(size_t id_, Value_Type profit_, const std::vector< size_t > &prereqs={}, const std::string &name_="")
Definition net_apps.H:345
Result of binary image segmentation.
Definition net_apps.H:692
std::vector< std::vector< int > > labels
0 or 1 for each pixel
Definition net_apps.H:693
double energy
Total energy of segmentation.
Definition net_apps.H:694
Result of survey design.
Definition net_apps.H:868
std::vector< std::pair< size_t, size_t > > assignments
(respondent, question)
Definition net_apps.H:870
Survey question with constraints.
Definition net_apps.H:847
int max_responses
Maximum responses accepted.
Definition net_apps.H:850
int min_responses
Minimum number of responses needed.
Definition net_apps.H:849
Survey respondent with constraints.
Definition net_apps.H:857
std::vector< size_t > eligible_questions
Questions this respondent can answer.
Definition net_apps.H:861
int min_questions
Minimum questions to answer.
Definition net_apps.H:859
int max_questions
Maximum questions can answer.
Definition net_apps.H:860
Team information for baseball elimination.
Definition net_apps.H:507
std::vector< int > against
Games remaining against each team.
Definition net_apps.H:512
Team(const std::string &n="", int w=0, int l=0, int r=0)
Definition net_apps.H:514
std::string name
Definition net_apps.H:508
int remaining
Games remaining.
Definition net_apps.H:511
Gsl_Compatible_Rng r
Dynamic queue implementation based on linked lists.
Dynamic set implementations based on balanced binary search trees.
Advanced maximum flow algorithms.
Network flow graph structures.
Maximum flow minimum cost network algorithms.
DynList< int > l