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<Arc> ArcVector;
165 typedef std::vector<Node> NodeVector;
166 typedef std::vector<int> IntVector;
167 typedef std::vector<bool> BoolVector;
168 typedef std::vector<Value> ValueVector;
169 typedef std::vector<Cost> CostVector;
171 // State constants for arcs
180 // Data related to the underlying digraph
187 // Parameters of the problem
192 // Data structures for storing the digraph
207 // Data for storing the spanning tree structure
211 IntVector _rev_thread;
213 IntVector _last_succ;
214 IntVector _dirty_revs;
219 // Temporary data used in the current pivot iteration
220 int in_arc, join, u_in, v_in, u_out, v_out;
221 int first, second, right, last;
222 int stem, par_stem, new_stem;
227 /// \brief Constant for infinite upper bounds (capacities).
229 /// Constant for infinite upper bounds (capacities).
230 /// It is \c std::numeric_limits<Value>::infinity() if available,
231 /// \c std::numeric_limits<Value>::max() otherwise.
236 // Implementation of the First Eligible pivot rule
237 class FirstEligiblePivotRule
241 // References to the NetworkSimplex class
242 const IntVector &_source;
243 const IntVector &_target;
244 const CostVector &_cost;
245 const IntVector &_state;
246 const CostVector &_pi;
256 FirstEligiblePivotRule(NetworkSimplex &ns) :
257 _source(ns._source), _target(ns._target),
258 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
259 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
263 // Find next entering arc
264 bool findEnteringArc() {
266 for (int e = _next_arc; e < _search_arc_num; ++e) {
267 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
274 for (int e = 0; e < _next_arc; ++e) {
275 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
285 }; //class FirstEligiblePivotRule
288 // Implementation of the Best Eligible pivot rule
289 class BestEligiblePivotRule
293 // References to the NetworkSimplex class
294 const IntVector &_source;
295 const IntVector &_target;
296 const CostVector &_cost;
297 const IntVector &_state;
298 const CostVector &_pi;
305 BestEligiblePivotRule(NetworkSimplex &ns) :
306 _source(ns._source), _target(ns._target),
307 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
308 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
311 // Find next entering arc
312 bool findEnteringArc() {
314 for (int e = 0; e < _search_arc_num; ++e) {
315 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
324 }; //class BestEligiblePivotRule
327 // Implementation of the Block Search pivot rule
328 class BlockSearchPivotRule
332 // References to the NetworkSimplex class
333 const IntVector &_source;
334 const IntVector &_target;
335 const CostVector &_cost;
336 const IntVector &_state;
337 const CostVector &_pi;
348 BlockSearchPivotRule(NetworkSimplex &ns) :
349 _source(ns._source), _target(ns._target),
350 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
351 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
354 // The main parameters of the pivot rule
355 const double BLOCK_SIZE_FACTOR = 0.5;
356 const int MIN_BLOCK_SIZE = 10;
358 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
359 std::sqrt(double(_search_arc_num))),
363 // Find next entering arc
364 bool findEnteringArc() {
366 int cnt = _block_size;
368 for (e = _next_arc; e < _search_arc_num; ++e) {
369 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
375 if (min < 0) goto search_end;
379 for (e = 0; e < _next_arc; ++e) {
380 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
386 if (min < 0) goto search_end;
390 if (min >= 0) return false;
397 }; //class BlockSearchPivotRule
400 // Implementation of the Candidate List pivot rule
401 class CandidateListPivotRule
405 // References to the NetworkSimplex class
406 const IntVector &_source;
407 const IntVector &_target;
408 const CostVector &_cost;
409 const IntVector &_state;
410 const CostVector &_pi;
415 IntVector _candidates;
416 int _list_length, _minor_limit;
417 int _curr_length, _minor_count;
423 CandidateListPivotRule(NetworkSimplex &ns) :
424 _source(ns._source), _target(ns._target),
425 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
426 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
429 // The main parameters of the pivot rule
430 const double LIST_LENGTH_FACTOR = 0.25;
431 const int MIN_LIST_LENGTH = 10;
432 const double MINOR_LIMIT_FACTOR = 0.1;
433 const int MIN_MINOR_LIMIT = 3;
435 _list_length = std::max( int(LIST_LENGTH_FACTOR *
436 std::sqrt(double(_search_arc_num))),
438 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
440 _curr_length = _minor_count = 0;
441 _candidates.resize(_list_length);
444 /// Find next entering arc
445 bool findEnteringArc() {
448 if (_curr_length > 0 && _minor_count < _minor_limit) {
449 // Minor iteration: select the best eligible arc from the
450 // current candidate list
453 for (int i = 0; i < _curr_length; ++i) {
455 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
461 _candidates[i--] = _candidates[--_curr_length];
464 if (min < 0) return true;
467 // Major iteration: build a new candidate list
470 for (e = _next_arc; e < _search_arc_num; ++e) {
471 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
473 _candidates[_curr_length++] = e;
478 if (_curr_length == _list_length) goto search_end;
481 for (e = 0; e < _next_arc; ++e) {
482 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
484 _candidates[_curr_length++] = e;
489 if (_curr_length == _list_length) goto search_end;
492 if (_curr_length == 0) return false;
500 }; //class CandidateListPivotRule
503 // Implementation of the Altering Candidate List pivot rule
504 class AlteringListPivotRule
508 // References to the NetworkSimplex class
509 const IntVector &_source;
510 const IntVector &_target;
511 const CostVector &_cost;
512 const IntVector &_state;
513 const CostVector &_pi;
518 int _block_size, _head_length, _curr_length;
520 IntVector _candidates;
521 CostVector _cand_cost;
523 // Functor class to compare arcs during sort of the candidate list
527 const CostVector &_map;
529 SortFunc(const CostVector &map) : _map(map) {}
530 bool operator()(int left, int right) {
531 return _map[left] > _map[right];
540 AlteringListPivotRule(NetworkSimplex &ns) :
541 _source(ns._source), _target(ns._target),
542 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
543 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
544 _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
546 // The main parameters of the pivot rule
547 const double BLOCK_SIZE_FACTOR = 1.0;
548 const int MIN_BLOCK_SIZE = 10;
549 const double HEAD_LENGTH_FACTOR = 0.1;
550 const int MIN_HEAD_LENGTH = 3;
552 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
553 std::sqrt(double(_search_arc_num))),
555 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
557 _candidates.resize(_head_length + _block_size);
561 // Find next entering arc
562 bool findEnteringArc() {
563 // Check the current candidate list
565 for (int i = 0; i < _curr_length; ++i) {
567 _cand_cost[e] = _state[e] *
568 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
569 if (_cand_cost[e] >= 0) {
570 _candidates[i--] = _candidates[--_curr_length];
575 int cnt = _block_size;
576 int limit = _head_length;
578 for (e = _next_arc; e < _search_arc_num; ++e) {
579 _cand_cost[e] = _state[e] *
580 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
581 if (_cand_cost[e] < 0) {
582 _candidates[_curr_length++] = e;
585 if (_curr_length > limit) goto search_end;
590 for (e = 0; e < _next_arc; ++e) {
591 _cand_cost[e] = _state[e] *
592 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
593 if (_cand_cost[e] < 0) {
594 _candidates[_curr_length++] = e;
597 if (_curr_length > limit) goto search_end;
602 if (_curr_length == 0) return false;
606 // Make heap of the candidate list (approximating a partial sort)
607 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
610 // Pop the first element of the heap
611 _in_arc = _candidates[0];
613 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
615 _curr_length = std::min(_head_length, _curr_length - 1);
619 }; //class AlteringListPivotRule
623 /// \brief Constructor.
625 /// The constructor of the class.
627 /// \param graph The digraph the algorithm runs on.
628 NetworkSimplex(const GR& graph) :
629 _graph(graph), _node_id(graph), _arc_id(graph),
630 INF(std::numeric_limits<Value>::has_infinity ?
631 std::numeric_limits<Value>::infinity() :
632 std::numeric_limits<Value>::max())
634 // Check the value types
635 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
636 "The flow type of NetworkSimplex must be signed");
637 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
638 "The cost type of NetworkSimplex must be signed");
641 _node_num = countNodes(_graph);
642 _arc_num = countArcs(_graph);
643 int all_node_num = _node_num + 1;
644 int max_arc_num = _arc_num + 2 * _node_num;
646 _source.resize(max_arc_num);
647 _target.resize(max_arc_num);
649 _lower.resize(_arc_num);
650 _upper.resize(_arc_num);
651 _cap.resize(max_arc_num);
652 _cost.resize(max_arc_num);
653 _supply.resize(all_node_num);
654 _flow.resize(max_arc_num);
655 _pi.resize(all_node_num);
657 _parent.resize(all_node_num);
658 _pred.resize(all_node_num);
659 _forward.resize(all_node_num);
660 _thread.resize(all_node_num);
661 _rev_thread.resize(all_node_num);
662 _succ_num.resize(all_node_num);
663 _last_succ.resize(all_node_num);
664 _state.resize(max_arc_num);
666 // Copy the graph (store the arcs in a mixed order)
668 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
671 int k = std::max(int(std::sqrt(double(_arc_num))), 10);
673 for (ArcIt a(_graph); a != INVALID; ++a) {
675 _source[i] = _node_id[_graph.source(a)];
676 _target[i] = _node_id[_graph.target(a)];
677 if ((i += k) >= _arc_num) i = (i % k) + 1;
681 for (int i = 0; i != _node_num; ++i) {
684 for (int i = 0; i != _arc_num; ++i) {
694 /// The parameters of the algorithm can be specified using these
699 /// \brief Set the lower bounds on the arcs.
701 /// This function sets the lower bounds on the arcs.
702 /// If it is not used before calling \ref run(), the lower bounds
703 /// will be set to zero on all arcs.
705 /// \param map An arc map storing the lower bounds.
706 /// Its \c Value type must be convertible to the \c Value type
707 /// of the algorithm.
709 /// \return <tt>(*this)</tt>
710 template <typename LowerMap>
711 NetworkSimplex& lowerMap(const LowerMap& map) {
713 for (ArcIt a(_graph); a != INVALID; ++a) {
714 _lower[_arc_id[a]] = map[a];
719 /// \brief Set the upper bounds (capacities) on the arcs.
721 /// This function sets the upper bounds (capacities) on the arcs.
722 /// If it is not used before calling \ref run(), the upper bounds
723 /// will be set to \ref INF on all arcs (i.e. the flow value will be
724 /// unbounded from above on each arc).
726 /// \param map An arc map storing the upper bounds.
727 /// Its \c Value type must be convertible to the \c Value type
728 /// of the algorithm.
730 /// \return <tt>(*this)</tt>
731 template<typename UpperMap>
732 NetworkSimplex& upperMap(const UpperMap& map) {
733 for (ArcIt a(_graph); a != INVALID; ++a) {
734 _upper[_arc_id[a]] = map[a];
739 /// \brief Set the costs of the arcs.
741 /// This function sets the costs of the arcs.
742 /// If it is not used before calling \ref run(), the costs
743 /// will be set to \c 1 on all arcs.
745 /// \param map An arc map storing the costs.
746 /// Its \c Value type must be convertible to the \c Cost type
747 /// of the algorithm.
749 /// \return <tt>(*this)</tt>
750 template<typename CostMap>
751 NetworkSimplex& costMap(const CostMap& map) {
752 for (ArcIt a(_graph); a != INVALID; ++a) {
753 _cost[_arc_id[a]] = map[a];
758 /// \brief Set the supply values of the nodes.
760 /// This function sets the supply values of the nodes.
761 /// If neither this function nor \ref stSupply() is used before
762 /// calling \ref run(), the supply of each node will be set to zero.
763 /// (It makes sense only if non-zero lower bounds are given.)
765 /// \param map A node map storing the supply values.
766 /// Its \c Value type must be convertible to the \c Value type
767 /// of the algorithm.
769 /// \return <tt>(*this)</tt>
770 template<typename SupplyMap>
771 NetworkSimplex& supplyMap(const SupplyMap& map) {
772 for (NodeIt n(_graph); n != INVALID; ++n) {
773 _supply[_node_id[n]] = map[n];
778 /// \brief Set single source and target nodes and a supply value.
780 /// This function sets a single source node and a single target node
781 /// and the required flow value.
782 /// If neither this function nor \ref supplyMap() is used before
783 /// calling \ref run(), the supply of each node will be set to zero.
784 /// (It makes sense only if non-zero lower bounds are given.)
786 /// Using this function has the same effect as using \ref supplyMap()
787 /// with such a map in which \c k is assigned to \c s, \c -k is
788 /// assigned to \c t and all other nodes have zero supply value.
790 /// \param s The source node.
791 /// \param t The target node.
792 /// \param k The required amount of flow from node \c s to node \c t
793 /// (i.e. the supply of \c s and the demand of \c t).
795 /// \return <tt>(*this)</tt>
796 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
797 for (int i = 0; i != _node_num; ++i) {
800 _supply[_node_id[s]] = k;
801 _supply[_node_id[t]] = -k;
805 /// \brief Set the type of the supply constraints.
807 /// This function sets the type of the supply/demand constraints.
808 /// If it is not used before calling \ref run(), the \ref GEQ supply
809 /// type will be used.
811 /// For more information see \ref SupplyType.
813 /// \return <tt>(*this)</tt>
814 NetworkSimplex& supplyType(SupplyType supply_type) {
815 _stype = supply_type;
821 /// \name Execution Control
822 /// The algorithm can be executed using \ref run().
826 /// \brief Run the algorithm.
828 /// This function runs the algorithm.
829 /// The paramters can be specified using functions \ref lowerMap(),
830 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
831 /// \ref supplyType().
834 /// NetworkSimplex<ListDigraph> ns(graph);
835 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
836 /// .supplyMap(sup).run();
839 /// This function can be called more than once. All the parameters
840 /// that have been given are kept for the next call, unless
841 /// \ref reset() is called, thus only the modified parameters
842 /// have to be set again. See \ref reset() for examples.
843 /// However the underlying digraph must not be modified after this
844 /// class have been constructed, since it copies and extends the graph.
846 /// \param pivot_rule The pivot rule that will be used during the
847 /// algorithm. For more information see \ref PivotRule.
849 /// \return \c INFEASIBLE if no feasible flow exists,
850 /// \n \c OPTIMAL if the problem has optimal solution
851 /// (i.e. it is feasible and bounded), and the algorithm has found
852 /// optimal flow and node potentials (primal and dual solutions),
853 /// \n \c UNBOUNDED if the objective function of the problem is
854 /// unbounded, i.e. there is a directed cycle having negative total
855 /// cost and infinite upper bound.
857 /// \see ProblemType, PivotRule
858 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
859 if (!init()) return INFEASIBLE;
860 return start(pivot_rule);
863 /// \brief Reset all the parameters that have been given before.
865 /// This function resets all the paramaters that have been given
866 /// before using functions \ref lowerMap(), \ref upperMap(),
867 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
869 /// It is useful for multiple run() calls. If this function is not
870 /// used, all the parameters given before are kept for the next
872 /// However the underlying digraph must not be modified after this
873 /// class have been constructed, since it copies and extends the graph.
877 /// NetworkSimplex<ListDigraph> ns(graph);
880 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
881 /// .supplyMap(sup).run();
883 /// // Run again with modified cost map (reset() is not called,
884 /// // so only the cost map have to be set again)
886 /// ns.costMap(cost).run();
888 /// // Run again from scratch using reset()
889 /// // (the lower bounds will be set to zero on all arcs)
891 /// ns.upperMap(capacity).costMap(cost)
892 /// .supplyMap(sup).run();
895 /// \return <tt>(*this)</tt>
896 NetworkSimplex& reset() {
897 for (int i = 0; i != _node_num; ++i) {
900 for (int i = 0; i != _arc_num; ++i) {
912 /// \name Query Functions
913 /// The results of the algorithm can be obtained using these
915 /// The \ref run() function must be called before using them.
919 /// \brief Return the total cost of the found flow.
921 /// This function returns the total cost of the found flow.
922 /// Its complexity is O(e).
924 /// \note The return type of the function can be specified as a
925 /// template parameter. For example,
927 /// ns.totalCost<double>();
929 /// It is useful if the total cost cannot be stored in the \c Cost
930 /// type of the algorithm, which is the default return type of the
933 /// \pre \ref run() must be called before using this function.
934 template <typename Number>
935 Number totalCost() const {
937 for (ArcIt a(_graph); a != INVALID; ++a) {
939 c += Number(_flow[i]) * Number(_cost[i]);
945 Cost totalCost() const {
946 return totalCost<Cost>();
950 /// \brief Return the flow on the given arc.
952 /// This function returns the flow on the given arc.
954 /// \pre \ref run() must be called before using this function.
955 Value flow(const Arc& a) const {
956 return _flow[_arc_id[a]];
959 /// \brief Return the flow map (the primal solution).
961 /// This function copies the flow value on each arc into the given
962 /// map. The \c Value type of the algorithm must be convertible to
963 /// the \c Value type of the map.
965 /// \pre \ref run() must be called before using this function.
966 template <typename FlowMap>
967 void flowMap(FlowMap &map) const {
968 for (ArcIt a(_graph); a != INVALID; ++a) {
969 map.set(a, _flow[_arc_id[a]]);
973 /// \brief Return the potential (dual value) of the given node.
975 /// This function returns the potential (dual value) of the
978 /// \pre \ref run() must be called before using this function.
979 Cost potential(const Node& n) const {
980 return _pi[_node_id[n]];
983 /// \brief Return the potential map (the dual solution).
985 /// This function copies the potential (dual value) of each node
986 /// into the given map.
987 /// The \c Cost type of the algorithm must be convertible to the
988 /// \c Value type of the map.
990 /// \pre \ref run() must be called before using this function.
991 template <typename PotentialMap>
992 void potentialMap(PotentialMap &map) const {
993 for (NodeIt n(_graph); n != INVALID; ++n) {
994 map.set(n, _pi[_node_id[n]]);
1002 // Initialize internal data structures
1004 if (_node_num == 0) return false;
1006 // Check the sum of supply values
1008 for (int i = 0; i != _node_num; ++i) {
1009 _sum_supply += _supply[i];
1011 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1012 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1014 // Remove non-zero lower bounds
1016 for (int i = 0; i != _arc_num; ++i) {
1017 Value c = _lower[i];
1019 _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
1021 _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
1023 _supply[_source[i]] -= c;
1024 _supply[_target[i]] += c;
1027 for (int i = 0; i != _arc_num; ++i) {
1028 _cap[i] = _upper[i];
1032 // Initialize artifical cost
1034 if (std::numeric_limits<Cost>::is_exact) {
1035 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1037 ART_COST = std::numeric_limits<Cost>::min();
1038 for (int i = 0; i != _arc_num; ++i) {
1039 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1041 ART_COST = (ART_COST + 1) * _node_num;
1044 // Initialize arc maps
1045 for (int i = 0; i != _arc_num; ++i) {
1047 _state[i] = STATE_LOWER;
1050 // Set data for the artificial root node
1052 _parent[_root] = -1;
1055 _rev_thread[0] = _root;
1056 _succ_num[_root] = _node_num + 1;
1057 _last_succ[_root] = _root - 1;
1058 _supply[_root] = -_sum_supply;
1061 // Add artificial arcs and initialize the spanning tree data structure
1062 if (_sum_supply == 0) {
1063 // EQ supply constraints
1064 _search_arc_num = _arc_num;
1065 _all_arc_num = _arc_num + _node_num;
1066 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1070 _rev_thread[u + 1] = u;
1074 _state[e] = STATE_TREE;
1075 if (_supply[u] >= 0) {
1080 _flow[e] = _supply[u];
1083 _forward[u] = false;
1087 _flow[e] = -_supply[u];
1088 _cost[e] = ART_COST;
1092 else if (_sum_supply > 0) {
1093 // LEQ supply constraints
1094 _search_arc_num = _arc_num + _node_num;
1095 int f = _arc_num + _node_num;
1096 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1099 _rev_thread[u + 1] = u;
1102 if (_supply[u] >= 0) {
1109 _flow[e] = _supply[u];
1111 _state[e] = STATE_TREE;
1113 _forward[u] = false;
1119 _flow[f] = -_supply[u];
1120 _cost[f] = ART_COST;
1121 _state[f] = STATE_TREE;
1127 _state[e] = STATE_LOWER;
1134 // GEQ supply constraints
1135 _search_arc_num = _arc_num + _node_num;
1136 int f = _arc_num + _node_num;
1137 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1140 _rev_thread[u + 1] = u;
1143 if (_supply[u] <= 0) {
1144 _forward[u] = false;
1150 _flow[e] = -_supply[u];
1152 _state[e] = STATE_TREE;
1160 _flow[f] = _supply[u];
1161 _state[f] = STATE_TREE;
1162 _cost[f] = ART_COST;
1168 _state[e] = STATE_LOWER;
1178 // Find the join node
1179 void findJoinNode() {
1180 int u = _source[in_arc];
1181 int v = _target[in_arc];
1183 if (_succ_num[u] < _succ_num[v]) {
1192 // Find the leaving arc of the cycle and returns true if the
1193 // leaving arc is not the same as the entering arc
1194 bool findLeavingArc() {
1195 // Initialize first and second nodes according to the direction
1197 if (_state[in_arc] == STATE_LOWER) {
1198 first = _source[in_arc];
1199 second = _target[in_arc];
1201 first = _target[in_arc];
1202 second = _source[in_arc];
1204 delta = _cap[in_arc];
1209 // Search the cycle along the path form the first node to the root
1210 for (int u = first; u != join; u = _parent[u]) {
1213 _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1220 // Search the cycle along the path form the second node to the root
1221 for (int u = second; u != join; u = _parent[u]) {
1224 (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1242 // Change _flow and _state vectors
1243 void changeFlow(bool change) {
1244 // Augment along the cycle
1246 Value val = _state[in_arc] * delta;
1247 _flow[in_arc] += val;
1248 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1249 _flow[_pred[u]] += _forward[u] ? -val : val;
1251 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1252 _flow[_pred[u]] += _forward[u] ? val : -val;
1255 // Update the state of the entering and leaving arcs
1257 _state[in_arc] = STATE_TREE;
1258 _state[_pred[u_out]] =
1259 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1261 _state[in_arc] = -_state[in_arc];
1265 // Update the tree structure
1266 void updateTreeStructure() {
1268 int old_rev_thread = _rev_thread[u_out];
1269 int old_succ_num = _succ_num[u_out];
1270 int old_last_succ = _last_succ[u_out];
1271 v_out = _parent[u_out];
1273 u = _last_succ[u_in]; // the last successor of u_in
1274 right = _thread[u]; // the node after it
1276 // Handle the case when old_rev_thread equals to v_in
1277 // (it also means that join and v_out coincide)
1278 if (old_rev_thread == v_in) {
1279 last = _thread[_last_succ[u_out]];
1281 last = _thread[v_in];
1284 // Update _thread and _parent along the stem nodes (i.e. the nodes
1285 // between u_in and u_out, whose parent have to be changed)
1286 _thread[v_in] = stem = u_in;
1287 _dirty_revs.clear();
1288 _dirty_revs.push_back(v_in);
1290 while (stem != u_out) {
1291 // Insert the next stem node into the thread list
1292 new_stem = _parent[stem];
1293 _thread[u] = new_stem;
1294 _dirty_revs.push_back(u);
1296 // Remove the subtree of stem from the thread list
1297 w = _rev_thread[stem];
1299 _rev_thread[right] = w;
1301 // Change the parent node and shift stem nodes
1302 _parent[stem] = par_stem;
1306 // Update u and right
1307 u = _last_succ[stem] == _last_succ[par_stem] ?
1308 _rev_thread[par_stem] : _last_succ[stem];
1311 _parent[u_out] = par_stem;
1313 _rev_thread[last] = u;
1314 _last_succ[u_out] = u;
1316 // Remove the subtree of u_out from the thread list except for
1317 // the case when old_rev_thread equals to v_in
1318 // (it also means that join and v_out coincide)
1319 if (old_rev_thread != v_in) {
1320 _thread[old_rev_thread] = right;
1321 _rev_thread[right] = old_rev_thread;
1324 // Update _rev_thread using the new _thread values
1325 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1327 _rev_thread[_thread[u]] = u;
1330 // Update _pred, _forward, _last_succ and _succ_num for the
1331 // stem nodes from u_out to u_in
1332 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1336 _pred[u] = _pred[w];
1337 _forward[u] = !_forward[w];
1338 tmp_sc += _succ_num[u] - _succ_num[w];
1339 _succ_num[u] = tmp_sc;
1340 _last_succ[w] = tmp_ls;
1343 _pred[u_in] = in_arc;
1344 _forward[u_in] = (u_in == _source[in_arc]);
1345 _succ_num[u_in] = old_succ_num;
1347 // Set limits for updating _last_succ form v_in and v_out
1349 int up_limit_in = -1;
1350 int up_limit_out = -1;
1351 if (_last_succ[join] == v_in) {
1352 up_limit_out = join;
1357 // Update _last_succ from v_in towards the root
1358 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1360 _last_succ[u] = _last_succ[u_out];
1362 // Update _last_succ from v_out towards the root
1363 if (join != old_rev_thread && v_in != old_rev_thread) {
1364 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1366 _last_succ[u] = old_rev_thread;
1369 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1371 _last_succ[u] = _last_succ[u_out];
1375 // Update _succ_num from v_in to join
1376 for (u = v_in; u != join; u = _parent[u]) {
1377 _succ_num[u] += old_succ_num;
1379 // Update _succ_num from v_out to join
1380 for (u = v_out; u != join; u = _parent[u]) {
1381 _succ_num[u] -= old_succ_num;
1385 // Update potentials
1386 void updatePotential() {
1387 Cost sigma = _forward[u_in] ?
1388 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1389 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1390 // Update potentials in the subtree, which has been moved
1391 int end = _thread[_last_succ[u_in]];
1392 for (int u = u_in; u != end; u = _thread[u]) {
1397 // Execute the algorithm
1398 ProblemType start(PivotRule pivot_rule) {
1399 // Select the pivot rule implementation
1400 switch (pivot_rule) {
1401 case FIRST_ELIGIBLE:
1402 return start<FirstEligiblePivotRule>();
1404 return start<BestEligiblePivotRule>();
1406 return start<BlockSearchPivotRule>();
1407 case CANDIDATE_LIST:
1408 return start<CandidateListPivotRule>();
1410 return start<AlteringListPivotRule>();
1412 return INFEASIBLE; // avoid warning
1415 template <typename PivotRuleImpl>
1416 ProblemType start() {
1417 PivotRuleImpl pivot(*this);
1419 // Execute the Network Simplex algorithm
1420 while (pivot.findEnteringArc()) {
1422 bool change = findLeavingArc();
1423 if (delta >= INF) return UNBOUNDED;
1426 updateTreeStructure();
1431 // Check feasibility
1432 for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1433 if (_flow[e] != 0) return INFEASIBLE;
1436 // Transform the solution and the supply map to the original form
1438 for (int i = 0; i != _arc_num; ++i) {
1439 Value c = _lower[i];
1442 _supply[_source[i]] += c;
1443 _supply[_target[i]] -= c;
1448 // Shift potentials to meet the requirements of the GEQ/LEQ type
1449 // optimality conditions
1450 if (_sum_supply == 0) {
1451 if (_stype == GEQ) {
1452 Cost max_pot = std::numeric_limits<Cost>::min();
1453 for (int i = 0; i != _node_num; ++i) {
1454 if (_pi[i] > max_pot) max_pot = _pi[i];
1457 for (int i = 0; i != _node_num; ++i)
1461 Cost min_pot = std::numeric_limits<Cost>::max();
1462 for (int i = 0; i != _node_num; ++i) {
1463 if (_pi[i] < min_pot) min_pot = _pi[i];
1466 for (int i = 0; i != _node_num; ++i)
1475 }; //class NetworkSimplex
1481 #endif //LEMON_NETWORK_SIMPLEX_H