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 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, since this form is supported
106 /// by other minimum cost flow algorithms and the \ref Circulation
107 /// algorithm, as well.
108 /// The \c LEQ problem type can be selected using the \ref supplyType()
111 /// Note that the equality form is a special case of both supply types.
114 /// This option means that there are <em>"greater or equal"</em>
115 /// supply/demand constraints in the definition, i.e. the exact
116 /// formulation of the problem is the following.
118 \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
119 \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
120 sup(u) \quad \forall u\in V \f]
121 \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
123 /// It means that the total demand must be greater or equal to the
124 /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
125 /// negative) and all the supplies have to be carried out from
126 /// the supply nodes, but there could be demands that are not
129 /// It is just an alias for the \c GEQ option.
130 CARRY_SUPPLIES = GEQ,
132 /// This option means that there are <em>"less or equal"</em>
133 /// supply/demand constraints in the definition, i.e. the exact
134 /// formulation of the problem is the following.
136 \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
137 \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
138 sup(u) \quad \forall u\in V \f]
139 \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
141 /// It means that the total demand must be less or equal to the
142 /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
143 /// positive) and all the demands have to be satisfied, but there
144 /// could be supplies that are not carried out from the supply
147 /// It is just an alias for the \c LEQ option.
148 SATISFY_DEMANDS = LEQ
151 /// \brief Constants for selecting the pivot rule.
153 /// Enum type containing constants for selecting the pivot rule for
154 /// the \ref run() function.
156 /// \ref NetworkSimplex provides five different pivot rule
157 /// implementations that significantly affect the running time
158 /// of the algorithm.
159 /// By default \ref BLOCK_SEARCH "Block Search" is used, which
160 /// proved to be the most efficient and the most robust on various
161 /// test inputs according to our benchmark tests.
162 /// However another pivot rule can be selected using the \ref run()
163 /// function with the proper parameter.
166 /// The First Eligible pivot rule.
167 /// The next eligible arc is selected in a wraparound fashion
168 /// in every iteration.
171 /// The Best Eligible pivot rule.
172 /// The best eligible arc is selected in every iteration.
175 /// The Block Search pivot rule.
176 /// A specified number of arcs are examined in every iteration
177 /// in a wraparound fashion and the best eligible arc is selected
181 /// The Candidate List pivot rule.
182 /// In a major iteration a candidate list is built from eligible arcs
183 /// in a wraparound fashion and in the following minor iterations
184 /// the best eligible arc is selected from this list.
187 /// The Altering Candidate List pivot rule.
188 /// It is a modified version of the Candidate List method.
189 /// It keeps only the several best eligible arcs from the former
190 /// candidate list and extends this list in every iteration.
196 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
198 typedef std::vector<Arc> ArcVector;
199 typedef std::vector<Node> NodeVector;
200 typedef std::vector<int> IntVector;
201 typedef std::vector<bool> BoolVector;
202 typedef std::vector<Value> ValueVector;
203 typedef std::vector<Cost> CostVector;
205 // State constants for arcs
214 // Data related to the underlying digraph
219 // Parameters of the problem
224 // Data structures for storing the digraph
239 // Data for storing the spanning tree structure
243 IntVector _rev_thread;
245 IntVector _last_succ;
246 IntVector _dirty_revs;
251 // Temporary data used in the current pivot iteration
252 int in_arc, join, u_in, v_in, u_out, v_out;
253 int first, second, right, last;
254 int stem, par_stem, new_stem;
259 /// \brief Constant for infinite upper bounds (capacities).
261 /// Constant for infinite upper bounds (capacities).
262 /// It is \c std::numeric_limits<Value>::infinity() if available,
263 /// \c std::numeric_limits<Value>::max() otherwise.
268 // Implementation of the First Eligible pivot rule
269 class FirstEligiblePivotRule
273 // References to the NetworkSimplex class
274 const IntVector &_source;
275 const IntVector &_target;
276 const CostVector &_cost;
277 const IntVector &_state;
278 const CostVector &_pi;
288 FirstEligiblePivotRule(NetworkSimplex &ns) :
289 _source(ns._source), _target(ns._target),
290 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
291 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
294 // Find next entering arc
295 bool findEnteringArc() {
297 for (int e = _next_arc; e < _arc_num; ++e) {
298 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
305 for (int e = 0; e < _next_arc; ++e) {
306 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
316 }; //class FirstEligiblePivotRule
319 // Implementation of the Best Eligible pivot rule
320 class BestEligiblePivotRule
324 // References to the NetworkSimplex class
325 const IntVector &_source;
326 const IntVector &_target;
327 const CostVector &_cost;
328 const IntVector &_state;
329 const CostVector &_pi;
336 BestEligiblePivotRule(NetworkSimplex &ns) :
337 _source(ns._source), _target(ns._target),
338 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
339 _in_arc(ns.in_arc), _arc_num(ns._arc_num)
342 // Find next entering arc
343 bool findEnteringArc() {
345 for (int e = 0; e < _arc_num; ++e) {
346 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
355 }; //class BestEligiblePivotRule
358 // Implementation of the Block Search pivot rule
359 class BlockSearchPivotRule
363 // References to the NetworkSimplex class
364 const IntVector &_source;
365 const IntVector &_target;
366 const CostVector &_cost;
367 const IntVector &_state;
368 const CostVector &_pi;
379 BlockSearchPivotRule(NetworkSimplex &ns) :
380 _source(ns._source), _target(ns._target),
381 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
382 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
384 // The main parameters of the pivot rule
385 const double BLOCK_SIZE_FACTOR = 2.0;
386 const int MIN_BLOCK_SIZE = 10;
388 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
389 std::sqrt(double(_arc_num))),
393 // Find next entering arc
394 bool findEnteringArc() {
396 int cnt = _block_size;
397 int e, min_arc = _next_arc;
398 for (e = _next_arc; e < _arc_num; ++e) {
399 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
409 if (min == 0 || cnt > 0) {
410 for (e = 0; e < _next_arc; ++e) {
411 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
422 if (min >= 0) return false;
428 }; //class BlockSearchPivotRule
431 // Implementation of the Candidate List pivot rule
432 class CandidateListPivotRule
436 // References to the NetworkSimplex class
437 const IntVector &_source;
438 const IntVector &_target;
439 const CostVector &_cost;
440 const IntVector &_state;
441 const CostVector &_pi;
446 IntVector _candidates;
447 int _list_length, _minor_limit;
448 int _curr_length, _minor_count;
454 CandidateListPivotRule(NetworkSimplex &ns) :
455 _source(ns._source), _target(ns._target),
456 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
457 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
459 // The main parameters of the pivot rule
460 const double LIST_LENGTH_FACTOR = 1.0;
461 const int MIN_LIST_LENGTH = 10;
462 const double MINOR_LIMIT_FACTOR = 0.1;
463 const int MIN_MINOR_LIMIT = 3;
465 _list_length = std::max( int(LIST_LENGTH_FACTOR *
466 std::sqrt(double(_arc_num))),
468 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
470 _curr_length = _minor_count = 0;
471 _candidates.resize(_list_length);
474 /// Find next entering arc
475 bool findEnteringArc() {
477 int e, min_arc = _next_arc;
478 if (_curr_length > 0 && _minor_count < _minor_limit) {
479 // Minor iteration: select the best eligible arc from the
480 // current candidate list
483 for (int i = 0; i < _curr_length; ++i) {
485 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
491 _candidates[i--] = _candidates[--_curr_length];
500 // Major iteration: build a new candidate list
503 for (e = _next_arc; e < _arc_num; ++e) {
504 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
506 _candidates[_curr_length++] = e;
511 if (_curr_length == _list_length) break;
514 if (_curr_length < _list_length) {
515 for (e = 0; e < _next_arc; ++e) {
516 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
518 _candidates[_curr_length++] = e;
523 if (_curr_length == _list_length) break;
527 if (_curr_length == 0) return false;
534 }; //class CandidateListPivotRule
537 // Implementation of the Altering Candidate List pivot rule
538 class AlteringListPivotRule
542 // References to the NetworkSimplex class
543 const IntVector &_source;
544 const IntVector &_target;
545 const CostVector &_cost;
546 const IntVector &_state;
547 const CostVector &_pi;
552 int _block_size, _head_length, _curr_length;
554 IntVector _candidates;
555 CostVector _cand_cost;
557 // Functor class to compare arcs during sort of the candidate list
561 const CostVector &_map;
563 SortFunc(const CostVector &map) : _map(map) {}
564 bool operator()(int left, int right) {
565 return _map[left] > _map[right];
574 AlteringListPivotRule(NetworkSimplex &ns) :
575 _source(ns._source), _target(ns._target),
576 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
577 _in_arc(ns.in_arc), _arc_num(ns._arc_num),
578 _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
580 // The main parameters of the pivot rule
581 const double BLOCK_SIZE_FACTOR = 1.5;
582 const int MIN_BLOCK_SIZE = 10;
583 const double HEAD_LENGTH_FACTOR = 0.1;
584 const int MIN_HEAD_LENGTH = 3;
586 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
587 std::sqrt(double(_arc_num))),
589 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
591 _candidates.resize(_head_length + _block_size);
595 // Find next entering arc
596 bool findEnteringArc() {
597 // Check the current candidate list
599 for (int i = 0; i < _curr_length; ++i) {
601 _cand_cost[e] = _state[e] *
602 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
603 if (_cand_cost[e] >= 0) {
604 _candidates[i--] = _candidates[--_curr_length];
609 int cnt = _block_size;
611 int limit = _head_length;
613 for (int e = _next_arc; e < _arc_num; ++e) {
614 _cand_cost[e] = _state[e] *
615 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
616 if (_cand_cost[e] < 0) {
617 _candidates[_curr_length++] = e;
621 if (_curr_length > limit) break;
626 if (_curr_length <= limit) {
627 for (int e = 0; e < _next_arc; ++e) {
628 _cand_cost[e] = _state[e] *
629 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
630 if (_cand_cost[e] < 0) {
631 _candidates[_curr_length++] = e;
635 if (_curr_length > limit) break;
641 if (_curr_length == 0) return false;
642 _next_arc = last_arc + 1;
644 // Make heap of the candidate list (approximating a partial sort)
645 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
648 // Pop the first element of the heap
649 _in_arc = _candidates[0];
650 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
652 _curr_length = std::min(_head_length, _curr_length - 1);
656 }; //class AlteringListPivotRule
660 /// \brief Constructor.
662 /// The constructor of the class.
664 /// \param graph The digraph the algorithm runs on.
665 NetworkSimplex(const GR& graph) :
666 _graph(graph), _node_id(graph), _arc_id(graph),
667 INF(std::numeric_limits<Value>::has_infinity ?
668 std::numeric_limits<Value>::infinity() :
669 std::numeric_limits<Value>::max())
671 // Check the value types
672 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
673 "The flow type of NetworkSimplex must be signed");
674 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
675 "The cost type of NetworkSimplex must be signed");
678 _node_num = countNodes(_graph);
679 _arc_num = countArcs(_graph);
680 int all_node_num = _node_num + 1;
681 int all_arc_num = _arc_num + _node_num;
683 _source.resize(all_arc_num);
684 _target.resize(all_arc_num);
686 _lower.resize(all_arc_num);
687 _upper.resize(all_arc_num);
688 _cap.resize(all_arc_num);
689 _cost.resize(all_arc_num);
690 _supply.resize(all_node_num);
691 _flow.resize(all_arc_num);
692 _pi.resize(all_node_num);
694 _parent.resize(all_node_num);
695 _pred.resize(all_node_num);
696 _forward.resize(all_node_num);
697 _thread.resize(all_node_num);
698 _rev_thread.resize(all_node_num);
699 _succ_num.resize(all_node_num);
700 _last_succ.resize(all_node_num);
701 _state.resize(all_arc_num);
703 // Copy the graph (store the arcs in a mixed order)
705 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
708 int k = std::max(int(std::sqrt(double(_arc_num))), 10);
710 for (ArcIt a(_graph); a != INVALID; ++a) {
712 _source[i] = _node_id[_graph.source(a)];
713 _target[i] = _node_id[_graph.target(a)];
714 if ((i += k) >= _arc_num) i = (i % k) + 1;
718 for (int i = 0; i != _node_num; ++i) {
721 for (int i = 0; i != _arc_num; ++i) {
731 /// The parameters of the algorithm can be specified using these
736 /// \brief Set the lower bounds on the arcs.
738 /// This function sets the lower bounds on the arcs.
739 /// If it is not used before calling \ref run(), the lower bounds
740 /// will be set to zero on all arcs.
742 /// \param map An arc map storing the lower bounds.
743 /// Its \c Value type must be convertible to the \c Value type
744 /// of the algorithm.
746 /// \return <tt>(*this)</tt>
747 template <typename LowerMap>
748 NetworkSimplex& lowerMap(const LowerMap& map) {
750 for (ArcIt a(_graph); a != INVALID; ++a) {
751 _lower[_arc_id[a]] = map[a];
756 /// \brief Set the upper bounds (capacities) on the arcs.
758 /// This function sets the upper bounds (capacities) on the arcs.
759 /// If it is not used before calling \ref run(), the upper bounds
760 /// will be set to \ref INF on all arcs (i.e. the flow value will be
761 /// unbounded from above on each arc).
763 /// \param map An arc map storing the upper bounds.
764 /// Its \c Value type must be convertible to the \c Value type
765 /// of the algorithm.
767 /// \return <tt>(*this)</tt>
768 template<typename UpperMap>
769 NetworkSimplex& upperMap(const UpperMap& map) {
770 for (ArcIt a(_graph); a != INVALID; ++a) {
771 _upper[_arc_id[a]] = map[a];
776 /// \brief Set the costs of the arcs.
778 /// This function sets the costs of the arcs.
779 /// If it is not used before calling \ref run(), the costs
780 /// will be set to \c 1 on all arcs.
782 /// \param map An arc map storing the costs.
783 /// Its \c Value type must be convertible to the \c Cost type
784 /// of the algorithm.
786 /// \return <tt>(*this)</tt>
787 template<typename CostMap>
788 NetworkSimplex& costMap(const CostMap& map) {
789 for (ArcIt a(_graph); a != INVALID; ++a) {
790 _cost[_arc_id[a]] = map[a];
795 /// \brief Set the supply values of the nodes.
797 /// This function sets the supply values of the nodes.
798 /// If neither this function nor \ref stSupply() is used before
799 /// calling \ref run(), the supply of each node will be set to zero.
800 /// (It makes sense only if non-zero lower bounds are given.)
802 /// \param map A node map storing the supply values.
803 /// Its \c Value type must be convertible to the \c Value type
804 /// of the algorithm.
806 /// \return <tt>(*this)</tt>
807 template<typename SupplyMap>
808 NetworkSimplex& supplyMap(const SupplyMap& map) {
809 for (NodeIt n(_graph); n != INVALID; ++n) {
810 _supply[_node_id[n]] = map[n];
815 /// \brief Set single source and target nodes and a supply value.
817 /// This function sets a single source node and a single target node
818 /// and the required flow value.
819 /// If neither this function nor \ref supplyMap() is used before
820 /// calling \ref run(), the supply of each node will be set to zero.
821 /// (It makes sense only if non-zero lower bounds are given.)
823 /// Using this function has the same effect as using \ref supplyMap()
824 /// with such a map in which \c k is assigned to \c s, \c -k is
825 /// assigned to \c t and all other nodes have zero supply value.
827 /// \param s The source node.
828 /// \param t The target node.
829 /// \param k The required amount of flow from node \c s to node \c t
830 /// (i.e. the supply of \c s and the demand of \c t).
832 /// \return <tt>(*this)</tt>
833 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
834 for (int i = 0; i != _node_num; ++i) {
837 _supply[_node_id[s]] = k;
838 _supply[_node_id[t]] = -k;
842 /// \brief Set the type of the supply constraints.
844 /// This function sets the type of the supply/demand constraints.
845 /// If it is not used before calling \ref run(), the \ref GEQ supply
846 /// type will be used.
848 /// For more information see \ref SupplyType.
850 /// \return <tt>(*this)</tt>
851 NetworkSimplex& supplyType(SupplyType supply_type) {
852 _stype = supply_type;
858 /// \name Execution Control
859 /// The algorithm can be executed using \ref run().
863 /// \brief Run the algorithm.
865 /// This function runs the algorithm.
866 /// The paramters can be specified using functions \ref lowerMap(),
867 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
868 /// \ref supplyType().
871 /// NetworkSimplex<ListDigraph> ns(graph);
872 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
873 /// .supplyMap(sup).run();
876 /// This function can be called more than once. All the parameters
877 /// that have been given are kept for the next call, unless
878 /// \ref reset() is called, thus only the modified parameters
879 /// have to be set again. See \ref reset() for examples.
880 /// However the underlying digraph must not be modified after this
881 /// class have been constructed, since it copies and extends the graph.
883 /// \param pivot_rule The pivot rule that will be used during the
884 /// algorithm. For more information see \ref PivotRule.
886 /// \return \c INFEASIBLE if no feasible flow exists,
887 /// \n \c OPTIMAL if the problem has optimal solution
888 /// (i.e. it is feasible and bounded), and the algorithm has found
889 /// optimal flow and node potentials (primal and dual solutions),
890 /// \n \c UNBOUNDED if the objective function of the problem is
891 /// unbounded, i.e. there is a directed cycle having negative total
892 /// cost and infinite upper bound.
894 /// \see ProblemType, PivotRule
895 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
896 if (!init()) return INFEASIBLE;
897 return start(pivot_rule);
900 /// \brief Reset all the parameters that have been given before.
902 /// This function resets all the paramaters that have been given
903 /// before using functions \ref lowerMap(), \ref upperMap(),
904 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
906 /// It is useful for multiple run() calls. If this function is not
907 /// used, all the parameters given before are kept for the next
909 /// However the underlying digraph must not be modified after this
910 /// class have been constructed, since it copies and extends the graph.
914 /// NetworkSimplex<ListDigraph> ns(graph);
917 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
918 /// .supplyMap(sup).run();
920 /// // Run again with modified cost map (reset() is not called,
921 /// // so only the cost map have to be set again)
923 /// ns.costMap(cost).run();
925 /// // Run again from scratch using reset()
926 /// // (the lower bounds will be set to zero on all arcs)
928 /// ns.upperMap(capacity).costMap(cost)
929 /// .supplyMap(sup).run();
932 /// \return <tt>(*this)</tt>
933 NetworkSimplex& reset() {
934 for (int i = 0; i != _node_num; ++i) {
937 for (int i = 0; i != _arc_num; ++i) {
949 /// \name Query Functions
950 /// The results of the algorithm can be obtained using these
952 /// The \ref run() function must be called before using them.
956 /// \brief Return the total cost of the found flow.
958 /// This function returns the total cost of the found flow.
959 /// Its complexity is O(e).
961 /// \note The return type of the function can be specified as a
962 /// template parameter. For example,
964 /// ns.totalCost<double>();
966 /// It is useful if the total cost cannot be stored in the \c Cost
967 /// type of the algorithm, which is the default return type of the
970 /// \pre \ref run() must be called before using this function.
971 template <typename Number>
972 Number totalCost() const {
974 for (ArcIt a(_graph); a != INVALID; ++a) {
976 c += Number(_flow[i]) * Number(_cost[i]);
982 Cost totalCost() const {
983 return totalCost<Cost>();
987 /// \brief Return the flow on the given arc.
989 /// This function returns the flow on the given arc.
991 /// \pre \ref run() must be called before using this function.
992 Value flow(const Arc& a) const {
993 return _flow[_arc_id[a]];
996 /// \brief Return the flow map (the primal solution).
998 /// This function copies the flow value on each arc into the given
999 /// map. The \c Value type of the algorithm must be convertible to
1000 /// the \c Value type of the map.
1002 /// \pre \ref run() must be called before using this function.
1003 template <typename FlowMap>
1004 void flowMap(FlowMap &map) const {
1005 for (ArcIt a(_graph); a != INVALID; ++a) {
1006 map.set(a, _flow[_arc_id[a]]);
1010 /// \brief Return the potential (dual value) of the given node.
1012 /// This function returns the potential (dual value) of the
1015 /// \pre \ref run() must be called before using this function.
1016 Cost potential(const Node& n) const {
1017 return _pi[_node_id[n]];
1020 /// \brief Return the potential map (the dual solution).
1022 /// This function copies the potential (dual value) of each node
1023 /// into the given map.
1024 /// The \c Cost type of the algorithm must be convertible to the
1025 /// \c Value type of the map.
1027 /// \pre \ref run() must be called before using this function.
1028 template <typename PotentialMap>
1029 void potentialMap(PotentialMap &map) const {
1030 for (NodeIt n(_graph); n != INVALID; ++n) {
1031 map.set(n, _pi[_node_id[n]]);
1039 // Initialize internal data structures
1041 if (_node_num == 0) return false;
1043 // Check the sum of supply values
1045 for (int i = 0; i != _node_num; ++i) {
1046 _sum_supply += _supply[i];
1048 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1049 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1051 // Remove non-zero lower bounds
1053 for (int i = 0; i != _arc_num; ++i) {
1054 Value c = _lower[i];
1056 _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
1058 _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
1060 _supply[_source[i]] -= c;
1061 _supply[_target[i]] += c;
1064 for (int i = 0; i != _arc_num; ++i) {
1065 _cap[i] = _upper[i];
1069 // Initialize artifical cost
1071 if (std::numeric_limits<Cost>::is_exact) {
1072 ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
1074 ART_COST = std::numeric_limits<Cost>::min();
1075 for (int i = 0; i != _arc_num; ++i) {
1076 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1078 ART_COST = (ART_COST + 1) * _node_num;
1081 // Initialize arc maps
1082 for (int i = 0; i != _arc_num; ++i) {
1084 _state[i] = STATE_LOWER;
1087 // Set data for the artificial root node
1089 _parent[_root] = -1;
1092 _rev_thread[0] = _root;
1093 _succ_num[_root] = _node_num + 1;
1094 _last_succ[_root] = _root - 1;
1095 _supply[_root] = -_sum_supply;
1096 _pi[_root] = _sum_supply < 0 ? -ART_COST : ART_COST;
1098 // Add artificial arcs and initialize the spanning tree data structure
1099 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1103 _rev_thread[u + 1] = u;
1106 _cost[e] = ART_COST;
1108 _state[e] = STATE_TREE;
1109 if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
1110 _flow[e] = _supply[u];
1112 _pi[u] = -ART_COST + _pi[_root];
1114 _flow[e] = -_supply[u];
1115 _forward[u] = false;
1116 _pi[u] = ART_COST + _pi[_root];
1123 // Find the join node
1124 void findJoinNode() {
1125 int u = _source[in_arc];
1126 int v = _target[in_arc];
1128 if (_succ_num[u] < _succ_num[v]) {
1137 // Find the leaving arc of the cycle and returns true if the
1138 // leaving arc is not the same as the entering arc
1139 bool findLeavingArc() {
1140 // Initialize first and second nodes according to the direction
1142 if (_state[in_arc] == STATE_LOWER) {
1143 first = _source[in_arc];
1144 second = _target[in_arc];
1146 first = _target[in_arc];
1147 second = _source[in_arc];
1149 delta = _cap[in_arc];
1154 // Search the cycle along the path form the first node to the root
1155 for (int u = first; u != join; u = _parent[u]) {
1158 _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1165 // Search the cycle along the path form the second node to the root
1166 for (int u = second; u != join; u = _parent[u]) {
1169 (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1187 // Change _flow and _state vectors
1188 void changeFlow(bool change) {
1189 // Augment along the cycle
1191 Value val = _state[in_arc] * delta;
1192 _flow[in_arc] += val;
1193 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1194 _flow[_pred[u]] += _forward[u] ? -val : val;
1196 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1197 _flow[_pred[u]] += _forward[u] ? val : -val;
1200 // Update the state of the entering and leaving arcs
1202 _state[in_arc] = STATE_TREE;
1203 _state[_pred[u_out]] =
1204 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1206 _state[in_arc] = -_state[in_arc];
1210 // Update the tree structure
1211 void updateTreeStructure() {
1213 int old_rev_thread = _rev_thread[u_out];
1214 int old_succ_num = _succ_num[u_out];
1215 int old_last_succ = _last_succ[u_out];
1216 v_out = _parent[u_out];
1218 u = _last_succ[u_in]; // the last successor of u_in
1219 right = _thread[u]; // the node after it
1221 // Handle the case when old_rev_thread equals to v_in
1222 // (it also means that join and v_out coincide)
1223 if (old_rev_thread == v_in) {
1224 last = _thread[_last_succ[u_out]];
1226 last = _thread[v_in];
1229 // Update _thread and _parent along the stem nodes (i.e. the nodes
1230 // between u_in and u_out, whose parent have to be changed)
1231 _thread[v_in] = stem = u_in;
1232 _dirty_revs.clear();
1233 _dirty_revs.push_back(v_in);
1235 while (stem != u_out) {
1236 // Insert the next stem node into the thread list
1237 new_stem = _parent[stem];
1238 _thread[u] = new_stem;
1239 _dirty_revs.push_back(u);
1241 // Remove the subtree of stem from the thread list
1242 w = _rev_thread[stem];
1244 _rev_thread[right] = w;
1246 // Change the parent node and shift stem nodes
1247 _parent[stem] = par_stem;
1251 // Update u and right
1252 u = _last_succ[stem] == _last_succ[par_stem] ?
1253 _rev_thread[par_stem] : _last_succ[stem];
1256 _parent[u_out] = par_stem;
1258 _rev_thread[last] = u;
1259 _last_succ[u_out] = u;
1261 // Remove the subtree of u_out from the thread list except for
1262 // the case when old_rev_thread equals to v_in
1263 // (it also means that join and v_out coincide)
1264 if (old_rev_thread != v_in) {
1265 _thread[old_rev_thread] = right;
1266 _rev_thread[right] = old_rev_thread;
1269 // Update _rev_thread using the new _thread values
1270 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1272 _rev_thread[_thread[u]] = u;
1275 // Update _pred, _forward, _last_succ and _succ_num for the
1276 // stem nodes from u_out to u_in
1277 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1281 _pred[u] = _pred[w];
1282 _forward[u] = !_forward[w];
1283 tmp_sc += _succ_num[u] - _succ_num[w];
1284 _succ_num[u] = tmp_sc;
1285 _last_succ[w] = tmp_ls;
1288 _pred[u_in] = in_arc;
1289 _forward[u_in] = (u_in == _source[in_arc]);
1290 _succ_num[u_in] = old_succ_num;
1292 // Set limits for updating _last_succ form v_in and v_out
1294 int up_limit_in = -1;
1295 int up_limit_out = -1;
1296 if (_last_succ[join] == v_in) {
1297 up_limit_out = join;
1302 // Update _last_succ from v_in towards the root
1303 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1305 _last_succ[u] = _last_succ[u_out];
1307 // Update _last_succ from v_out towards the root
1308 if (join != old_rev_thread && v_in != old_rev_thread) {
1309 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1311 _last_succ[u] = old_rev_thread;
1314 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1316 _last_succ[u] = _last_succ[u_out];
1320 // Update _succ_num from v_in to join
1321 for (u = v_in; u != join; u = _parent[u]) {
1322 _succ_num[u] += old_succ_num;
1324 // Update _succ_num from v_out to join
1325 for (u = v_out; u != join; u = _parent[u]) {
1326 _succ_num[u] -= old_succ_num;
1330 // Update potentials
1331 void updatePotential() {
1332 Cost sigma = _forward[u_in] ?
1333 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1334 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1335 // Update potentials in the subtree, which has been moved
1336 int end = _thread[_last_succ[u_in]];
1337 for (int u = u_in; u != end; u = _thread[u]) {
1342 // Execute the algorithm
1343 ProblemType start(PivotRule pivot_rule) {
1344 // Select the pivot rule implementation
1345 switch (pivot_rule) {
1346 case FIRST_ELIGIBLE:
1347 return start<FirstEligiblePivotRule>();
1349 return start<BestEligiblePivotRule>();
1351 return start<BlockSearchPivotRule>();
1352 case CANDIDATE_LIST:
1353 return start<CandidateListPivotRule>();
1355 return start<AlteringListPivotRule>();
1357 return INFEASIBLE; // avoid warning
1360 template <typename PivotRuleImpl>
1361 ProblemType start() {
1362 PivotRuleImpl pivot(*this);
1364 // Execute the Network Simplex algorithm
1365 while (pivot.findEnteringArc()) {
1367 bool change = findLeavingArc();
1368 if (delta >= INF) return UNBOUNDED;
1371 updateTreeStructure();
1376 // Check feasibility
1377 if (_sum_supply < 0) {
1378 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1379 if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
1382 else if (_sum_supply > 0) {
1383 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1384 if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
1388 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1389 if (_flow[e] != 0) return INFEASIBLE;
1393 // Transform the solution and the supply map to the original form
1395 for (int i = 0; i != _arc_num; ++i) {
1396 Value c = _lower[i];
1399 _supply[_source[i]] += c;
1400 _supply[_target[i]] -= c;
1408 }; //class NetworkSimplex
1414 #endif //LEMON_NETWORK_SIMPLEX_H