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_algs
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_algs
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 type of the flow amounts, capacity bounds and supply values
77 /// The type of the arc costs
82 /// \brief Problem type constants for the \c run() function.
84 /// Enum type containing the problem type constants that can be
85 /// returned by the \ref run() function of the algorithm.
87 /// The problem has no feasible solution (flow).
89 /// The problem has optimal solution (i.e. it is feasible and
90 /// bounded), and the algorithm has found optimal flow and node
91 /// potentials (primal and dual solutions).
93 /// The objective function of the problem is unbounded, i.e.
94 /// there is a directed cycle having negative total cost and
95 /// infinite upper bound.
99 /// \brief Constants for selecting the type of the supply constraints.
101 /// Enum type containing constants for selecting the supply type,
102 /// i.e. the direction of the inequalities in the supply/demand
103 /// constraints of the \ref min_cost_flow "minimum cost flow problem".
105 /// The default supply type is \c GEQ, the \c LEQ type can be
106 /// selected using \ref supplyType().
107 /// The equality form is a special case of both supply types.
109 /// This option means that there are <em>"greater or equal"</em>
110 /// supply/demand constraints in the definition of the problem.
112 /// This option means that there are <em>"less or equal"</em>
113 /// supply/demand constraints in the definition of the problem.
117 /// \brief Constants for selecting the pivot rule.
119 /// Enum type containing constants for selecting the pivot rule for
120 /// the \ref run() function.
122 /// \ref NetworkSimplex provides five different pivot rule
123 /// implementations that significantly affect the running time
124 /// of the algorithm.
125 /// By default \ref BLOCK_SEARCH "Block Search" is used, which
126 /// proved to be the most efficient and the most robust on various
127 /// test inputs according to our benchmark tests.
128 /// However another pivot rule can be selected using the \ref run()
129 /// function with the proper parameter.
132 /// The First Eligible pivot rule.
133 /// The next eligible arc is selected in a wraparound fashion
134 /// in every iteration.
137 /// The Best Eligible pivot rule.
138 /// The best eligible arc is selected in every iteration.
141 /// The Block Search pivot rule.
142 /// A specified number of arcs are examined in every iteration
143 /// in a wraparound fashion and the best eligible arc is selected
147 /// The Candidate List pivot rule.
148 /// In a major iteration a candidate list is built from eligible arcs
149 /// in a wraparound fashion and in the following minor iterations
150 /// the best eligible arc is selected from this list.
153 /// The Altering Candidate List pivot rule.
154 /// It is a modified version of the Candidate List method.
155 /// It keeps only the several best eligible arcs from the former
156 /// candidate list and extends this list in every iteration.
162 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
164 typedef std::vector<int> IntVector;
165 typedef std::vector<bool> BoolVector;
166 typedef std::vector<Value> ValueVector;
167 typedef std::vector<Cost> CostVector;
169 // State constants for arcs
178 // Data related to the underlying digraph
185 // Parameters of the problem
190 // Data structures for storing the digraph
205 // Data for storing the spanning tree structure
209 IntVector _rev_thread;
211 IntVector _last_succ;
212 IntVector _dirty_revs;
217 // Temporary data used in the current pivot iteration
218 int in_arc, join, u_in, v_in, u_out, v_out;
219 int first, second, right, last;
220 int stem, par_stem, new_stem;
225 /// \brief Constant for infinite upper bounds (capacities).
227 /// Constant for infinite upper bounds (capacities).
228 /// It is \c std::numeric_limits<Value>::infinity() if available,
229 /// \c std::numeric_limits<Value>::max() otherwise.
234 // Implementation of the First Eligible pivot rule
235 class FirstEligiblePivotRule
239 // References to the NetworkSimplex class
240 const IntVector &_source;
241 const IntVector &_target;
242 const CostVector &_cost;
243 const IntVector &_state;
244 const CostVector &_pi;
254 FirstEligiblePivotRule(NetworkSimplex &ns) :
255 _source(ns._source), _target(ns._target),
256 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
257 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
261 // Find next entering arc
262 bool findEnteringArc() {
264 for (int e = _next_arc; e < _search_arc_num; ++e) {
265 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
272 for (int e = 0; e < _next_arc; ++e) {
273 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
283 }; //class FirstEligiblePivotRule
286 // Implementation of the Best Eligible pivot rule
287 class BestEligiblePivotRule
291 // References to the NetworkSimplex class
292 const IntVector &_source;
293 const IntVector &_target;
294 const CostVector &_cost;
295 const IntVector &_state;
296 const CostVector &_pi;
303 BestEligiblePivotRule(NetworkSimplex &ns) :
304 _source(ns._source), _target(ns._target),
305 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
306 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
309 // Find next entering arc
310 bool findEnteringArc() {
312 for (int e = 0; e < _search_arc_num; ++e) {
313 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
322 }; //class BestEligiblePivotRule
325 // Implementation of the Block Search pivot rule
326 class BlockSearchPivotRule
330 // References to the NetworkSimplex class
331 const IntVector &_source;
332 const IntVector &_target;
333 const CostVector &_cost;
334 const IntVector &_state;
335 const CostVector &_pi;
346 BlockSearchPivotRule(NetworkSimplex &ns) :
347 _source(ns._source), _target(ns._target),
348 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
349 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
352 // The main parameters of the pivot rule
353 const double BLOCK_SIZE_FACTOR = 0.5;
354 const int MIN_BLOCK_SIZE = 10;
356 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
357 std::sqrt(double(_search_arc_num))),
361 // Find next entering arc
362 bool findEnteringArc() {
364 int cnt = _block_size;
365 int e, min_arc = _next_arc;
366 for (e = _next_arc; e < _search_arc_num; ++e) {
367 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
377 if (min == 0 || cnt > 0) {
378 for (e = 0; e < _next_arc; ++e) {
379 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
390 if (min >= 0) return false;
396 }; //class BlockSearchPivotRule
399 // Implementation of the Candidate List pivot rule
400 class CandidateListPivotRule
404 // References to the NetworkSimplex class
405 const IntVector &_source;
406 const IntVector &_target;
407 const CostVector &_cost;
408 const IntVector &_state;
409 const CostVector &_pi;
414 IntVector _candidates;
415 int _list_length, _minor_limit;
416 int _curr_length, _minor_count;
422 CandidateListPivotRule(NetworkSimplex &ns) :
423 _source(ns._source), _target(ns._target),
424 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
425 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
428 // The main parameters of the pivot rule
429 const double LIST_LENGTH_FACTOR = 1.0;
430 const int MIN_LIST_LENGTH = 10;
431 const double MINOR_LIMIT_FACTOR = 0.1;
432 const int MIN_MINOR_LIMIT = 3;
434 _list_length = std::max( int(LIST_LENGTH_FACTOR *
435 std::sqrt(double(_search_arc_num))),
437 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
439 _curr_length = _minor_count = 0;
440 _candidates.resize(_list_length);
443 /// Find next entering arc
444 bool findEnteringArc() {
446 int e, min_arc = _next_arc;
447 if (_curr_length > 0 && _minor_count < _minor_limit) {
448 // Minor iteration: select the best eligible arc from the
449 // current candidate list
452 for (int i = 0; i < _curr_length; ++i) {
454 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
460 _candidates[i--] = _candidates[--_curr_length];
469 // Major iteration: build a new candidate list
472 for (e = _next_arc; e < _search_arc_num; ++e) {
473 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
475 _candidates[_curr_length++] = e;
480 if (_curr_length == _list_length) break;
483 if (_curr_length < _list_length) {
484 for (e = 0; e < _next_arc; ++e) {
485 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
487 _candidates[_curr_length++] = e;
492 if (_curr_length == _list_length) break;
496 if (_curr_length == 0) return false;
503 }; //class CandidateListPivotRule
506 // Implementation of the Altering Candidate List pivot rule
507 class AlteringListPivotRule
511 // References to the NetworkSimplex class
512 const IntVector &_source;
513 const IntVector &_target;
514 const CostVector &_cost;
515 const IntVector &_state;
516 const CostVector &_pi;
521 int _block_size, _head_length, _curr_length;
523 IntVector _candidates;
524 CostVector _cand_cost;
526 // Functor class to compare arcs during sort of the candidate list
530 const CostVector &_map;
532 SortFunc(const CostVector &map) : _map(map) {}
533 bool operator()(int left, int right) {
534 return _map[left] > _map[right];
543 AlteringListPivotRule(NetworkSimplex &ns) :
544 _source(ns._source), _target(ns._target),
545 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
546 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
547 _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
549 // The main parameters of the pivot rule
550 const double BLOCK_SIZE_FACTOR = 1.5;
551 const int MIN_BLOCK_SIZE = 10;
552 const double HEAD_LENGTH_FACTOR = 0.1;
553 const int MIN_HEAD_LENGTH = 3;
555 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
556 std::sqrt(double(_search_arc_num))),
558 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
560 _candidates.resize(_head_length + _block_size);
564 // Find next entering arc
565 bool findEnteringArc() {
566 // Check the current candidate list
568 for (int i = 0; i < _curr_length; ++i) {
570 _cand_cost[e] = _state[e] *
571 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
572 if (_cand_cost[e] >= 0) {
573 _candidates[i--] = _candidates[--_curr_length];
578 int cnt = _block_size;
580 int limit = _head_length;
582 for (int e = _next_arc; e < _search_arc_num; ++e) {
583 _cand_cost[e] = _state[e] *
584 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
585 if (_cand_cost[e] < 0) {
586 _candidates[_curr_length++] = e;
590 if (_curr_length > limit) break;
595 if (_curr_length <= limit) {
596 for (int e = 0; e < _next_arc; ++e) {
597 _cand_cost[e] = _state[e] *
598 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
599 if (_cand_cost[e] < 0) {
600 _candidates[_curr_length++] = e;
604 if (_curr_length > limit) break;
610 if (_curr_length == 0) return false;
611 _next_arc = last_arc + 1;
613 // Make heap of the candidate list (approximating a partial sort)
614 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
617 // Pop the first element of the heap
618 _in_arc = _candidates[0];
619 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
621 _curr_length = std::min(_head_length, _curr_length - 1);
625 }; //class AlteringListPivotRule
629 /// \brief Constructor.
631 /// The constructor of the class.
633 /// \param graph The digraph the algorithm runs on.
634 NetworkSimplex(const GR& graph) :
635 _graph(graph), _node_id(graph), _arc_id(graph),
636 INF(std::numeric_limits<Value>::has_infinity ?
637 std::numeric_limits<Value>::infinity() :
638 std::numeric_limits<Value>::max())
640 // Check the value types
641 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
642 "The flow type of NetworkSimplex must be signed");
643 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
644 "The cost type of NetworkSimplex must be signed");
647 _node_num = countNodes(_graph);
648 _arc_num = countArcs(_graph);
649 int all_node_num = _node_num + 1;
650 int max_arc_num = _arc_num + 2 * _node_num;
652 _source.resize(max_arc_num);
653 _target.resize(max_arc_num);
655 _lower.resize(_arc_num);
656 _upper.resize(_arc_num);
657 _cap.resize(max_arc_num);
658 _cost.resize(max_arc_num);
659 _supply.resize(all_node_num);
660 _flow.resize(max_arc_num);
661 _pi.resize(all_node_num);
663 _parent.resize(all_node_num);
664 _pred.resize(all_node_num);
665 _forward.resize(all_node_num);
666 _thread.resize(all_node_num);
667 _rev_thread.resize(all_node_num);
668 _succ_num.resize(all_node_num);
669 _last_succ.resize(all_node_num);
670 _state.resize(max_arc_num);
672 // Copy the graph (store the arcs in a mixed order)
674 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
677 int k = std::max(int(std::sqrt(double(_arc_num))), 10);
679 for (ArcIt a(_graph); a != INVALID; ++a) {
681 _source[i] = _node_id[_graph.source(a)];
682 _target[i] = _node_id[_graph.target(a)];
683 if ((i += k) >= _arc_num) i = (i % k) + 1;
691 /// The parameters of the algorithm can be specified using these
696 /// \brief Set the lower bounds on the arcs.
698 /// This function sets the lower bounds on the arcs.
699 /// If it is not used before calling \ref run(), the lower bounds
700 /// will be set to zero on all arcs.
702 /// \param map An arc map storing the lower bounds.
703 /// Its \c Value type must be convertible to the \c Value type
704 /// of the algorithm.
706 /// \return <tt>(*this)</tt>
707 template <typename LowerMap>
708 NetworkSimplex& lowerMap(const LowerMap& map) {
710 for (ArcIt a(_graph); a != INVALID; ++a) {
711 _lower[_arc_id[a]] = map[a];
716 /// \brief Set the upper bounds (capacities) on the arcs.
718 /// This function sets the upper bounds (capacities) on the arcs.
719 /// If it is not used before calling \ref run(), the upper bounds
720 /// will be set to \ref INF on all arcs (i.e. the flow value will be
721 /// unbounded from above on each arc).
723 /// \param map An arc map storing the upper bounds.
724 /// Its \c Value type must be convertible to the \c Value type
725 /// of the algorithm.
727 /// \return <tt>(*this)</tt>
728 template<typename UpperMap>
729 NetworkSimplex& upperMap(const UpperMap& map) {
730 for (ArcIt a(_graph); a != INVALID; ++a) {
731 _upper[_arc_id[a]] = map[a];
736 /// \brief Set the costs of the arcs.
738 /// This function sets the costs of the arcs.
739 /// If it is not used before calling \ref run(), the costs
740 /// will be set to \c 1 on all arcs.
742 /// \param map An arc map storing the costs.
743 /// Its \c Value type must be convertible to the \c Cost type
744 /// of the algorithm.
746 /// \return <tt>(*this)</tt>
747 template<typename CostMap>
748 NetworkSimplex& costMap(const CostMap& map) {
749 for (ArcIt a(_graph); a != INVALID; ++a) {
750 _cost[_arc_id[a]] = map[a];
755 /// \brief Set the supply values of the nodes.
757 /// This function sets the supply values of the nodes.
758 /// If neither this function nor \ref stSupply() is used before
759 /// calling \ref run(), the supply of each node will be set to zero.
761 /// \param map A node map storing the supply values.
762 /// Its \c Value type must be convertible to the \c Value type
763 /// of the algorithm.
765 /// \return <tt>(*this)</tt>
766 template<typename SupplyMap>
767 NetworkSimplex& supplyMap(const SupplyMap& map) {
768 for (NodeIt n(_graph); n != INVALID; ++n) {
769 _supply[_node_id[n]] = map[n];
774 /// \brief Set single source and target nodes and a supply value.
776 /// This function sets a single source node and a single target node
777 /// and the required flow value.
778 /// If neither this function nor \ref supplyMap() is used before
779 /// calling \ref run(), the supply of each node will be set to zero.
781 /// Using this function has the same effect as using \ref supplyMap()
782 /// with such a map in which \c k is assigned to \c s, \c -k is
783 /// assigned to \c t and all other nodes have zero supply value.
785 /// \param s The source node.
786 /// \param t The target node.
787 /// \param k The required amount of flow from node \c s to node \c t
788 /// (i.e. the supply of \c s and the demand of \c t).
790 /// \return <tt>(*this)</tt>
791 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
792 for (int i = 0; i != _node_num; ++i) {
795 _supply[_node_id[s]] = k;
796 _supply[_node_id[t]] = -k;
800 /// \brief Set the type of the supply constraints.
802 /// This function sets the type of the supply/demand constraints.
803 /// If it is not used before calling \ref run(), the \ref GEQ supply
804 /// type will be used.
806 /// For more information see \ref SupplyType.
808 /// \return <tt>(*this)</tt>
809 NetworkSimplex& supplyType(SupplyType supply_type) {
810 _stype = supply_type;
816 /// \name Execution Control
817 /// The algorithm can be executed using \ref run().
821 /// \brief Run the algorithm.
823 /// This function runs the algorithm.
824 /// The paramters can be specified using functions \ref lowerMap(),
825 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
826 /// \ref supplyType().
829 /// NetworkSimplex<ListDigraph> ns(graph);
830 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
831 /// .supplyMap(sup).run();
834 /// This function can be called more than once. All the parameters
835 /// that have been given are kept for the next call, unless
836 /// \ref reset() is called, thus only the modified parameters
837 /// have to be set again. See \ref reset() for examples.
838 /// However the underlying digraph must not be modified after this
839 /// class have been constructed, since it copies and extends the graph.
841 /// \param pivot_rule The pivot rule that will be used during the
842 /// algorithm. For more information see \ref PivotRule.
844 /// \return \c INFEASIBLE if no feasible flow exists,
845 /// \n \c OPTIMAL if the problem has optimal solution
846 /// (i.e. it is feasible and bounded), and the algorithm has found
847 /// optimal flow and node potentials (primal and dual solutions),
848 /// \n \c UNBOUNDED if the objective function of the problem is
849 /// unbounded, i.e. there is a directed cycle having negative total
850 /// cost and infinite upper bound.
852 /// \see ProblemType, PivotRule
853 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
854 if (!init()) return INFEASIBLE;
855 return start(pivot_rule);
858 /// \brief Reset all the parameters that have been given before.
860 /// This function resets all the paramaters that have been given
861 /// before using functions \ref lowerMap(), \ref upperMap(),
862 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
864 /// It is useful for multiple run() calls. If this function is not
865 /// used, all the parameters given before are kept for the next
867 /// However the underlying digraph must not be modified after this
868 /// class have been constructed, since it copies and extends the graph.
872 /// NetworkSimplex<ListDigraph> ns(graph);
875 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
876 /// .supplyMap(sup).run();
878 /// // Run again with modified cost map (reset() is not called,
879 /// // so only the cost map have to be set again)
881 /// ns.costMap(cost).run();
883 /// // Run again from scratch using reset()
884 /// // (the lower bounds will be set to zero on all arcs)
886 /// ns.upperMap(capacity).costMap(cost)
887 /// .supplyMap(sup).run();
890 /// \return <tt>(*this)</tt>
891 NetworkSimplex& reset() {
892 for (int i = 0; i != _node_num; ++i) {
895 for (int i = 0; i != _arc_num; ++i) {
907 /// \name Query Functions
908 /// The results of the algorithm can be obtained using these
910 /// The \ref run() function must be called before using them.
914 /// \brief Return the total cost of the found flow.
916 /// This function returns the total cost of the found flow.
917 /// Its complexity is O(e).
919 /// \note The return type of the function can be specified as a
920 /// template parameter. For example,
922 /// ns.totalCost<double>();
924 /// It is useful if the total cost cannot be stored in the \c Cost
925 /// type of the algorithm, which is the default return type of the
928 /// \pre \ref run() must be called before using this function.
929 template <typename Number>
930 Number totalCost() const {
932 for (ArcIt a(_graph); a != INVALID; ++a) {
934 c += Number(_flow[i]) * Number(_cost[i]);
940 Cost totalCost() const {
941 return totalCost<Cost>();
945 /// \brief Return the flow on the given arc.
947 /// This function returns the flow on the given arc.
949 /// \pre \ref run() must be called before using this function.
950 Value flow(const Arc& a) const {
951 return _flow[_arc_id[a]];
954 /// \brief Return the flow map (the primal solution).
956 /// This function copies the flow value on each arc into the given
957 /// map. The \c Value type of the algorithm must be convertible to
958 /// the \c Value type of the map.
960 /// \pre \ref run() must be called before using this function.
961 template <typename FlowMap>
962 void flowMap(FlowMap &map) const {
963 for (ArcIt a(_graph); a != INVALID; ++a) {
964 map.set(a, _flow[_arc_id[a]]);
968 /// \brief Return the potential (dual value) of the given node.
970 /// This function returns the potential (dual value) of the
973 /// \pre \ref run() must be called before using this function.
974 Cost potential(const Node& n) const {
975 return _pi[_node_id[n]];
978 /// \brief Return the potential map (the dual solution).
980 /// This function copies the potential (dual value) of each node
981 /// into the given map.
982 /// The \c Cost type of the algorithm must be convertible to the
983 /// \c Value type of the map.
985 /// \pre \ref run() must be called before using this function.
986 template <typename PotentialMap>
987 void potentialMap(PotentialMap &map) const {
988 for (NodeIt n(_graph); n != INVALID; ++n) {
989 map.set(n, _pi[_node_id[n]]);
997 // Initialize internal data structures
999 if (_node_num == 0) return false;
1001 // Check the sum of supply values
1003 for (int i = 0; i != _node_num; ++i) {
1004 _sum_supply += _supply[i];
1006 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1007 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1009 // Remove non-zero lower bounds
1011 for (int i = 0; i != _arc_num; ++i) {
1012 Value c = _lower[i];
1014 _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
1016 _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
1018 _supply[_source[i]] -= c;
1019 _supply[_target[i]] += c;
1022 for (int i = 0; i != _arc_num; ++i) {
1023 _cap[i] = _upper[i];
1027 // Initialize artifical cost
1029 if (std::numeric_limits<Cost>::is_exact) {
1030 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1032 ART_COST = std::numeric_limits<Cost>::min();
1033 for (int i = 0; i != _arc_num; ++i) {
1034 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1036 ART_COST = (ART_COST + 1) * _node_num;
1039 // Initialize arc maps
1040 for (int i = 0; i != _arc_num; ++i) {
1042 _state[i] = STATE_LOWER;
1045 // Set data for the artificial root node
1047 _parent[_root] = -1;
1050 _rev_thread[0] = _root;
1051 _succ_num[_root] = _node_num + 1;
1052 _last_succ[_root] = _root - 1;
1053 _supply[_root] = -_sum_supply;
1056 // Add artificial arcs and initialize the spanning tree data structure
1057 if (_sum_supply == 0) {
1058 // EQ supply constraints
1059 _search_arc_num = _arc_num;
1060 _all_arc_num = _arc_num + _node_num;
1061 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1065 _rev_thread[u + 1] = u;
1069 _state[e] = STATE_TREE;
1070 if (_supply[u] >= 0) {
1075 _flow[e] = _supply[u];
1078 _forward[u] = false;
1082 _flow[e] = -_supply[u];
1083 _cost[e] = ART_COST;
1087 else if (_sum_supply > 0) {
1088 // LEQ supply constraints
1089 _search_arc_num = _arc_num + _node_num;
1090 int f = _arc_num + _node_num;
1091 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1094 _rev_thread[u + 1] = u;
1097 if (_supply[u] >= 0) {
1104 _flow[e] = _supply[u];
1106 _state[e] = STATE_TREE;
1108 _forward[u] = false;
1114 _flow[f] = -_supply[u];
1115 _cost[f] = ART_COST;
1116 _state[f] = STATE_TREE;
1122 _state[e] = STATE_LOWER;
1129 // GEQ supply constraints
1130 _search_arc_num = _arc_num + _node_num;
1131 int f = _arc_num + _node_num;
1132 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1135 _rev_thread[u + 1] = u;
1138 if (_supply[u] <= 0) {
1139 _forward[u] = false;
1145 _flow[e] = -_supply[u];
1147 _state[e] = STATE_TREE;
1155 _flow[f] = _supply[u];
1156 _state[f] = STATE_TREE;
1157 _cost[f] = ART_COST;
1163 _state[e] = STATE_LOWER;
1173 // Find the join node
1174 void findJoinNode() {
1175 int u = _source[in_arc];
1176 int v = _target[in_arc];
1178 if (_succ_num[u] < _succ_num[v]) {
1187 // Find the leaving arc of the cycle and returns true if the
1188 // leaving arc is not the same as the entering arc
1189 bool findLeavingArc() {
1190 // Initialize first and second nodes according to the direction
1192 if (_state[in_arc] == STATE_LOWER) {
1193 first = _source[in_arc];
1194 second = _target[in_arc];
1196 first = _target[in_arc];
1197 second = _source[in_arc];
1199 delta = _cap[in_arc];
1204 // Search the cycle along the path form the first node to the root
1205 for (int u = first; u != join; u = _parent[u]) {
1208 _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1215 // Search the cycle along the path form the second node to the root
1216 for (int u = second; u != join; u = _parent[u]) {
1219 (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1237 // Change _flow and _state vectors
1238 void changeFlow(bool change) {
1239 // Augment along the cycle
1241 Value val = _state[in_arc] * delta;
1242 _flow[in_arc] += val;
1243 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1244 _flow[_pred[u]] += _forward[u] ? -val : val;
1246 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1247 _flow[_pred[u]] += _forward[u] ? val : -val;
1250 // Update the state of the entering and leaving arcs
1252 _state[in_arc] = STATE_TREE;
1253 _state[_pred[u_out]] =
1254 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1256 _state[in_arc] = -_state[in_arc];
1260 // Update the tree structure
1261 void updateTreeStructure() {
1263 int old_rev_thread = _rev_thread[u_out];
1264 int old_succ_num = _succ_num[u_out];
1265 int old_last_succ = _last_succ[u_out];
1266 v_out = _parent[u_out];
1268 u = _last_succ[u_in]; // the last successor of u_in
1269 right = _thread[u]; // the node after it
1271 // Handle the case when old_rev_thread equals to v_in
1272 // (it also means that join and v_out coincide)
1273 if (old_rev_thread == v_in) {
1274 last = _thread[_last_succ[u_out]];
1276 last = _thread[v_in];
1279 // Update _thread and _parent along the stem nodes (i.e. the nodes
1280 // between u_in and u_out, whose parent have to be changed)
1281 _thread[v_in] = stem = u_in;
1282 _dirty_revs.clear();
1283 _dirty_revs.push_back(v_in);
1285 while (stem != u_out) {
1286 // Insert the next stem node into the thread list
1287 new_stem = _parent[stem];
1288 _thread[u] = new_stem;
1289 _dirty_revs.push_back(u);
1291 // Remove the subtree of stem from the thread list
1292 w = _rev_thread[stem];
1294 _rev_thread[right] = w;
1296 // Change the parent node and shift stem nodes
1297 _parent[stem] = par_stem;
1301 // Update u and right
1302 u = _last_succ[stem] == _last_succ[par_stem] ?
1303 _rev_thread[par_stem] : _last_succ[stem];
1306 _parent[u_out] = par_stem;
1308 _rev_thread[last] = u;
1309 _last_succ[u_out] = u;
1311 // Remove the subtree of u_out from the thread list except for
1312 // the case when old_rev_thread equals to v_in
1313 // (it also means that join and v_out coincide)
1314 if (old_rev_thread != v_in) {
1315 _thread[old_rev_thread] = right;
1316 _rev_thread[right] = old_rev_thread;
1319 // Update _rev_thread using the new _thread values
1320 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1322 _rev_thread[_thread[u]] = u;
1325 // Update _pred, _forward, _last_succ and _succ_num for the
1326 // stem nodes from u_out to u_in
1327 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1331 _pred[u] = _pred[w];
1332 _forward[u] = !_forward[w];
1333 tmp_sc += _succ_num[u] - _succ_num[w];
1334 _succ_num[u] = tmp_sc;
1335 _last_succ[w] = tmp_ls;
1338 _pred[u_in] = in_arc;
1339 _forward[u_in] = (u_in == _source[in_arc]);
1340 _succ_num[u_in] = old_succ_num;
1342 // Set limits for updating _last_succ form v_in and v_out
1344 int up_limit_in = -1;
1345 int up_limit_out = -1;
1346 if (_last_succ[join] == v_in) {
1347 up_limit_out = join;
1352 // Update _last_succ from v_in towards the root
1353 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1355 _last_succ[u] = _last_succ[u_out];
1357 // Update _last_succ from v_out towards the root
1358 if (join != old_rev_thread && v_in != old_rev_thread) {
1359 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1361 _last_succ[u] = old_rev_thread;
1364 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1366 _last_succ[u] = _last_succ[u_out];
1370 // Update _succ_num from v_in to join
1371 for (u = v_in; u != join; u = _parent[u]) {
1372 _succ_num[u] += old_succ_num;
1374 // Update _succ_num from v_out to join
1375 for (u = v_out; u != join; u = _parent[u]) {
1376 _succ_num[u] -= old_succ_num;
1380 // Update potentials
1381 void updatePotential() {
1382 Cost sigma = _forward[u_in] ?
1383 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1384 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1385 // Update potentials in the subtree, which has been moved
1386 int end = _thread[_last_succ[u_in]];
1387 for (int u = u_in; u != end; u = _thread[u]) {
1392 // Execute the algorithm
1393 ProblemType start(PivotRule pivot_rule) {
1394 // Select the pivot rule implementation
1395 switch (pivot_rule) {
1396 case FIRST_ELIGIBLE:
1397 return start<FirstEligiblePivotRule>();
1399 return start<BestEligiblePivotRule>();
1401 return start<BlockSearchPivotRule>();
1402 case CANDIDATE_LIST:
1403 return start<CandidateListPivotRule>();
1405 return start<AlteringListPivotRule>();
1407 return INFEASIBLE; // avoid warning
1410 template <typename PivotRuleImpl>
1411 ProblemType start() {
1412 PivotRuleImpl pivot(*this);
1414 // Execute the Network Simplex algorithm
1415 while (pivot.findEnteringArc()) {
1417 bool change = findLeavingArc();
1418 if (delta >= INF) return UNBOUNDED;
1421 updateTreeStructure();
1426 // Check feasibility
1427 for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1428 if (_flow[e] != 0) return INFEASIBLE;
1431 // Transform the solution and the supply map to the original form
1433 for (int i = 0; i != _arc_num; ++i) {
1434 Value c = _lower[i];
1437 _supply[_source[i]] += c;
1438 _supply[_target[i]] -= c;
1443 // Shift potentials to meet the requirements of the GEQ/LEQ type
1444 // optimality conditions
1445 if (_sum_supply == 0) {
1446 if (_stype == GEQ) {
1447 Cost max_pot = std::numeric_limits<Cost>::min();
1448 for (int i = 0; i != _node_num; ++i) {
1449 if (_pi[i] > max_pot) max_pot = _pi[i];
1452 for (int i = 0; i != _node_num; ++i)
1456 Cost min_pot = std::numeric_limits<Cost>::max();
1457 for (int i = 0; i != _node_num; ++i) {
1458 if (_pi[i] < min_pot) min_pot = _pi[i];
1461 for (int i = 0; i != _node_num; ++i)
1470 }; //class NetworkSimplex
1476 #endif //LEMON_NETWORK_SIMPLEX_H