1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
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.
31 #include <lemon/core.h>
32 #include <lemon/math.h>
36 /// \addtogroup min_cost_flow
39 /// \brief Implementation of the primal Network Simplex algorithm
40 /// for finding a \ref min_cost_flow "minimum cost flow".
42 /// \ref NetworkSimplex implements the primal Network Simplex algorithm
43 /// for finding a \ref min_cost_flow "minimum cost flow".
44 /// This algorithm is a specialized version of the linear programming
45 /// simplex method directly for the minimum cost flow problem.
46 /// It is one of the most efficient solution methods.
48 /// In general this class is the fastest implementation available
49 /// in LEMON for the minimum cost flow problem.
50 /// Moreover it supports both directions of the supply/demand inequality
51 /// constraints. For more information see \ref SupplyType.
53 /// Most of the parameters of the problem (except for the digraph)
54 /// can be given using separate functions, and the algorithm can be
55 /// executed using the \ref run() function. If some parameters are not
56 /// specified, then default values will be used.
58 /// \tparam GR The digraph type the algorithm runs on.
59 /// \tparam V The value type used for flow amounts, capacity bounds
60 /// and supply values in the algorithm. By default it is \c int.
61 /// \tparam C The value type used for costs and potentials in the
62 /// algorithm. By default it is the same as \c V.
64 /// \warning Both value types must be signed and all input data must
67 /// \note %NetworkSimplex provides five different pivot rule
68 /// implementations, from which the most efficient one is used
69 /// by default. For more information see \ref PivotRule.
70 template <typename GR, typename V = int, typename C = V>
75 /// The flow type of the algorithm
77 /// The cost type of the algorithm
80 /// The type of the flow map
81 typedef GR::ArcMap<Value> FlowMap;
82 /// The type of the potential map
83 typedef GR::NodeMap<Cost> PotentialMap;
85 /// The type of the flow map
86 typedef typename GR::template ArcMap<Value> FlowMap;
87 /// The type of the potential map
88 typedef typename GR::template NodeMap<Cost> PotentialMap;
93 /// \brief Problem type constants for the \c run() function.
95 /// Enum type containing the problem type constants that can be
96 /// returned by the \ref run() function of the algorithm.
98 /// The problem has no feasible solution (flow).
100 /// The problem has optimal solution (i.e. it is feasible and
101 /// bounded), and the algorithm has found optimal flow and node
102 /// potentials (primal and dual solutions).
104 /// The objective function of the problem is unbounded, i.e.
105 /// there is a directed cycle having negative total cost and
106 /// infinite upper bound.
110 /// \brief Constants for selecting the type of the supply constraints.
112 /// Enum type containing constants for selecting the supply type,
113 /// i.e. the direction of the inequalities in the supply/demand
114 /// constraints of the \ref min_cost_flow "minimum cost flow problem".
116 /// The default supply type is \c GEQ, since this form is supported
117 /// by other minimum cost flow algorithms and the \ref Circulation
118 /// algorithm, as well.
119 /// The \c LEQ problem type can be selected using the \ref supplyType()
122 /// Note that the equality form is a special case of both supply types.
125 /// This option means that there are <em>"greater or equal"</em>
126 /// supply/demand constraints in the definition, i.e. the exact
127 /// formulation of the problem is the following.
129 \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
130 \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
131 sup(u) \quad \forall u\in V \f]
132 \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
134 /// It means that the total demand must be greater or equal to the
135 /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
136 /// negative) and all the supplies have to be carried out from
137 /// the supply nodes, but there could be demands that are not
140 /// It is just an alias for the \c GEQ option.
141 CARRY_SUPPLIES = GEQ,
143 /// This option means that there are <em>"less or equal"</em>
144 /// supply/demand constraints in the definition, i.e. the exact
145 /// formulation of the problem is the following.
147 \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
148 \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
149 sup(u) \quad \forall u\in V \f]
150 \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
152 /// It means that the total demand must be less or equal to the
153 /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
154 /// positive) and all the demands have to be satisfied, but there
155 /// could be supplies that are not carried out from the supply
158 /// It is just an alias for the \c LEQ option.
159 SATISFY_DEMANDS = LEQ
162 /// \brief Constants for selecting the pivot rule.
164 /// Enum type containing constants for selecting the pivot rule for
165 /// the \ref run() function.
167 /// \ref NetworkSimplex provides five different pivot rule
168 /// implementations that significantly affect the running time
169 /// of the algorithm.
170 /// By default \ref BLOCK_SEARCH "Block Search" is used, which
171 /// proved to be the most efficient and the most robust on various
172 /// test inputs according to our benchmark tests.
173 /// However another pivot rule can be selected using the \ref run()
174 /// function with the proper parameter.
177 /// The First Eligible pivot rule.
178 /// The next eligible arc is selected in a wraparound fashion
179 /// in every iteration.
182 /// The Best Eligible pivot rule.
183 /// The best eligible arc is selected in every iteration.
186 /// The Block Search pivot rule.
187 /// A specified number of arcs are examined in every iteration
188 /// in a wraparound fashion and the best eligible arc is selected
192 /// The Candidate List pivot rule.
193 /// In a major iteration a candidate list is built from eligible arcs
194 /// in a wraparound fashion and in the following minor iterations
195 /// the best eligible arc is selected from this list.
198 /// The Altering Candidate List pivot rule.
199 /// It is a modified version of the Candidate List method.
200 /// It keeps only the several best eligible arcs from the former
201 /// candidate list and extends this list in every iteration.
207 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
209 typedef typename GR::template ArcMap<Value> ValueArcMap;
210 typedef typename GR::template ArcMap<Cost> CostArcMap;
211 typedef typename GR::template NodeMap<Value> ValueNodeMap;
213 typedef std::vector<Arc> ArcVector;
214 typedef std::vector<Node> NodeVector;
215 typedef std::vector<int> IntVector;
216 typedef std::vector<bool> BoolVector;
217 typedef std::vector<Value> FlowVector;
218 typedef std::vector<Cost> CostVector;
220 // State constants for arcs
229 // Data related to the underlying digraph
234 // Parameters of the problem
235 ValueArcMap *_plower;
236 ValueArcMap *_pupper;
238 ValueNodeMap *_psupply;
240 Node _psource, _ptarget;
248 PotentialMap *_potential_map;
250 bool _local_potential;
252 // Data structures for storing the digraph
265 // Data for storing the spanning tree structure
269 IntVector _rev_thread;
271 IntVector _last_succ;
272 IntVector _dirty_revs;
277 // Temporary data used in the current pivot iteration
278 int in_arc, join, u_in, v_in, u_out, v_out;
279 int first, second, right, last;
280 int stem, par_stem, new_stem;
285 /// \brief Constant for infinite upper bounds (capacities).
287 /// Constant for infinite upper bounds (capacities).
288 /// It is \c std::numeric_limits<Value>::infinity() if available,
289 /// \c std::numeric_limits<Value>::max() otherwise.
294 // Implementation of the First Eligible pivot rule
295 class FirstEligiblePivotRule
299 // References to the NetworkSimplex class
300 const IntVector &_source;
301 const IntVector &_target;
302 const CostVector &_cost;
303 const IntVector &_state;
304 const CostVector &_pi;
314 FirstEligiblePivotRule(NetworkSimplex &ns) :
315 _source(ns._source), _target(ns._target),
316 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
317 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
320 // Find next entering arc
321 bool findEnteringArc() {
323 for (int e = _next_arc; e < _arc_num; ++e) {
324 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
331 for (int e = 0; e < _next_arc; ++e) {
332 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
342 }; //class FirstEligiblePivotRule
345 // Implementation of the Best Eligible pivot rule
346 class BestEligiblePivotRule
350 // References to the NetworkSimplex class
351 const IntVector &_source;
352 const IntVector &_target;
353 const CostVector &_cost;
354 const IntVector &_state;
355 const CostVector &_pi;
362 BestEligiblePivotRule(NetworkSimplex &ns) :
363 _source(ns._source), _target(ns._target),
364 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
365 _in_arc(ns.in_arc), _arc_num(ns._arc_num)
368 // Find next entering arc
369 bool findEnteringArc() {
371 for (int e = 0; e < _arc_num; ++e) {
372 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
381 }; //class BestEligiblePivotRule
384 // Implementation of the Block Search pivot rule
385 class BlockSearchPivotRule
389 // References to the NetworkSimplex class
390 const IntVector &_source;
391 const IntVector &_target;
392 const CostVector &_cost;
393 const IntVector &_state;
394 const CostVector &_pi;
405 BlockSearchPivotRule(NetworkSimplex &ns) :
406 _source(ns._source), _target(ns._target),
407 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
408 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
410 // The main parameters of the pivot rule
411 const double BLOCK_SIZE_FACTOR = 2.0;
412 const int MIN_BLOCK_SIZE = 10;
414 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
415 std::sqrt(double(_arc_num))),
419 // Find next entering arc
420 bool findEnteringArc() {
422 int cnt = _block_size;
423 int e, min_arc = _next_arc;
424 for (e = _next_arc; e < _arc_num; ++e) {
425 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
435 if (min == 0 || cnt > 0) {
436 for (e = 0; e < _next_arc; ++e) {
437 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
448 if (min >= 0) return false;
454 }; //class BlockSearchPivotRule
457 // Implementation of the Candidate List pivot rule
458 class CandidateListPivotRule
462 // References to the NetworkSimplex class
463 const IntVector &_source;
464 const IntVector &_target;
465 const CostVector &_cost;
466 const IntVector &_state;
467 const CostVector &_pi;
472 IntVector _candidates;
473 int _list_length, _minor_limit;
474 int _curr_length, _minor_count;
480 CandidateListPivotRule(NetworkSimplex &ns) :
481 _source(ns._source), _target(ns._target),
482 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
483 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
485 // The main parameters of the pivot rule
486 const double LIST_LENGTH_FACTOR = 1.0;
487 const int MIN_LIST_LENGTH = 10;
488 const double MINOR_LIMIT_FACTOR = 0.1;
489 const int MIN_MINOR_LIMIT = 3;
491 _list_length = std::max( int(LIST_LENGTH_FACTOR *
492 std::sqrt(double(_arc_num))),
494 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
496 _curr_length = _minor_count = 0;
497 _candidates.resize(_list_length);
500 /// Find next entering arc
501 bool findEnteringArc() {
503 int e, min_arc = _next_arc;
504 if (_curr_length > 0 && _minor_count < _minor_limit) {
505 // Minor iteration: select the best eligible arc from the
506 // current candidate list
509 for (int i = 0; i < _curr_length; ++i) {
511 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
517 _candidates[i--] = _candidates[--_curr_length];
526 // Major iteration: build a new candidate list
529 for (e = _next_arc; e < _arc_num; ++e) {
530 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
532 _candidates[_curr_length++] = e;
537 if (_curr_length == _list_length) break;
540 if (_curr_length < _list_length) {
541 for (e = 0; e < _next_arc; ++e) {
542 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
544 _candidates[_curr_length++] = e;
549 if (_curr_length == _list_length) break;
553 if (_curr_length == 0) return false;
560 }; //class CandidateListPivotRule
563 // Implementation of the Altering Candidate List pivot rule
564 class AlteringListPivotRule
568 // References to the NetworkSimplex class
569 const IntVector &_source;
570 const IntVector &_target;
571 const CostVector &_cost;
572 const IntVector &_state;
573 const CostVector &_pi;
578 int _block_size, _head_length, _curr_length;
580 IntVector _candidates;
581 CostVector _cand_cost;
583 // Functor class to compare arcs during sort of the candidate list
587 const CostVector &_map;
589 SortFunc(const CostVector &map) : _map(map) {}
590 bool operator()(int left, int right) {
591 return _map[left] > _map[right];
600 AlteringListPivotRule(NetworkSimplex &ns) :
601 _source(ns._source), _target(ns._target),
602 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
603 _in_arc(ns.in_arc), _arc_num(ns._arc_num),
604 _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
606 // The main parameters of the pivot rule
607 const double BLOCK_SIZE_FACTOR = 1.5;
608 const int MIN_BLOCK_SIZE = 10;
609 const double HEAD_LENGTH_FACTOR = 0.1;
610 const int MIN_HEAD_LENGTH = 3;
612 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
613 std::sqrt(double(_arc_num))),
615 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
617 _candidates.resize(_head_length + _block_size);
621 // Find next entering arc
622 bool findEnteringArc() {
623 // Check the current candidate list
625 for (int i = 0; i < _curr_length; ++i) {
627 _cand_cost[e] = _state[e] *
628 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
629 if (_cand_cost[e] >= 0) {
630 _candidates[i--] = _candidates[--_curr_length];
635 int cnt = _block_size;
637 int limit = _head_length;
639 for (int e = _next_arc; e < _arc_num; ++e) {
640 _cand_cost[e] = _state[e] *
641 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
642 if (_cand_cost[e] < 0) {
643 _candidates[_curr_length++] = e;
647 if (_curr_length > limit) break;
652 if (_curr_length <= limit) {
653 for (int e = 0; e < _next_arc; ++e) {
654 _cand_cost[e] = _state[e] *
655 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
656 if (_cand_cost[e] < 0) {
657 _candidates[_curr_length++] = e;
661 if (_curr_length > limit) break;
667 if (_curr_length == 0) return false;
668 _next_arc = last_arc + 1;
670 // Make heap of the candidate list (approximating a partial sort)
671 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
674 // Pop the first element of the heap
675 _in_arc = _candidates[0];
676 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
678 _curr_length = std::min(_head_length, _curr_length - 1);
682 }; //class AlteringListPivotRule
686 /// \brief Constructor.
688 /// The constructor of the class.
690 /// \param graph The digraph the algorithm runs on.
691 NetworkSimplex(const GR& graph) :
693 _plower(NULL), _pupper(NULL), _pcost(NULL),
694 _psupply(NULL), _pstsup(false), _stype(GEQ),
695 _flow_map(NULL), _potential_map(NULL),
696 _local_flow(false), _local_potential(false),
698 INF(std::numeric_limits<Value>::has_infinity ?
699 std::numeric_limits<Value>::infinity() :
700 std::numeric_limits<Value>::max())
702 // Check the value types
703 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
704 "The flow type of NetworkSimplex must be signed");
705 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
706 "The cost type of NetworkSimplex must be signed");
711 if (_local_flow) delete _flow_map;
712 if (_local_potential) delete _potential_map;
716 /// The parameters of the algorithm can be specified using these
721 /// \brief Set the lower bounds on the arcs.
723 /// This function sets the lower bounds on the arcs.
724 /// If it is not used before calling \ref run(), the lower bounds
725 /// will be set to zero on all arcs.
727 /// \param map An arc map storing the lower bounds.
728 /// Its \c Value type must be convertible to the \c Value type
729 /// of the algorithm.
731 /// \return <tt>(*this)</tt>
732 template <typename LowerMap>
733 NetworkSimplex& lowerMap(const LowerMap& map) {
735 _plower = new ValueArcMap(_graph);
736 for (ArcIt a(_graph); a != INVALID; ++a) {
737 (*_plower)[a] = map[a];
742 /// \brief Set the upper bounds (capacities) on the arcs.
744 /// This function sets the upper bounds (capacities) on the arcs.
745 /// If it is not used before calling \ref run(), the upper bounds
746 /// will be set to \ref INF on all arcs (i.e. the flow value will be
747 /// unbounded from above on each arc).
749 /// \param map An arc map storing the upper bounds.
750 /// Its \c Value type must be convertible to the \c Value type
751 /// of the algorithm.
753 /// \return <tt>(*this)</tt>
754 template<typename UpperMap>
755 NetworkSimplex& upperMap(const UpperMap& map) {
757 _pupper = new ValueArcMap(_graph);
758 for (ArcIt a(_graph); a != INVALID; ++a) {
759 (*_pupper)[a] = map[a];
764 /// \brief Set the costs of the arcs.
766 /// This function sets the costs of the arcs.
767 /// If it is not used before calling \ref run(), the costs
768 /// will be set to \c 1 on all arcs.
770 /// \param map An arc map storing the costs.
771 /// Its \c Value type must be convertible to the \c Cost type
772 /// of the algorithm.
774 /// \return <tt>(*this)</tt>
775 template<typename CostMap>
776 NetworkSimplex& costMap(const CostMap& map) {
778 _pcost = new CostArcMap(_graph);
779 for (ArcIt a(_graph); a != INVALID; ++a) {
780 (*_pcost)[a] = map[a];
785 /// \brief Set the supply values of the nodes.
787 /// This function sets the supply values of the nodes.
788 /// If neither this function nor \ref stSupply() is used before
789 /// calling \ref run(), the supply of each node will be set to zero.
790 /// (It makes sense only if non-zero lower bounds are given.)
792 /// \param map A node map storing the supply values.
793 /// Its \c Value type must be convertible to the \c Value type
794 /// of the algorithm.
796 /// \return <tt>(*this)</tt>
797 template<typename SupplyMap>
798 NetworkSimplex& supplyMap(const SupplyMap& map) {
801 _psupply = new ValueNodeMap(_graph);
802 for (NodeIt n(_graph); n != INVALID; ++n) {
803 (*_psupply)[n] = map[n];
808 /// \brief Set single source and target nodes and a supply value.
810 /// This function sets a single source node and a single target node
811 /// and the required flow value.
812 /// If neither this function nor \ref supplyMap() is used before
813 /// calling \ref run(), the supply of each node will be set to zero.
814 /// (It makes sense only if non-zero lower bounds are given.)
816 /// Using this function has the same effect as using \ref supplyMap()
817 /// with such a map in which \c k is assigned to \c s, \c -k is
818 /// assigned to \c t and all other nodes have zero supply value.
820 /// \param s The source node.
821 /// \param t The target node.
822 /// \param k The required amount of flow from node \c s to node \c t
823 /// (i.e. the supply of \c s and the demand of \c t).
825 /// \return <tt>(*this)</tt>
826 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
836 /// \brief Set the type of the supply constraints.
838 /// This function sets the type of the supply/demand constraints.
839 /// If it is not used before calling \ref run(), the \ref GEQ supply
840 /// type will be used.
842 /// For more information see \ref SupplyType.
844 /// \return <tt>(*this)</tt>
845 NetworkSimplex& supplyType(SupplyType supply_type) {
846 _stype = supply_type;
850 /// \brief Set the flow map.
852 /// This function sets the flow map.
853 /// If it is not used before calling \ref run(), an instance will
854 /// be allocated automatically. The destructor deallocates this
855 /// automatically allocated map, of course.
857 /// \return <tt>(*this)</tt>
858 NetworkSimplex& flowMap(FlowMap& map) {
867 /// \brief Set the potential map.
869 /// This function sets the potential map, which is used for storing
870 /// the dual solution.
871 /// If it is not used before calling \ref run(), an instance will
872 /// be allocated automatically. The destructor deallocates this
873 /// automatically allocated map, of course.
875 /// \return <tt>(*this)</tt>
876 NetworkSimplex& potentialMap(PotentialMap& map) {
877 if (_local_potential) {
878 delete _potential_map;
879 _local_potential = false;
881 _potential_map = ↦
887 /// \name Execution Control
888 /// The algorithm can be executed using \ref run().
892 /// \brief Run the algorithm.
894 /// This function runs the algorithm.
895 /// The paramters can be specified using functions \ref lowerMap(),
896 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
897 /// \ref supplyType(), \ref flowMap() and \ref potentialMap().
900 /// NetworkSimplex<ListDigraph> ns(graph);
901 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
902 /// .supplyMap(sup).run();
905 /// This function can be called more than once. All the parameters
906 /// that have been given are kept for the next call, unless
907 /// \ref reset() is called, thus only the modified parameters
908 /// have to be set again. See \ref reset() for examples.
910 /// \param pivot_rule The pivot rule that will be used during the
911 /// algorithm. For more information see \ref PivotRule.
913 /// \return \c INFEASIBLE if no feasible flow exists,
914 /// \n \c OPTIMAL if the problem has optimal solution
915 /// (i.e. it is feasible and bounded), and the algorithm has found
916 /// optimal flow and node potentials (primal and dual solutions),
917 /// \n \c UNBOUNDED if the objective function of the problem is
918 /// unbounded, i.e. there is a directed cycle having negative total
919 /// cost and infinite upper bound.
921 /// \see ProblemType, PivotRule
922 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
923 if (!init()) return INFEASIBLE;
924 return start(pivot_rule);
927 /// \brief Reset all the parameters that have been given before.
929 /// This function resets all the paramaters that have been given
930 /// before using functions \ref lowerMap(), \ref upperMap(),
931 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType(),
932 /// \ref flowMap() and \ref potentialMap().
934 /// It is useful for multiple run() calls. If this function is not
935 /// used, all the parameters given before are kept for the next
940 /// NetworkSimplex<ListDigraph> ns(graph);
943 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
944 /// .supplyMap(sup).run();
946 /// // Run again with modified cost map (reset() is not called,
947 /// // so only the cost map have to be set again)
949 /// ns.costMap(cost).run();
951 /// // Run again from scratch using reset()
952 /// // (the lower bounds will be set to zero on all arcs)
954 /// ns.upperMap(capacity).costMap(cost)
955 /// .supplyMap(sup).run();
958 /// \return <tt>(*this)</tt>
959 NetworkSimplex& reset() {
970 if (_local_flow) delete _flow_map;
971 if (_local_potential) delete _potential_map;
973 _potential_map = NULL;
975 _local_potential = false;
982 /// \name Query Functions
983 /// The results of the algorithm can be obtained using these
985 /// The \ref run() function must be called before using them.
989 /// \brief Return the total cost of the found flow.
991 /// This function returns the total cost of the found flow.
992 /// Its complexity is O(e).
994 /// \note The return type of the function can be specified as a
995 /// template parameter. For example,
997 /// ns.totalCost<double>();
999 /// It is useful if the total cost cannot be stored in the \c Cost
1000 /// type of the algorithm, which is the default return type of the
1003 /// \pre \ref run() must be called before using this function.
1004 template <typename Value>
1005 Value totalCost() const {
1008 for (ArcIt e(_graph); e != INVALID; ++e)
1009 c += (*_flow_map)[e] * (*_pcost)[e];
1011 for (ArcIt e(_graph); e != INVALID; ++e)
1012 c += (*_flow_map)[e];
1018 Cost totalCost() const {
1019 return totalCost<Cost>();
1023 /// \brief Return the flow on the given arc.
1025 /// This function returns the flow on the given arc.
1027 /// \pre \ref run() must be called before using this function.
1028 Value flow(const Arc& a) const {
1029 return (*_flow_map)[a];
1032 /// \brief Return a const reference to the flow map.
1034 /// This function returns a const reference to an arc map storing
1037 /// \pre \ref run() must be called before using this function.
1038 const FlowMap& flowMap() const {
1042 /// \brief Return the potential (dual value) of the given node.
1044 /// This function returns the potential (dual value) of the
1047 /// \pre \ref run() must be called before using this function.
1048 Cost potential(const Node& n) const {
1049 return (*_potential_map)[n];
1052 /// \brief Return a const reference to the potential map
1053 /// (the dual solution).
1055 /// This function returns a const reference to a node map storing
1056 /// the found potentials, which form the dual solution of the
1057 /// \ref min_cost_flow "minimum cost flow problem".
1059 /// \pre \ref run() must be called before using this function.
1060 const PotentialMap& potentialMap() const {
1061 return *_potential_map;
1068 // Initialize internal data structures
1070 // Initialize result maps
1072 _flow_map = new FlowMap(_graph);
1075 if (!_potential_map) {
1076 _potential_map = new PotentialMap(_graph);
1077 _local_potential = true;
1080 // Initialize vectors
1081 _node_num = countNodes(_graph);
1082 _arc_num = countArcs(_graph);
1083 int all_node_num = _node_num + 1;
1084 int all_arc_num = _arc_num + _node_num;
1085 if (_node_num == 0) return false;
1087 _arc_ref.resize(_arc_num);
1088 _source.resize(all_arc_num);
1089 _target.resize(all_arc_num);
1091 _cap.resize(all_arc_num);
1092 _cost.resize(all_arc_num);
1093 _supply.resize(all_node_num);
1094 _flow.resize(all_arc_num);
1095 _pi.resize(all_node_num);
1097 _parent.resize(all_node_num);
1098 _pred.resize(all_node_num);
1099 _forward.resize(all_node_num);
1100 _thread.resize(all_node_num);
1101 _rev_thread.resize(all_node_num);
1102 _succ_num.resize(all_node_num);
1103 _last_succ.resize(all_node_num);
1104 _state.resize(all_arc_num);
1106 // Initialize node related data
1107 bool valid_supply = true;
1109 if (!_pstsup && !_psupply) {
1111 _psource = _ptarget = NodeIt(_graph);
1116 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1118 _supply[i] = (*_psupply)[n];
1119 _sum_supply += _supply[i];
1121 valid_supply = (_stype == GEQ && _sum_supply <= 0) ||
1122 (_stype == LEQ && _sum_supply >= 0);
1125 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1129 _supply[_node_id[_psource]] = _pstflow;
1130 _supply[_node_id[_ptarget]] = -_pstflow;
1132 if (!valid_supply) return false;
1134 // Initialize artifical cost
1136 if (std::numeric_limits<Cost>::is_exact) {
1137 ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
1139 ART_COST = std::numeric_limits<Cost>::min();
1140 for (int i = 0; i != _arc_num; ++i) {
1141 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1143 ART_COST = (ART_COST + 1) * _node_num;
1146 // Set data for the artificial root node
1148 _parent[_root] = -1;
1151 _rev_thread[0] = _root;
1152 _succ_num[_root] = all_node_num;
1153 _last_succ[_root] = _root - 1;
1154 _supply[_root] = -_sum_supply;
1155 if (_sum_supply < 0) {
1156 _pi[_root] = -ART_COST;
1158 _pi[_root] = ART_COST;
1161 // Store the arcs in a mixed order
1162 int k = std::max(int(std::sqrt(double(_arc_num))), 10);
1164 for (ArcIt e(_graph); e != INVALID; ++e) {
1166 if ((i += k) >= _arc_num) i = (i % k) + 1;
1169 // Initialize arc maps
1170 if (_pupper && _pcost) {
1171 for (int i = 0; i != _arc_num; ++i) {
1172 Arc e = _arc_ref[i];
1173 _source[i] = _node_id[_graph.source(e)];
1174 _target[i] = _node_id[_graph.target(e)];
1175 _cap[i] = (*_pupper)[e];
1176 _cost[i] = (*_pcost)[e];
1178 _state[i] = STATE_LOWER;
1181 for (int i = 0; i != _arc_num; ++i) {
1182 Arc e = _arc_ref[i];
1183 _source[i] = _node_id[_graph.source(e)];
1184 _target[i] = _node_id[_graph.target(e)];
1186 _state[i] = STATE_LOWER;
1189 for (int i = 0; i != _arc_num; ++i)
1190 _cap[i] = (*_pupper)[_arc_ref[i]];
1192 for (int i = 0; i != _arc_num; ++i)
1196 for (int i = 0; i != _arc_num; ++i)
1197 _cost[i] = (*_pcost)[_arc_ref[i]];
1199 for (int i = 0; i != _arc_num; ++i)
1204 // Remove non-zero lower bounds
1206 for (int i = 0; i != _arc_num; ++i) {
1207 Value c = (*_plower)[_arc_ref[i]];
1209 if (_cap[i] < INF) _cap[i] -= c;
1210 _supply[_source[i]] -= c;
1211 _supply[_target[i]] += c;
1214 if (_cap[i] < INF + c) {
1219 _supply[_source[i]] -= c;
1220 _supply[_target[i]] += c;
1225 // Add artificial arcs and initialize the spanning tree data structure
1226 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1228 _rev_thread[u + 1] = u;
1233 _cost[e] = ART_COST;
1235 _state[e] = STATE_TREE;
1236 if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
1237 _flow[e] = _supply[u];
1239 _pi[u] = -ART_COST + _pi[_root];
1241 _flow[e] = -_supply[u];
1242 _forward[u] = false;
1243 _pi[u] = ART_COST + _pi[_root];
1250 // Find the join node
1251 void findJoinNode() {
1252 int u = _source[in_arc];
1253 int v = _target[in_arc];
1255 if (_succ_num[u] < _succ_num[v]) {
1264 // Find the leaving arc of the cycle and returns true if the
1265 // leaving arc is not the same as the entering arc
1266 bool findLeavingArc() {
1267 // Initialize first and second nodes according to the direction
1269 if (_state[in_arc] == STATE_LOWER) {
1270 first = _source[in_arc];
1271 second = _target[in_arc];
1273 first = _target[in_arc];
1274 second = _source[in_arc];
1276 delta = _cap[in_arc];
1281 // Search the cycle along the path form the first node to the root
1282 for (int u = first; u != join; u = _parent[u]) {
1285 _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1292 // Search the cycle along the path form the second node to the root
1293 for (int u = second; u != join; u = _parent[u]) {
1296 (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1314 // Change _flow and _state vectors
1315 void changeFlow(bool change) {
1316 // Augment along the cycle
1318 Value val = _state[in_arc] * delta;
1319 _flow[in_arc] += val;
1320 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1321 _flow[_pred[u]] += _forward[u] ? -val : val;
1323 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1324 _flow[_pred[u]] += _forward[u] ? val : -val;
1327 // Update the state of the entering and leaving arcs
1329 _state[in_arc] = STATE_TREE;
1330 _state[_pred[u_out]] =
1331 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1333 _state[in_arc] = -_state[in_arc];
1337 // Update the tree structure
1338 void updateTreeStructure() {
1340 int old_rev_thread = _rev_thread[u_out];
1341 int old_succ_num = _succ_num[u_out];
1342 int old_last_succ = _last_succ[u_out];
1343 v_out = _parent[u_out];
1345 u = _last_succ[u_in]; // the last successor of u_in
1346 right = _thread[u]; // the node after it
1348 // Handle the case when old_rev_thread equals to v_in
1349 // (it also means that join and v_out coincide)
1350 if (old_rev_thread == v_in) {
1351 last = _thread[_last_succ[u_out]];
1353 last = _thread[v_in];
1356 // Update _thread and _parent along the stem nodes (i.e. the nodes
1357 // between u_in and u_out, whose parent have to be changed)
1358 _thread[v_in] = stem = u_in;
1359 _dirty_revs.clear();
1360 _dirty_revs.push_back(v_in);
1362 while (stem != u_out) {
1363 // Insert the next stem node into the thread list
1364 new_stem = _parent[stem];
1365 _thread[u] = new_stem;
1366 _dirty_revs.push_back(u);
1368 // Remove the subtree of stem from the thread list
1369 w = _rev_thread[stem];
1371 _rev_thread[right] = w;
1373 // Change the parent node and shift stem nodes
1374 _parent[stem] = par_stem;
1378 // Update u and right
1379 u = _last_succ[stem] == _last_succ[par_stem] ?
1380 _rev_thread[par_stem] : _last_succ[stem];
1383 _parent[u_out] = par_stem;
1385 _rev_thread[last] = u;
1386 _last_succ[u_out] = u;
1388 // Remove the subtree of u_out from the thread list except for
1389 // the case when old_rev_thread equals to v_in
1390 // (it also means that join and v_out coincide)
1391 if (old_rev_thread != v_in) {
1392 _thread[old_rev_thread] = right;
1393 _rev_thread[right] = old_rev_thread;
1396 // Update _rev_thread using the new _thread values
1397 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1399 _rev_thread[_thread[u]] = u;
1402 // Update _pred, _forward, _last_succ and _succ_num for the
1403 // stem nodes from u_out to u_in
1404 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1408 _pred[u] = _pred[w];
1409 _forward[u] = !_forward[w];
1410 tmp_sc += _succ_num[u] - _succ_num[w];
1411 _succ_num[u] = tmp_sc;
1412 _last_succ[w] = tmp_ls;
1415 _pred[u_in] = in_arc;
1416 _forward[u_in] = (u_in == _source[in_arc]);
1417 _succ_num[u_in] = old_succ_num;
1419 // Set limits for updating _last_succ form v_in and v_out
1421 int up_limit_in = -1;
1422 int up_limit_out = -1;
1423 if (_last_succ[join] == v_in) {
1424 up_limit_out = join;
1429 // Update _last_succ from v_in towards the root
1430 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1432 _last_succ[u] = _last_succ[u_out];
1434 // Update _last_succ from v_out towards the root
1435 if (join != old_rev_thread && v_in != old_rev_thread) {
1436 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1438 _last_succ[u] = old_rev_thread;
1441 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1443 _last_succ[u] = _last_succ[u_out];
1447 // Update _succ_num from v_in to join
1448 for (u = v_in; u != join; u = _parent[u]) {
1449 _succ_num[u] += old_succ_num;
1451 // Update _succ_num from v_out to join
1452 for (u = v_out; u != join; u = _parent[u]) {
1453 _succ_num[u] -= old_succ_num;
1457 // Update potentials
1458 void updatePotential() {
1459 Cost sigma = _forward[u_in] ?
1460 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1461 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1462 // Update potentials in the subtree, which has been moved
1463 int end = _thread[_last_succ[u_in]];
1464 for (int u = u_in; u != end; u = _thread[u]) {
1469 // Execute the algorithm
1470 ProblemType start(PivotRule pivot_rule) {
1471 // Select the pivot rule implementation
1472 switch (pivot_rule) {
1473 case FIRST_ELIGIBLE:
1474 return start<FirstEligiblePivotRule>();
1476 return start<BestEligiblePivotRule>();
1478 return start<BlockSearchPivotRule>();
1479 case CANDIDATE_LIST:
1480 return start<CandidateListPivotRule>();
1482 return start<AlteringListPivotRule>();
1484 return INFEASIBLE; // avoid warning
1487 template <typename PivotRuleImpl>
1488 ProblemType start() {
1489 PivotRuleImpl pivot(*this);
1491 // Execute the Network Simplex algorithm
1492 while (pivot.findEnteringArc()) {
1494 bool change = findLeavingArc();
1495 if (delta >= INF) return UNBOUNDED;
1498 updateTreeStructure();
1503 // Check feasibility
1504 if (_sum_supply < 0) {
1505 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1506 if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
1509 else if (_sum_supply > 0) {
1510 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1511 if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
1515 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1516 if (_flow[e] != 0) return INFEASIBLE;
1520 // Copy flow values to _flow_map
1522 for (int i = 0; i != _arc_num; ++i) {
1523 Arc e = _arc_ref[i];
1524 _flow_map->set(e, (*_plower)[e] + _flow[i]);
1527 for (int i = 0; i != _arc_num; ++i) {
1528 _flow_map->set(_arc_ref[i], _flow[i]);
1531 // Copy potential values to _potential_map
1532 for (NodeIt n(_graph); n != INVALID; ++n) {
1533 _potential_map->set(n, _pi[_node_id[n]]);
1539 }; //class NetworkSimplex
1545 #endif //LEMON_NETWORK_SIMPLEX_H