3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_NETWORK_SIMPLEX_H
20 #define LEMON_NETWORK_SIMPLEX_H
22 /// \ingroup min_cost_flow
25 /// \brief Network simplex algorithm for finding a minimum cost flow.
30 #include <lemon/graph_adaptor.h>
31 #include <lemon/graph_utils.h>
32 #include <lemon/smart_graph.h>
33 #include <lemon/math.h>
39 /// \addtogroup min_cost_flow
42 /// \brief Implementation of the primal network simplex algorithm
43 /// for finding a minimum cost flow.
45 /// \ref NetworkSimplex implements the primal network simplex algorithm
46 /// for finding a minimum cost flow.
48 /// \tparam Graph The directed graph type the algorithm runs on.
49 /// \tparam LowerMap The type of the lower bound map.
50 /// \tparam CapacityMap The type of the capacity (upper bound) map.
51 /// \tparam CostMap The type of the cost (length) map.
52 /// \tparam SupplyMap The type of the supply map.
55 /// - Edge capacities and costs should be \e non-negative \e integers.
56 /// - Supply values should be \e signed \e integers.
57 /// - The value types of the maps should be convertible to each other.
58 /// - \c CostMap::Value must be signed type.
60 /// \note \ref NetworkSimplex provides five different pivot rule
61 /// implementations that significantly affect the efficiency of the
63 /// By default "Block Search" pivot rule is used, which proved to be
64 /// by far the most efficient according to our benchmark tests.
65 /// However another pivot rule can be selected using \ref run()
66 /// function with the proper parameter.
68 /// \author Peter Kovacs
69 template < typename Graph,
70 typename LowerMap = typename Graph::template EdgeMap<int>,
71 typename CapacityMap = typename Graph::template EdgeMap<int>,
72 typename CostMap = typename Graph::template EdgeMap<int>,
73 typename SupplyMap = typename Graph::template NodeMap<int> >
76 typedef typename CapacityMap::Value Capacity;
77 typedef typename CostMap::Value Cost;
78 typedef typename SupplyMap::Value Supply;
80 typedef SmartGraph SGraph;
81 GRAPH_TYPEDEFS(typename SGraph);
83 typedef typename SGraph::template EdgeMap<Capacity> SCapacityMap;
84 typedef typename SGraph::template EdgeMap<Cost> SCostMap;
85 typedef typename SGraph::template NodeMap<Supply> SSupplyMap;
86 typedef typename SGraph::template NodeMap<Cost> SPotentialMap;
88 typedef typename SGraph::template NodeMap<int> IntNodeMap;
89 typedef typename SGraph::template NodeMap<bool> BoolNodeMap;
90 typedef typename SGraph::template NodeMap<Node> NodeNodeMap;
91 typedef typename SGraph::template NodeMap<Edge> EdgeNodeMap;
92 typedef typename SGraph::template EdgeMap<int> IntEdgeMap;
93 typedef typename SGraph::template EdgeMap<bool> BoolEdgeMap;
95 typedef typename Graph::template NodeMap<Node> NodeRefMap;
96 typedef typename Graph::template EdgeMap<Edge> EdgeRefMap;
98 typedef std::vector<Edge> EdgeVector;
102 /// The type of the flow map.
103 typedef typename Graph::template EdgeMap<Capacity> FlowMap;
104 /// The type of the potential map.
105 typedef typename Graph::template NodeMap<Cost> PotentialMap;
109 /// Enum type to select the pivot rule used by \ref run().
111 FIRST_ELIGIBLE_PIVOT,
114 CANDIDATE_LIST_PIVOT,
120 /// \brief Map adaptor class for handling reduced edge costs.
122 /// Map adaptor class for handling reduced edge costs.
123 class ReducedCostMap : public MapBase<Edge, Cost>
128 const SCostMap &_cost_map;
129 const SPotentialMap &_pot_map;
134 ReducedCostMap( const SGraph &gr,
135 const SCostMap &cost_map,
136 const SPotentialMap &pot_map ) :
137 _gr(gr), _cost_map(cost_map), _pot_map(pot_map) {}
140 Cost operator[](const Edge &e) const {
141 return _cost_map[e] + _pot_map[_gr.source(e)]
142 - _pot_map[_gr.target(e)];
145 }; //class ReducedCostMap
149 /// \brief Implementation of the "First Eligible" pivot rule for the
150 /// \ref NetworkSimplex "network simplex" algorithm.
152 /// This class implements the "First Eligible" pivot rule
153 /// for the \ref NetworkSimplex "network simplex" algorithm.
155 /// For more information see \ref NetworkSimplex::run().
156 class FirstEligiblePivotRule
160 // References to the NetworkSimplex class
169 FirstEligiblePivotRule(NetworkSimplex &ns, EdgeVector &edges) :
170 _ns(ns), _edges(edges), _next_edge(0) {}
172 /// Find next entering edge
173 inline bool findEnteringEdge() {
175 for (int i = _next_edge; i < int(_edges.size()); ++i) {
177 if (_ns._state[e] * _ns._red_cost[e] < 0) {
183 for (int i = 0; i < _next_edge; ++i) {
185 if (_ns._state[e] * _ns._red_cost[e] < 0) {
193 }; //class FirstEligiblePivotRule
195 /// \brief Implementation of the "Best Eligible" pivot rule for the
196 /// \ref NetworkSimplex "network simplex" algorithm.
198 /// This class implements the "Best Eligible" pivot rule
199 /// for the \ref NetworkSimplex "network simplex" algorithm.
201 /// For more information see \ref NetworkSimplex::run().
202 class BestEligiblePivotRule
206 // References to the NetworkSimplex class
213 BestEligiblePivotRule(NetworkSimplex &ns, EdgeVector &edges) :
214 _ns(ns), _edges(edges) {}
216 /// Find next entering edge
217 inline bool findEnteringEdge() {
220 for (int i = 0; i < int(_edges.size()); ++i) {
222 if (_ns._state[e] * _ns._red_cost[e] < min) {
223 min = _ns._state[e] * _ns._red_cost[e];
229 }; //class BestEligiblePivotRule
231 /// \brief Implementation of the "Block Search" pivot rule for the
232 /// \ref NetworkSimplex "network simplex" algorithm.
234 /// This class implements the "Block Search" pivot rule
235 /// for the \ref NetworkSimplex "network simplex" algorithm.
237 /// For more information see \ref NetworkSimplex::run().
238 class BlockSearchPivotRule
242 // References to the NetworkSimplex class
247 int _next_edge, _min_edge;
252 BlockSearchPivotRule(NetworkSimplex &ns, EdgeVector &edges) :
253 _ns(ns), _edges(edges), _next_edge(0), _min_edge(0)
255 // The main parameters of the pivot rule
256 const double BLOCK_SIZE_FACTOR = 2.0;
257 const int MIN_BLOCK_SIZE = 10;
259 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_edges.size())),
263 /// Find next entering edge
264 inline bool findEnteringEdge() {
267 int cnt = _block_size;
269 for (i = _next_edge; i < int(_edges.size()); ++i) {
271 if ((curr = _ns._state[e] * _ns._red_cost[e]) < min) {
280 if (min == 0 || cnt > 0) {
281 for (i = 0; i < _next_edge; ++i) {
283 if ((curr = _ns._state[e] * _ns._red_cost[e]) < min) {
293 if (min >= 0) return false;
294 _ns._in_edge = _edges[_min_edge];
298 }; //class BlockSearchPivotRule
300 /// \brief Implementation of the "Candidate List" pivot rule for the
301 /// \ref NetworkSimplex "network simplex" algorithm.
303 /// This class implements the "Candidate List" pivot rule
304 /// for the \ref NetworkSimplex "network simplex" algorithm.
306 /// For more information see \ref NetworkSimplex::run().
307 class CandidateListPivotRule
311 // References to the NetworkSimplex class
315 EdgeVector _candidates;
316 int _list_length, _minor_limit;
317 int _curr_length, _minor_count;
318 int _next_edge, _min_edge;
323 CandidateListPivotRule(NetworkSimplex &ns, EdgeVector &edges) :
324 _ns(ns), _edges(edges), _next_edge(0), _min_edge(0)
326 // The main parameters of the pivot rule
327 const double LIST_LENGTH_FACTOR = 1.0;
328 const int MIN_LIST_LENGTH = 10;
329 const double MINOR_LIMIT_FACTOR = 0.1;
330 const int MIN_MINOR_LIMIT = 3;
332 _list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_edges.size())),
334 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
336 _curr_length = _minor_count = 0;
337 _candidates.resize(_list_length);
340 /// Find next entering edge
341 inline bool findEnteringEdge() {
343 if (_curr_length > 0 && _minor_count < _minor_limit) {
344 // Minor iteration: selecting the best eligible edge from
345 // the current candidate list
349 for (int i = 0; i < _curr_length; ++i) {
351 curr = _ns._state[e] * _ns._red_cost[e];
357 _candidates[i--] = _candidates[--_curr_length];
360 if (min < 0) return true;
363 // Major iteration: building a new candidate list
368 for (i = _next_edge; i < int(_edges.size()); ++i) {
370 if ((curr = _ns._state[e] * _ns._red_cost[e]) < 0) {
371 _candidates[_curr_length++] = e;
376 if (_curr_length == _list_length) break;
379 if (_curr_length < _list_length) {
380 for (i = 0; i < _next_edge; ++i) {
382 if ((curr = _ns._state[e] * _ns._red_cost[e]) < 0) {
383 _candidates[_curr_length++] = e;
388 if (_curr_length == _list_length) break;
392 if (_curr_length == 0) return false;
394 _ns._in_edge = _edges[_min_edge];
398 }; //class CandidateListPivotRule
400 /// \brief Implementation of the "Altering Candidate List" pivot rule
401 /// for the \ref NetworkSimplex "network simplex" algorithm.
403 /// This class implements the "Altering Candidate List" pivot rule
404 /// for the \ref NetworkSimplex "network simplex" algorithm.
406 /// For more information see \ref NetworkSimplex::run().
407 class AlteringListPivotRule
411 // References to the NetworkSimplex class
415 EdgeVector _candidates;
417 int _block_size, _head_length, _curr_length;
420 // Functor class to compare edges during sort of the candidate list
424 const SCostMap &_map;
426 SortFunc(const SCostMap &map) : _map(map) {}
427 bool operator()(const Edge &e1, const Edge &e2) {
428 return _map[e1] < _map[e2];
437 AlteringListPivotRule(NetworkSimplex &ns, EdgeVector &edges) :
438 _ns(ns), _edges(edges), _cand_cost(_ns._graph),
439 _next_edge(0), _sort_func(_cand_cost)
441 // The main parameters of the pivot rule
442 const double BLOCK_SIZE_FACTOR = 1.0;
443 const int MIN_BLOCK_SIZE = 10;
444 const double HEAD_LENGTH_FACTOR = 0.1;
445 const int MIN_HEAD_LENGTH = 5;
447 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_edges.size())),
449 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
451 _candidates.resize(_head_length + _block_size);
455 /// Find next entering edge
456 inline bool findEnteringEdge() {
457 // Checking the current candidate list
459 for (int idx = 0; idx < _curr_length; ++idx) {
460 e = _candidates[idx];
461 if ((_cand_cost[e] = _ns._state[e] * _ns._red_cost[e]) >= 0) {
462 _candidates[idx--] = _candidates[--_curr_length];
466 // Extending the list
467 int cnt = _block_size;
469 int limit = _head_length;
470 for (int i = _next_edge; i < int(_edges.size()); ++i) {
472 if ((_cand_cost[e] = _ns._state[e] * _ns._red_cost[e]) < 0) {
473 _candidates[_curr_length++] = e;
477 if (_curr_length > limit) break;
482 if (_curr_length <= limit) {
483 for (int i = 0; i < _next_edge; ++i) {
485 if ((_cand_cost[e] = _ns._state[e] * _ns._red_cost[e]) < 0) {
486 _candidates[_curr_length++] = e;
490 if (_curr_length > limit) break;
496 if (_curr_length == 0) return false;
497 _next_edge = last_edge + 1;
499 // Sorting the list partially
500 EdgeVector::iterator sort_end = _candidates.begin();
501 EdgeVector::iterator vector_end = _candidates.begin();
502 for (int idx = 0; idx < _curr_length; ++idx) {
504 if (idx <= _head_length) ++sort_end;
506 partial_sort(_candidates.begin(), sort_end, vector_end, _sort_func);
508 _ns._in_edge = _candidates[0];
509 if (_curr_length > _head_length) {
510 _candidates[0] = _candidates[_head_length - 1];
511 _curr_length = _head_length - 1;
513 _candidates[0] = _candidates[_curr_length - 1];
519 }; //class AlteringListPivotRule
523 // State constants for edges
532 // The directed graph the algorithm runs on
534 // The original graph
535 const Graph &_graph_ref;
536 // The original lower bound map
537 const LowerMap *_lower;
539 SCapacityMap _capacity;
546 // Edge map of the current flow
548 // Node map of the current potentials
549 SPotentialMap _potential;
551 // The depth node map of the spanning tree structure
553 // The parent node map of the spanning tree structure
555 // The pred_edge node map of the spanning tree structure
556 EdgeNodeMap _pred_edge;
557 // The thread node map of the spanning tree structure
559 // The forward node map of the spanning tree structure
560 BoolNodeMap _forward;
561 // The state edge map
563 // The root node of the starting spanning tree
566 // The reduced cost map
567 ReducedCostMap _red_cost;
569 // The non-artifical edges
572 // Members for handling the original graph
573 FlowMap *_flow_result;
574 PotentialMap *_potential_result;
576 bool _local_potential;
577 NodeRefMap _node_ref;
578 EdgeRefMap _edge_ref;
580 // The entering edge of the current pivot iteration.
583 // Temporary nodes used in the current pivot iteration.
584 Node join, u_in, v_in, u_out, v_out;
585 Node right, first, second, last;
586 Node stem, par_stem, new_stem;
587 // The maximum augment amount along the found cycle in the current
593 /// \brief General constructor (with lower bounds).
595 /// General constructor (with lower bounds).
597 /// \param graph The directed graph the algorithm runs on.
598 /// \param lower The lower bounds of the edges.
599 /// \param capacity The capacities (upper bounds) of the edges.
600 /// \param cost The cost (length) values of the edges.
601 /// \param supply The supply values of the nodes (signed).
602 NetworkSimplex( const Graph &graph,
603 const LowerMap &lower,
604 const CapacityMap &capacity,
606 const SupplyMap &supply ) :
607 _graph(), _graph_ref(graph), _lower(&lower), _capacity(_graph),
608 _cost(_graph), _supply(_graph), _flow(_graph),
609 _potential(_graph), _depth(_graph), _parent(_graph),
610 _pred_edge(_graph), _thread(_graph), _forward(_graph),
611 _state(_graph), _red_cost(_graph, _cost, _potential),
612 _flow_result(0), _potential_result(0),
613 _local_flow(false), _local_potential(false),
614 _node_ref(graph), _edge_ref(graph)
616 // Checking the sum of supply values
618 for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n)
620 if (!(_valid_supply = sum == 0)) return;
622 // Copying _graph_ref to _graph
623 _graph.reserveNode(countNodes(_graph_ref) + 1);
624 _graph.reserveEdge(countEdges(_graph_ref) + countNodes(_graph_ref));
625 copyGraph(_graph, _graph_ref)
626 .edgeMap(_cost, cost)
631 // Removing non-zero lower bounds
632 for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) {
633 _capacity[_edge_ref[e]] = capacity[e] - lower[e];
635 for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) {
636 Supply s = supply[n];
637 for (typename Graph::InEdgeIt e(_graph_ref, n); e != INVALID; ++e)
639 for (typename Graph::OutEdgeIt e(_graph_ref, n); e != INVALID; ++e)
641 _supply[_node_ref[n]] = s;
645 /// \brief General constructor (without lower bounds).
647 /// General constructor (without lower bounds).
649 /// \param graph The directed graph the algorithm runs on.
650 /// \param capacity The capacities (upper bounds) of the edges.
651 /// \param cost The cost (length) values of the edges.
652 /// \param supply The supply values of the nodes (signed).
653 NetworkSimplex( const Graph &graph,
654 const CapacityMap &capacity,
656 const SupplyMap &supply ) :
657 _graph(), _graph_ref(graph), _lower(NULL), _capacity(_graph),
658 _cost(_graph), _supply(_graph), _flow(_graph),
659 _potential(_graph), _depth(_graph), _parent(_graph),
660 _pred_edge(_graph), _thread(_graph), _forward(_graph),
661 _state(_graph), _red_cost(_graph, _cost, _potential),
662 _flow_result(0), _potential_result(0),
663 _local_flow(false), _local_potential(false),
664 _node_ref(graph), _edge_ref(graph)
666 // Checking the sum of supply values
668 for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n)
670 if (!(_valid_supply = sum == 0)) return;
672 // Copying _graph_ref to graph
673 copyGraph(_graph, _graph_ref)
674 .edgeMap(_capacity, capacity)
675 .edgeMap(_cost, cost)
676 .nodeMap(_supply, supply)
682 /// \brief Simple constructor (with lower bounds).
684 /// Simple constructor (with lower bounds).
686 /// \param graph The directed graph the algorithm runs on.
687 /// \param lower The lower bounds of the edges.
688 /// \param capacity The capacities (upper bounds) of the edges.
689 /// \param cost The cost (length) values of the edges.
690 /// \param s The source node.
691 /// \param t The target node.
692 /// \param flow_value The required amount of flow from node \c s
693 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
694 NetworkSimplex( const Graph &graph,
695 const LowerMap &lower,
696 const CapacityMap &capacity,
698 typename Graph::Node s,
699 typename Graph::Node t,
700 typename SupplyMap::Value flow_value ) :
701 _graph(), _graph_ref(graph), _lower(&lower), _capacity(_graph),
702 _cost(_graph), _supply(_graph), _flow(_graph),
703 _potential(_graph), _depth(_graph), _parent(_graph),
704 _pred_edge(_graph), _thread(_graph), _forward(_graph),
705 _state(_graph), _red_cost(_graph, _cost, _potential),
706 _flow_result(0), _potential_result(0),
707 _local_flow(false), _local_potential(false),
708 _node_ref(graph), _edge_ref(graph)
710 // Copying _graph_ref to graph
711 copyGraph(_graph, _graph_ref)
712 .edgeMap(_cost, cost)
717 // Removing non-zero lower bounds
718 for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) {
719 _capacity[_edge_ref[e]] = capacity[e] - lower[e];
721 for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) {
723 if (n == s) sum = flow_value;
724 if (n == t) sum = -flow_value;
725 for (typename Graph::InEdgeIt e(_graph_ref, n); e != INVALID; ++e)
727 for (typename Graph::OutEdgeIt e(_graph_ref, n); e != INVALID; ++e)
729 _supply[_node_ref[n]] = sum;
731 _valid_supply = true;
734 /// \brief Simple constructor (without lower bounds).
736 /// Simple constructor (without lower bounds).
738 /// \param graph The directed graph the algorithm runs on.
739 /// \param capacity The capacities (upper bounds) of the edges.
740 /// \param cost The cost (length) values of the edges.
741 /// \param s The source node.
742 /// \param t The target node.
743 /// \param flow_value The required amount of flow from node \c s
744 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
745 NetworkSimplex( const Graph &graph,
746 const CapacityMap &capacity,
748 typename Graph::Node s,
749 typename Graph::Node t,
750 typename SupplyMap::Value flow_value ) :
751 _graph(), _graph_ref(graph), _lower(NULL), _capacity(_graph),
752 _cost(_graph), _supply(_graph, 0), _flow(_graph),
753 _potential(_graph), _depth(_graph), _parent(_graph),
754 _pred_edge(_graph), _thread(_graph), _forward(_graph),
755 _state(_graph), _red_cost(_graph, _cost, _potential),
756 _flow_result(0), _potential_result(0),
757 _local_flow(false), _local_potential(false),
758 _node_ref(graph), _edge_ref(graph)
760 // Copying _graph_ref to graph
761 copyGraph(_graph, _graph_ref)
762 .edgeMap(_capacity, capacity)
763 .edgeMap(_cost, cost)
767 _supply[_node_ref[s]] = flow_value;
768 _supply[_node_ref[t]] = -flow_value;
769 _valid_supply = true;
774 if (_local_flow) delete _flow_result;
775 if (_local_potential) delete _potential_result;
778 /// \brief Set the flow map.
780 /// Set the flow map.
782 /// \return \c (*this)
783 NetworkSimplex& flowMap(FlowMap &map) {
792 /// \brief Set the potential map.
794 /// Set the potential map.
796 /// \return \c (*this)
797 NetworkSimplex& potentialMap(PotentialMap &map) {
798 if (_local_potential) {
799 delete _potential_result;
800 _local_potential = false;
802 _potential_result = ↦
806 /// \name Execution control
810 /// \brief Runs the algorithm.
812 /// Runs the algorithm.
814 /// \param pivot_rule The pivot rule that is used during the
817 /// The available pivot rules:
819 /// - FIRST_ELIGIBLE_PIVOT The next eligible edge is selected in
820 /// a wraparound fashion in every iteration
821 /// (\ref FirstEligiblePivotRule).
823 /// - BEST_ELIGIBLE_PIVOT The best eligible edge is selected in
824 /// every iteration (\ref BestEligiblePivotRule).
826 /// - BLOCK_SEARCH_PIVOT A specified number of edges are examined in
827 /// every iteration in a wraparound fashion and the best eligible
828 /// edge is selected from this block (\ref BlockSearchPivotRule).
830 /// - CANDIDATE_LIST_PIVOT In a major iteration a candidate list is
831 /// built from eligible edges in a wraparound fashion and in the
832 /// following minor iterations the best eligible edge is selected
833 /// from this list (\ref CandidateListPivotRule).
835 /// - ALTERING_LIST_PIVOT It is a modified version of the
836 /// "Candidate List" pivot rule. It keeps only the several best
837 /// eligible edges from the former candidate list and extends this
838 /// list in every iteration (\ref AlteringListPivotRule).
840 /// According to our comprehensive benchmark tests the "Block Search"
841 /// pivot rule proved to be by far the fastest and the most robust
842 /// on various test inputs. Thus it is the default option.
844 /// \return \c true if a feasible flow can be found.
845 bool run(PivotRuleEnum pivot_rule = BLOCK_SEARCH_PIVOT) {
846 return init() && start(pivot_rule);
851 /// \name Query Functions
852 /// The results of the algorithm can be obtained using these
854 /// \ref lemon::NetworkSimplex::run() "run()" must be called before
859 /// \brief Return a const reference to the edge map storing the
862 /// Return a const reference to the edge map storing the found flow.
864 /// \pre \ref run() must be called before using this function.
865 const FlowMap& flowMap() const {
866 return *_flow_result;
869 /// \brief Return a const reference to the node map storing the
870 /// found potentials (the dual solution).
872 /// Return a const reference to the node map storing the found
873 /// potentials (the dual solution).
875 /// \pre \ref run() must be called before using this function.
876 const PotentialMap& potentialMap() const {
877 return *_potential_result;
880 /// \brief Return the flow on the given edge.
882 /// Return the flow on the given edge.
884 /// \pre \ref run() must be called before using this function.
885 Capacity flow(const typename Graph::Edge& edge) const {
886 return (*_flow_result)[edge];
889 /// \brief Return the potential of the given node.
891 /// Return the potential of the given node.
893 /// \pre \ref run() must be called before using this function.
894 Cost potential(const typename Graph::Node& node) const {
895 return (*_potential_result)[node];
898 /// \brief Return the total cost of the found flow.
900 /// Return the total cost of the found flow. The complexity of the
901 /// function is \f$ O(e) \f$.
903 /// \pre \ref run() must be called before using this function.
904 Cost totalCost() const {
906 for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e)
907 c += (*_flow_result)[e] * _cost[_edge_ref[e]];
915 /// \brief Extend the underlying graph and initialize all the
916 /// node and edge maps.
918 if (!_valid_supply) return false;
920 // Initializing result maps
922 _flow_result = new FlowMap(_graph_ref);
925 if (!_potential_result) {
926 _potential_result = new PotentialMap(_graph_ref);
927 _local_potential = true;
930 // Initializing the edge vector and the edge maps
931 _edges.reserve(countEdges(_graph));
932 for (EdgeIt e(_graph); e != INVALID; ++e) {
935 _state[e] = STATE_LOWER;
938 // Adding an artificial root node to the graph
939 _root = _graph.addNode();
940 _parent[_root] = INVALID;
941 _pred_edge[_root] = INVALID;
944 _potential[_root] = 0;
946 // Adding artificial edges to the graph and initializing the node
947 // maps of the spanning tree data structure
950 Cost max_cost = std::numeric_limits<Cost>::max() / 4;
951 for (NodeIt u(_graph); u != INVALID; ++u) {
952 if (u == _root) continue;
957 if (_supply[u] >= 0) {
958 e = _graph.addEdge(u, _root);
959 _flow[e] = _supply[u];
961 _potential[u] = -max_cost;
963 e = _graph.addEdge(_root, u);
964 _flow[e] = -_supply[u];
966 _potential[u] = max_cost;
969 _capacity[e] = std::numeric_limits<Capacity>::max();
970 _state[e] = STATE_TREE;
973 _thread[last] = _root;
978 /// Find the join node.
979 inline Node findJoinNode() {
980 Node u = _graph.source(_in_edge);
981 Node v = _graph.target(_in_edge);
983 if (_depth[u] == _depth[v]) {
987 else if (_depth[u] > _depth[v]) u = _parent[u];
993 /// \brief Find the leaving edge of the cycle.
994 /// \return \c true if the leaving edge is not the same as the
996 inline bool findLeavingEdge() {
997 // Initializing first and second nodes according to the direction
999 if (_state[_in_edge] == STATE_LOWER) {
1000 first = _graph.source(_in_edge);
1001 second = _graph.target(_in_edge);
1003 first = _graph.target(_in_edge);
1004 second = _graph.source(_in_edge);
1006 delta = _capacity[_in_edge];
1007 bool result = false;
1011 // Searching the cycle along the path form the first node to the
1013 for (Node u = first; u != join; u = _parent[u]) {
1015 d = _forward[u] ? _flow[e] : _capacity[e] - _flow[e];
1024 // Searching the cycle along the path form the second node to the
1026 for (Node u = second; u != join; u = _parent[u]) {
1028 d = _forward[u] ? _capacity[e] - _flow[e] : _flow[e];
1040 /// Change \c flow and \c state edge maps.
1041 inline void changeFlows(bool change) {
1042 // Augmenting along the cycle
1044 Capacity val = _state[_in_edge] * delta;
1045 _flow[_in_edge] += val;
1046 for (Node u = _graph.source(_in_edge); u != join; u = _parent[u]) {
1047 _flow[_pred_edge[u]] += _forward[u] ? -val : val;
1049 for (Node u = _graph.target(_in_edge); u != join; u = _parent[u]) {
1050 _flow[_pred_edge[u]] += _forward[u] ? val : -val;
1053 // Updating the state of the entering and leaving edges
1055 _state[_in_edge] = STATE_TREE;
1056 _state[_pred_edge[u_out]] =
1057 (_flow[_pred_edge[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1059 _state[_in_edge] = -_state[_in_edge];
1063 /// Update \c thread and \c parent node maps.
1064 inline void updateThreadParent() {
1066 v_out = _parent[u_out];
1068 // Handling the case when join and v_out coincide
1069 bool par_first = false;
1070 if (join == v_out) {
1071 for (u = join; u != u_in && u != v_in; u = _thread[u]) ;
1074 while (_thread[u] != u_out) u = _thread[u];
1079 // Finding the last successor of u_in (u) and the node after it
1080 // (right) according to the thread index
1081 for (u = u_in; _depth[_thread[u]] > _depth[u_in]; u = _thread[u]) ;
1083 if (_thread[v_in] == u_out) {
1084 for (last = u; _depth[last] > _depth[u_out]; last = _thread[last]) ;
1085 if (last == u_out) last = _thread[last];
1087 else last = _thread[v_in];
1089 // Updating stem nodes
1090 _thread[v_in] = stem = u_in;
1092 while (stem != u_out) {
1093 _thread[u] = new_stem = _parent[stem];
1095 // Finding the node just before the stem node (u) according to
1096 // the original thread index
1097 for (u = new_stem; _thread[u] != stem; u = _thread[u]) ;
1100 // Changing the parent node of stem and shifting stem and
1102 _parent[stem] = par_stem;
1106 // Finding the last successor of stem (u) and the node after it
1107 // (right) according to the thread index
1108 for (u = stem; _depth[_thread[u]] > _depth[stem]; u = _thread[u]) ;
1111 _parent[u_out] = par_stem;
1114 if (join == v_out && par_first) {
1115 if (first != v_in) _thread[first] = right;
1117 for (u = v_out; _thread[u] != u_out; u = _thread[u]) ;
1122 /// Update \c pred_edge and \c forward node maps.
1123 inline void updatePredEdge() {
1127 _pred_edge[u] = _pred_edge[v];
1128 _forward[u] = !_forward[v];
1131 _pred_edge[u_in] = _in_edge;
1132 _forward[u_in] = (u_in == _graph.source(_in_edge));
1135 /// Update \c depth and \c potential node maps.
1136 inline void updateDepthPotential() {
1137 _depth[u_in] = _depth[v_in] + 1;
1138 _potential[u_in] = _forward[u_in] ?
1139 _potential[v_in] - _cost[_pred_edge[u_in]] :
1140 _potential[v_in] + _cost[_pred_edge[u_in]];
1142 Node u = _thread[u_in], v;
1145 if (v == INVALID) break;
1146 _depth[u] = _depth[v] + 1;
1147 _potential[u] = _forward[u] ?
1148 _potential[v] - _cost[_pred_edge[u]] :
1149 _potential[v] + _cost[_pred_edge[u]];
1150 if (_depth[u] <= _depth[v_in]) break;
1155 /// Execute the algorithm.
1156 bool start(PivotRuleEnum pivot_rule) {
1157 // Selecting the pivot rule implementation
1158 switch (pivot_rule) {
1159 case FIRST_ELIGIBLE_PIVOT:
1160 return start<FirstEligiblePivotRule>();
1161 case BEST_ELIGIBLE_PIVOT:
1162 return start<BestEligiblePivotRule>();
1163 case BLOCK_SEARCH_PIVOT:
1164 return start<BlockSearchPivotRule>();
1165 case CANDIDATE_LIST_PIVOT:
1166 return start<CandidateListPivotRule>();
1167 case ALTERING_LIST_PIVOT:
1168 return start<AlteringListPivotRule>();
1173 template<class PivotRuleImplementation>
1175 PivotRuleImplementation pivot(*this, _edges);
1177 // Executing the network simplex algorithm
1178 while (pivot.findEnteringEdge()) {
1179 join = findJoinNode();
1180 bool change = findLeavingEdge();
1181 changeFlows(change);
1183 updateThreadParent();
1185 updateDepthPotential();
1189 // Checking if the flow amount equals zero on all the artificial
1191 for (InEdgeIt e(_graph, _root); e != INVALID; ++e)
1192 if (_flow[e] > 0) return false;
1193 for (OutEdgeIt e(_graph, _root); e != INVALID; ++e)
1194 if (_flow[e] > 0) return false;
1196 // Copying flow values to _flow_result
1198 for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e)
1199 (*_flow_result)[e] = (*_lower)[e] + _flow[_edge_ref[e]];
1201 for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e)
1202 (*_flow_result)[e] = _flow[_edge_ref[e]];
1204 // Copying potential values to _potential_result
1205 for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n)
1206 (*_potential_result)[n] = _potential[_node_ref[n]];
1211 }; //class NetworkSimplex
1217 #endif //LEMON_NETWORK_SIMPLEX_H