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>
33 #include <lemon/maps.h>
34 #include <lemon/circulation.h>
35 #include <lemon/adaptors.h>
39 /// \addtogroup min_cost_flow
42 /// \brief Implementation of the primal Network Simplex algorithm
43 /// for finding a \ref min_cost_flow "minimum cost flow".
45 /// \ref NetworkSimplex implements the primal Network Simplex algorithm
46 /// for finding a \ref min_cost_flow "minimum cost flow".
47 /// This algorithm is a specialized version of the linear programming
48 /// simplex method directly for the minimum cost flow problem.
49 /// It is one of the most efficient solution methods.
51 /// In general this class is the fastest implementation available
52 /// in LEMON for the minimum cost flow problem.
53 /// Moreover it supports both direction of the supply/demand inequality
54 /// constraints. For more information see \ref ProblemType.
56 /// \tparam GR The digraph type the algorithm runs on.
57 /// \tparam F The value type used for flow amounts, capacity bounds
58 /// and supply values in the algorithm. By default it is \c int.
59 /// \tparam C The value type used for costs and potentials in the
60 /// algorithm. By default it is the same as \c F.
62 /// \warning Both value types must be signed and all input data must
65 /// \note %NetworkSimplex provides five different pivot rule
66 /// implementations, from which the most efficient one is used
67 /// by default. For more information see \ref PivotRule.
68 template <typename GR, typename F = int, typename C = F>
73 /// The flow type of the algorithm
75 /// The cost type of the algorithm
78 /// The type of the flow map
79 typedef GR::ArcMap<Flow> FlowMap;
80 /// The type of the potential map
81 typedef GR::NodeMap<Cost> PotentialMap;
83 /// The type of the flow map
84 typedef typename GR::template ArcMap<Flow> FlowMap;
85 /// The type of the potential map
86 typedef typename GR::template NodeMap<Cost> PotentialMap;
91 /// \brief Enum type for selecting the pivot rule.
93 /// Enum type for selecting the pivot rule for the \ref run()
96 /// \ref NetworkSimplex provides five different pivot rule
97 /// implementations that significantly affect the running time
99 /// By default \ref BLOCK_SEARCH "Block Search" is used, which
100 /// proved to be the most efficient and the most robust on various
101 /// test inputs according to our benchmark tests.
102 /// However another pivot rule can be selected using the \ref run()
103 /// function with the proper parameter.
106 /// The First Eligible pivot rule.
107 /// The next eligible arc is selected in a wraparound fashion
108 /// in every iteration.
111 /// The Best Eligible pivot rule.
112 /// The best eligible arc is selected in every iteration.
115 /// The Block Search pivot rule.
116 /// A specified number of arcs are examined in every iteration
117 /// in a wraparound fashion and the best eligible arc is selected
121 /// The Candidate List pivot rule.
122 /// In a major iteration a candidate list is built from eligible arcs
123 /// in a wraparound fashion and in the following minor iterations
124 /// the best eligible arc is selected from this list.
127 /// The Altering Candidate List pivot rule.
128 /// It is a modified version of the Candidate List method.
129 /// It keeps only the several best eligible arcs from the former
130 /// candidate list and extends this list in every iteration.
134 /// \brief Enum type for selecting the problem type.
136 /// Enum type for selecting the problem type, i.e. the direction of
137 /// the inequalities in the supply/demand constraints of the
138 /// \ref min_cost_flow "minimum cost flow problem".
140 /// The default problem type is \c GEQ, since this form is supported
141 /// by other minimum cost flow algorithms and the \ref Circulation
142 /// algorithm as well.
143 /// The \c LEQ problem type can be selected using the \ref problemType()
146 /// Note that the equality form is a special case of both problem type.
149 /// This option means that there are "<em>greater or equal</em>"
150 /// constraints in the defintion, i.e. the exact formulation of the
151 /// problem is the following.
153 \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
154 \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
155 sup(u) \quad \forall u\in V \f]
156 \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
158 /// It means that the total demand must be greater or equal to the
159 /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
160 /// negative) and all the supplies have to be carried out from
161 /// the supply nodes, but there could be demands that are not
164 /// It is just an alias for the \c GEQ option.
165 CARRY_SUPPLIES = GEQ,
167 /// This option means that there are "<em>less or equal</em>"
168 /// constraints in the defintion, i.e. the exact formulation of the
169 /// problem is the following.
171 \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
172 \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
173 sup(u) \quad \forall u\in V \f]
174 \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
176 /// It means that the total demand must be less or equal to the
177 /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
178 /// positive) and all the demands have to be satisfied, but there
179 /// could be supplies that are not carried out from the supply
182 /// It is just an alias for the \c LEQ option.
183 SATISFY_DEMANDS = LEQ
188 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
190 typedef typename GR::template ArcMap<Flow> FlowArcMap;
191 typedef typename GR::template ArcMap<Cost> CostArcMap;
192 typedef typename GR::template NodeMap<Flow> FlowNodeMap;
194 typedef std::vector<Arc> ArcVector;
195 typedef std::vector<Node> NodeVector;
196 typedef std::vector<int> IntVector;
197 typedef std::vector<bool> BoolVector;
198 typedef std::vector<Flow> FlowVector;
199 typedef std::vector<Cost> CostVector;
201 // State constants for arcs
210 // Data related to the underlying digraph
215 // Parameters of the problem
219 FlowNodeMap *_psupply;
221 Node _psource, _ptarget;
227 PotentialMap *_potential_map;
229 bool _local_potential;
231 // Data structures for storing the digraph
244 // Data for storing the spanning tree structure
248 IntVector _rev_thread;
250 IntVector _last_succ;
251 IntVector _dirty_revs;
256 // Temporary data used in the current pivot iteration
257 int in_arc, join, u_in, v_in, u_out, v_out;
258 int first, second, right, last;
259 int stem, par_stem, new_stem;
264 // Implementation of the First Eligible pivot rule
265 class FirstEligiblePivotRule
269 // References to the NetworkSimplex class
270 const IntVector &_source;
271 const IntVector &_target;
272 const CostVector &_cost;
273 const IntVector &_state;
274 const CostVector &_pi;
284 FirstEligiblePivotRule(NetworkSimplex &ns) :
285 _source(ns._source), _target(ns._target),
286 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
287 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
290 // Find next entering arc
291 bool findEnteringArc() {
293 for (int e = _next_arc; e < _arc_num; ++e) {
294 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
301 for (int e = 0; e < _next_arc; ++e) {
302 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
312 }; //class FirstEligiblePivotRule
315 // Implementation of the Best Eligible pivot rule
316 class BestEligiblePivotRule
320 // References to the NetworkSimplex class
321 const IntVector &_source;
322 const IntVector &_target;
323 const CostVector &_cost;
324 const IntVector &_state;
325 const CostVector &_pi;
332 BestEligiblePivotRule(NetworkSimplex &ns) :
333 _source(ns._source), _target(ns._target),
334 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
335 _in_arc(ns.in_arc), _arc_num(ns._arc_num)
338 // Find next entering arc
339 bool findEnteringArc() {
341 for (int e = 0; e < _arc_num; ++e) {
342 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
351 }; //class BestEligiblePivotRule
354 // Implementation of the Block Search pivot rule
355 class BlockSearchPivotRule
359 // References to the NetworkSimplex class
360 const IntVector &_source;
361 const IntVector &_target;
362 const CostVector &_cost;
363 const IntVector &_state;
364 const CostVector &_pi;
375 BlockSearchPivotRule(NetworkSimplex &ns) :
376 _source(ns._source), _target(ns._target),
377 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
378 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
380 // The main parameters of the pivot rule
381 const double BLOCK_SIZE_FACTOR = 2.0;
382 const int MIN_BLOCK_SIZE = 10;
384 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
388 // Find next entering arc
389 bool findEnteringArc() {
391 int cnt = _block_size;
392 int e, min_arc = _next_arc;
393 for (e = _next_arc; e < _arc_num; ++e) {
394 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
404 if (min == 0 || cnt > 0) {
405 for (e = 0; e < _next_arc; ++e) {
406 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
417 if (min >= 0) return false;
423 }; //class BlockSearchPivotRule
426 // Implementation of the Candidate List pivot rule
427 class CandidateListPivotRule
431 // References to the NetworkSimplex class
432 const IntVector &_source;
433 const IntVector &_target;
434 const CostVector &_cost;
435 const IntVector &_state;
436 const CostVector &_pi;
441 IntVector _candidates;
442 int _list_length, _minor_limit;
443 int _curr_length, _minor_count;
449 CandidateListPivotRule(NetworkSimplex &ns) :
450 _source(ns._source), _target(ns._target),
451 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
452 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
454 // The main parameters of the pivot rule
455 const double LIST_LENGTH_FACTOR = 1.0;
456 const int MIN_LIST_LENGTH = 10;
457 const double MINOR_LIMIT_FACTOR = 0.1;
458 const int MIN_MINOR_LIMIT = 3;
460 _list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_arc_num)),
462 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
464 _curr_length = _minor_count = 0;
465 _candidates.resize(_list_length);
468 /// Find next entering arc
469 bool findEnteringArc() {
471 int e, min_arc = _next_arc;
472 if (_curr_length > 0 && _minor_count < _minor_limit) {
473 // Minor iteration: select the best eligible arc from the
474 // current candidate list
477 for (int i = 0; i < _curr_length; ++i) {
479 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
485 _candidates[i--] = _candidates[--_curr_length];
494 // Major iteration: build a new candidate list
497 for (e = _next_arc; e < _arc_num; ++e) {
498 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
500 _candidates[_curr_length++] = e;
505 if (_curr_length == _list_length) break;
508 if (_curr_length < _list_length) {
509 for (e = 0; e < _next_arc; ++e) {
510 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
512 _candidates[_curr_length++] = e;
517 if (_curr_length == _list_length) break;
521 if (_curr_length == 0) return false;
528 }; //class CandidateListPivotRule
531 // Implementation of the Altering Candidate List pivot rule
532 class AlteringListPivotRule
536 // References to the NetworkSimplex class
537 const IntVector &_source;
538 const IntVector &_target;
539 const CostVector &_cost;
540 const IntVector &_state;
541 const CostVector &_pi;
546 int _block_size, _head_length, _curr_length;
548 IntVector _candidates;
549 CostVector _cand_cost;
551 // Functor class to compare arcs during sort of the candidate list
555 const CostVector &_map;
557 SortFunc(const CostVector &map) : _map(map) {}
558 bool operator()(int left, int right) {
559 return _map[left] > _map[right];
568 AlteringListPivotRule(NetworkSimplex &ns) :
569 _source(ns._source), _target(ns._target),
570 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
571 _in_arc(ns.in_arc), _arc_num(ns._arc_num),
572 _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
574 // The main parameters of the pivot rule
575 const double BLOCK_SIZE_FACTOR = 1.5;
576 const int MIN_BLOCK_SIZE = 10;
577 const double HEAD_LENGTH_FACTOR = 0.1;
578 const int MIN_HEAD_LENGTH = 3;
580 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
582 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
584 _candidates.resize(_head_length + _block_size);
588 // Find next entering arc
589 bool findEnteringArc() {
590 // Check the current candidate list
592 for (int i = 0; i < _curr_length; ++i) {
594 _cand_cost[e] = _state[e] *
595 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
596 if (_cand_cost[e] >= 0) {
597 _candidates[i--] = _candidates[--_curr_length];
602 int cnt = _block_size;
604 int limit = _head_length;
606 for (int e = _next_arc; e < _arc_num; ++e) {
607 _cand_cost[e] = _state[e] *
608 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
609 if (_cand_cost[e] < 0) {
610 _candidates[_curr_length++] = e;
614 if (_curr_length > limit) break;
619 if (_curr_length <= limit) {
620 for (int e = 0; e < _next_arc; ++e) {
621 _cand_cost[e] = _state[e] *
622 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
623 if (_cand_cost[e] < 0) {
624 _candidates[_curr_length++] = e;
628 if (_curr_length > limit) break;
634 if (_curr_length == 0) return false;
635 _next_arc = last_arc + 1;
637 // Make heap of the candidate list (approximating a partial sort)
638 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
641 // Pop the first element of the heap
642 _in_arc = _candidates[0];
643 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
645 _curr_length = std::min(_head_length, _curr_length - 1);
649 }; //class AlteringListPivotRule
653 /// \brief Constructor.
655 /// The constructor of the class.
657 /// \param graph The digraph the algorithm runs on.
658 NetworkSimplex(const GR& graph) :
660 _plower(NULL), _pupper(NULL), _pcost(NULL),
661 _psupply(NULL), _pstsup(false), _ptype(GEQ),
662 _flow_map(NULL), _potential_map(NULL),
663 _local_flow(false), _local_potential(false),
666 LEMON_ASSERT(std::numeric_limits<Flow>::is_integer &&
667 std::numeric_limits<Flow>::is_signed,
668 "The flow type of NetworkSimplex must be signed integer");
669 LEMON_ASSERT(std::numeric_limits<Cost>::is_integer &&
670 std::numeric_limits<Cost>::is_signed,
671 "The cost type of NetworkSimplex must be signed integer");
676 if (_local_flow) delete _flow_map;
677 if (_local_potential) delete _potential_map;
681 /// The parameters of the algorithm can be specified using these
686 /// \brief Set the lower bounds on the arcs.
688 /// This function sets the lower bounds on the arcs.
689 /// If neither this function nor \ref boundMaps() is used before
690 /// calling \ref run(), the lower bounds will be set to zero
693 /// \param map An arc map storing the lower bounds.
694 /// Its \c Value type must be convertible to the \c Flow type
695 /// of the algorithm.
697 /// \return <tt>(*this)</tt>
698 template <typename LOWER>
699 NetworkSimplex& lowerMap(const LOWER& map) {
701 _plower = new FlowArcMap(_graph);
702 for (ArcIt a(_graph); a != INVALID; ++a) {
703 (*_plower)[a] = map[a];
708 /// \brief Set the upper bounds (capacities) on the arcs.
710 /// This function sets the upper bounds (capacities) on the arcs.
711 /// If none of the functions \ref upperMap(), \ref capacityMap()
712 /// and \ref boundMaps() is used before calling \ref run(),
713 /// the upper bounds (capacities) will be set to
714 /// \c std::numeric_limits<Flow>::max() on all arcs.
716 /// \param map An arc map storing the upper bounds.
717 /// Its \c Value type must be convertible to the \c Flow type
718 /// of the algorithm.
720 /// \return <tt>(*this)</tt>
721 template<typename UPPER>
722 NetworkSimplex& upperMap(const UPPER& map) {
724 _pupper = new FlowArcMap(_graph);
725 for (ArcIt a(_graph); a != INVALID; ++a) {
726 (*_pupper)[a] = map[a];
731 /// \brief Set the upper bounds (capacities) on the arcs.
733 /// This function sets the upper bounds (capacities) on the arcs.
734 /// It is just an alias for \ref upperMap().
736 /// \return <tt>(*this)</tt>
737 template<typename CAP>
738 NetworkSimplex& capacityMap(const CAP& map) {
739 return upperMap(map);
742 /// \brief Set the lower and upper bounds on the arcs.
744 /// This function sets the lower and upper bounds on the arcs.
745 /// If neither this function nor \ref lowerMap() is used before
746 /// calling \ref run(), the lower bounds will be set to zero
748 /// If none of the functions \ref upperMap(), \ref capacityMap()
749 /// and \ref boundMaps() is used before calling \ref run(),
750 /// the upper bounds (capacities) will be set to
751 /// \c std::numeric_limits<Flow>::max() on all arcs.
753 /// \param lower An arc map storing the lower bounds.
754 /// \param upper An arc map storing the upper bounds.
756 /// The \c Value type of the maps must be convertible to the
757 /// \c Flow type of the algorithm.
759 /// \note This function is just a shortcut of calling \ref lowerMap()
760 /// and \ref upperMap() separately.
762 /// \return <tt>(*this)</tt>
763 template <typename LOWER, typename UPPER>
764 NetworkSimplex& boundMaps(const LOWER& lower, const UPPER& upper) {
765 return lowerMap(lower).upperMap(upper);
768 /// \brief Set the costs of the arcs.
770 /// This function sets the costs of the arcs.
771 /// If it is not used before calling \ref run(), the costs
772 /// will be set to \c 1 on all arcs.
774 /// \param map An arc map storing the costs.
775 /// Its \c Value type must be convertible to the \c Cost type
776 /// of the algorithm.
778 /// \return <tt>(*this)</tt>
779 template<typename COST>
780 NetworkSimplex& costMap(const COST& map) {
782 _pcost = new CostArcMap(_graph);
783 for (ArcIt a(_graph); a != INVALID; ++a) {
784 (*_pcost)[a] = map[a];
789 /// \brief Set the supply values of the nodes.
791 /// This function sets the supply values of the nodes.
792 /// If neither this function nor \ref stSupply() is used before
793 /// calling \ref run(), the supply of each node will be set to zero.
794 /// (It makes sense only if non-zero lower bounds are given.)
796 /// \param map A node map storing the supply values.
797 /// Its \c Value type must be convertible to the \c Flow type
798 /// of the algorithm.
800 /// \return <tt>(*this)</tt>
801 template<typename SUP>
802 NetworkSimplex& supplyMap(const SUP& map) {
805 _psupply = new FlowNodeMap(_graph);
806 for (NodeIt n(_graph); n != INVALID; ++n) {
807 (*_psupply)[n] = map[n];
812 /// \brief Set single source and target nodes and a supply value.
814 /// This function sets a single source node and a single target node
815 /// and the required flow value.
816 /// If neither this function nor \ref supplyMap() is used before
817 /// calling \ref run(), the supply of each node will be set to zero.
818 /// (It makes sense only if non-zero lower bounds are given.)
820 /// \param s The source node.
821 /// \param t The target node.
822 /// \param k The required amount of flow from node \c s to node \c t
823 /// (i.e. the supply of \c s and the demand of \c t).
825 /// \return <tt>(*this)</tt>
826 NetworkSimplex& stSupply(const Node& s, const Node& t, Flow k) {
836 /// \brief Set the problem type.
838 /// This function sets the problem type for the algorithm.
839 /// If it is not used before calling \ref run(), the \ref GEQ problem
840 /// type will be used.
842 /// For more information see \ref ProblemType.
844 /// \return <tt>(*this)</tt>
845 NetworkSimplex& problemType(ProblemType problem_type) {
846 _ptype = problem_type;
850 /// \brief Set the flow map.
852 /// This function sets the flow map.
853 /// If it is not used before calling \ref run(), an instance will
854 /// be allocated automatically. The destructor deallocates this
855 /// automatically allocated map, of course.
857 /// \return <tt>(*this)</tt>
858 NetworkSimplex& flowMap(FlowMap& map) {
867 /// \brief Set the potential map.
869 /// This function sets the potential map, which is used for storing
870 /// the dual solution.
871 /// If it is not used before calling \ref run(), an instance will
872 /// be allocated automatically. The destructor deallocates this
873 /// automatically allocated map, of course.
875 /// \return <tt>(*this)</tt>
876 NetworkSimplex& potentialMap(PotentialMap& map) {
877 if (_local_potential) {
878 delete _potential_map;
879 _local_potential = false;
881 _potential_map = ↦
887 /// \name Execution Control
888 /// The algorithm can be executed using \ref run().
892 /// \brief Run the algorithm.
894 /// This function runs the algorithm.
895 /// The paramters can be specified using functions \ref lowerMap(),
896 /// \ref upperMap(), \ref capacityMap(), \ref boundMaps(),
897 /// \ref costMap(), \ref supplyMap(), \ref stSupply(),
898 /// \ref problemType(), \ref flowMap() and \ref potentialMap().
901 /// NetworkSimplex<ListDigraph> ns(graph);
902 /// ns.boundMaps(lower, upper).costMap(cost)
903 /// .supplyMap(sup).run();
906 /// This function can be called more than once. All the parameters
907 /// that have been given are kept for the next call, unless
908 /// \ref reset() is called, thus only the modified parameters
909 /// have to be set again. See \ref reset() for examples.
911 /// \param pivot_rule The pivot rule that will be used during the
912 /// algorithm. For more information see \ref PivotRule.
914 /// \return \c true if a feasible flow can be found.
915 bool run(PivotRule pivot_rule = BLOCK_SEARCH) {
916 return init() && start(pivot_rule);
919 /// \brief Reset all the parameters that have been given before.
921 /// This function resets all the paramaters that have been given
922 /// before using functions \ref lowerMap(), \ref upperMap(),
923 /// \ref capacityMap(), \ref boundMaps(), \ref costMap(),
924 /// \ref supplyMap(), \ref stSupply(), \ref problemType(),
925 /// \ref flowMap() and \ref potentialMap().
927 /// It is useful for multiple run() calls. If this function is not
928 /// used, all the parameters given before are kept for the next
933 /// NetworkSimplex<ListDigraph> ns(graph);
936 /// ns.lowerMap(lower).capacityMap(cap).costMap(cost)
937 /// .supplyMap(sup).run();
939 /// // Run again with modified cost map (reset() is not called,
940 /// // so only the cost map have to be set again)
942 /// ns.costMap(cost).run();
944 /// // Run again from scratch using reset()
945 /// // (the lower bounds will be set to zero on all arcs)
947 /// ns.capacityMap(cap).costMap(cost)
948 /// .supplyMap(sup).run();
951 /// \return <tt>(*this)</tt>
952 NetworkSimplex& reset() {
963 if (_local_flow) delete _flow_map;
964 if (_local_potential) delete _potential_map;
966 _potential_map = NULL;
968 _local_potential = false;
975 /// \name Query Functions
976 /// The results of the algorithm can be obtained using these
978 /// The \ref run() function must be called before using them.
982 /// \brief Return the total cost of the found flow.
984 /// This function returns the total cost of the found flow.
985 /// The complexity of the function is O(e).
987 /// \note The return type of the function can be specified as a
988 /// template parameter. For example,
990 /// ns.totalCost<double>();
992 /// It is useful if the total cost cannot be stored in the \c Cost
993 /// type of the algorithm, which is the default return type of the
996 /// \pre \ref run() must be called before using this function.
997 template <typename Num>
998 Num totalCost() const {
1001 for (ArcIt e(_graph); e != INVALID; ++e)
1002 c += (*_flow_map)[e] * (*_pcost)[e];
1004 for (ArcIt e(_graph); e != INVALID; ++e)
1005 c += (*_flow_map)[e];
1011 Cost totalCost() const {
1012 return totalCost<Cost>();
1016 /// \brief Return the flow on the given arc.
1018 /// This function returns the flow on the given arc.
1020 /// \pre \ref run() must be called before using this function.
1021 Flow flow(const Arc& a) const {
1022 return (*_flow_map)[a];
1025 /// \brief Return a const reference to the flow map.
1027 /// This function returns a const reference to an arc map storing
1030 /// \pre \ref run() must be called before using this function.
1031 const FlowMap& flowMap() const {
1035 /// \brief Return the potential (dual value) of the given node.
1037 /// This function returns the potential (dual value) of the
1040 /// \pre \ref run() must be called before using this function.
1041 Cost potential(const Node& n) const {
1042 return (*_potential_map)[n];
1045 /// \brief Return a const reference to the potential map
1046 /// (the dual solution).
1048 /// This function returns a const reference to a node map storing
1049 /// the found potentials, which form the dual solution of the
1050 /// \ref min_cost_flow "minimum cost flow" problem.
1052 /// \pre \ref run() must be called before using this function.
1053 const PotentialMap& potentialMap() const {
1054 return *_potential_map;
1061 // Initialize internal data structures
1063 // Initialize result maps
1065 _flow_map = new FlowMap(_graph);
1068 if (!_potential_map) {
1069 _potential_map = new PotentialMap(_graph);
1070 _local_potential = true;
1073 // Initialize vectors
1074 _node_num = countNodes(_graph);
1075 _arc_num = countArcs(_graph);
1076 int all_node_num = _node_num + 1;
1077 int all_arc_num = _arc_num + _node_num;
1078 if (_node_num == 0) return false;
1080 _arc_ref.resize(_arc_num);
1081 _source.resize(all_arc_num);
1082 _target.resize(all_arc_num);
1084 _cap.resize(all_arc_num);
1085 _cost.resize(all_arc_num);
1086 _supply.resize(all_node_num);
1087 _flow.resize(all_arc_num);
1088 _pi.resize(all_node_num);
1090 _parent.resize(all_node_num);
1091 _pred.resize(all_node_num);
1092 _forward.resize(all_node_num);
1093 _thread.resize(all_node_num);
1094 _rev_thread.resize(all_node_num);
1095 _succ_num.resize(all_node_num);
1096 _last_succ.resize(all_node_num);
1097 _state.resize(all_arc_num);
1099 // Initialize node related data
1100 bool valid_supply = true;
1101 Flow sum_supply = 0;
1102 if (!_pstsup && !_psupply) {
1104 _psource = _ptarget = NodeIt(_graph);
1109 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1111 _supply[i] = (*_psupply)[n];
1112 sum_supply += _supply[i];
1114 valid_supply = (_ptype == GEQ && sum_supply <= 0) ||
1115 (_ptype == LEQ && sum_supply >= 0);
1118 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1122 _supply[_node_id[_psource]] = _pstflow;
1123 _supply[_node_id[_ptarget]] = -_pstflow;
1125 if (!valid_supply) return false;
1127 // Infinite capacity value
1129 std::numeric_limits<Flow>::has_infinity ?
1130 std::numeric_limits<Flow>::infinity() :
1131 std::numeric_limits<Flow>::max();
1133 // Initialize artifical cost
1135 if (std::numeric_limits<Cost>::is_exact) {
1136 art_cost = std::numeric_limits<Cost>::max() / 4 + 1;
1138 art_cost = std::numeric_limits<Cost>::min();
1139 for (int i = 0; i != _arc_num; ++i) {
1140 if (_cost[i] > art_cost) art_cost = _cost[i];
1142 art_cost = (art_cost + 1) * _node_num;
1145 // Run Circulation to check if a feasible solution exists
1146 typedef ConstMap<Arc, Flow> ConstArcMap;
1147 ConstArcMap zero_arc_map(0), inf_arc_map(inf_cap);
1148 FlowNodeMap *csup = NULL;
1149 bool local_csup = false;
1153 csup = new FlowNodeMap(_graph, 0);
1154 (*csup)[_psource] = _pstflow;
1155 (*csup)[_ptarget] = -_pstflow;
1158 bool circ_result = false;
1159 if (_ptype == GEQ || (_ptype == LEQ && sum_supply == 0)) {
1163 Circulation<GR, FlowArcMap, FlowArcMap, FlowNodeMap>
1164 circ(_graph, *_plower, *_pupper, *csup);
1165 circ_result = circ.run();
1167 Circulation<GR, FlowArcMap, ConstArcMap, FlowNodeMap>
1168 circ(_graph, *_plower, inf_arc_map, *csup);
1169 circ_result = circ.run();
1173 Circulation<GR, ConstArcMap, FlowArcMap, FlowNodeMap>
1174 circ(_graph, zero_arc_map, *_pupper, *csup);
1175 circ_result = circ.run();
1177 Circulation<GR, ConstArcMap, ConstArcMap, FlowNodeMap>
1178 circ(_graph, zero_arc_map, inf_arc_map, *csup);
1179 circ_result = circ.run();
1184 typedef ReverseDigraph<const GR> RevGraph;
1185 typedef NegMap<FlowNodeMap> NegNodeMap;
1186 RevGraph rgraph(_graph);
1187 NegNodeMap neg_csup(*csup);
1190 Circulation<RevGraph, FlowArcMap, FlowArcMap, NegNodeMap>
1191 circ(rgraph, *_plower, *_pupper, neg_csup);
1192 circ_result = circ.run();
1194 Circulation<RevGraph, FlowArcMap, ConstArcMap, NegNodeMap>
1195 circ(rgraph, *_plower, inf_arc_map, neg_csup);
1196 circ_result = circ.run();
1200 Circulation<RevGraph, ConstArcMap, FlowArcMap, NegNodeMap>
1201 circ(rgraph, zero_arc_map, *_pupper, neg_csup);
1202 circ_result = circ.run();
1204 Circulation<RevGraph, ConstArcMap, ConstArcMap, NegNodeMap>
1205 circ(rgraph, zero_arc_map, inf_arc_map, neg_csup);
1206 circ_result = circ.run();
1210 if (local_csup) delete csup;
1211 if (!circ_result) return false;
1213 // Set data for the artificial root node
1215 _parent[_root] = -1;
1218 _rev_thread[0] = _root;
1219 _succ_num[_root] = all_node_num;
1220 _last_succ[_root] = _root - 1;
1221 _supply[_root] = -sum_supply;
1222 if (sum_supply < 0) {
1223 _pi[_root] = -art_cost;
1225 _pi[_root] = art_cost;
1228 // Store the arcs in a mixed order
1229 int k = std::max(int(sqrt(_arc_num)), 10);
1231 for (ArcIt e(_graph); e != INVALID; ++e) {
1233 if ((i += k) >= _arc_num) i = (i % k) + 1;
1236 // Initialize arc maps
1237 if (_pupper && _pcost) {
1238 for (int i = 0; i != _arc_num; ++i) {
1239 Arc e = _arc_ref[i];
1240 _source[i] = _node_id[_graph.source(e)];
1241 _target[i] = _node_id[_graph.target(e)];
1242 _cap[i] = (*_pupper)[e];
1243 _cost[i] = (*_pcost)[e];
1245 _state[i] = STATE_LOWER;
1248 for (int i = 0; i != _arc_num; ++i) {
1249 Arc e = _arc_ref[i];
1250 _source[i] = _node_id[_graph.source(e)];
1251 _target[i] = _node_id[_graph.target(e)];
1253 _state[i] = STATE_LOWER;
1256 for (int i = 0; i != _arc_num; ++i)
1257 _cap[i] = (*_pupper)[_arc_ref[i]];
1259 for (int i = 0; i != _arc_num; ++i)
1263 for (int i = 0; i != _arc_num; ++i)
1264 _cost[i] = (*_pcost)[_arc_ref[i]];
1266 for (int i = 0; i != _arc_num; ++i)
1271 // Remove non-zero lower bounds
1273 for (int i = 0; i != _arc_num; ++i) {
1274 Flow c = (*_plower)[_arc_ref[i]];
1277 _supply[_source[i]] -= c;
1278 _supply[_target[i]] += c;
1283 // Add artificial arcs and initialize the spanning tree data structure
1284 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1286 _rev_thread[u + 1] = u;
1291 _cost[e] = art_cost;
1293 _state[e] = STATE_TREE;
1294 if (_supply[u] > 0 || (_supply[u] == 0 && sum_supply <= 0)) {
1295 _flow[e] = _supply[u];
1297 _pi[u] = -art_cost + _pi[_root];
1299 _flow[e] = -_supply[u];
1300 _forward[u] = false;
1301 _pi[u] = art_cost + _pi[_root];
1308 // Find the join node
1309 void findJoinNode() {
1310 int u = _source[in_arc];
1311 int v = _target[in_arc];
1313 if (_succ_num[u] < _succ_num[v]) {
1322 // Find the leaving arc of the cycle and returns true if the
1323 // leaving arc is not the same as the entering arc
1324 bool findLeavingArc() {
1325 // Initialize first and second nodes according to the direction
1327 if (_state[in_arc] == STATE_LOWER) {
1328 first = _source[in_arc];
1329 second = _target[in_arc];
1331 first = _target[in_arc];
1332 second = _source[in_arc];
1334 delta = _cap[in_arc];
1339 // Search the cycle along the path form the first node to the root
1340 for (int u = first; u != join; u = _parent[u]) {
1342 d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
1349 // Search the cycle along the path form the second node to the root
1350 for (int u = second; u != join; u = _parent[u]) {
1352 d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
1370 // Change _flow and _state vectors
1371 void changeFlow(bool change) {
1372 // Augment along the cycle
1374 Flow val = _state[in_arc] * delta;
1375 _flow[in_arc] += val;
1376 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1377 _flow[_pred[u]] += _forward[u] ? -val : val;
1379 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1380 _flow[_pred[u]] += _forward[u] ? val : -val;
1383 // Update the state of the entering and leaving arcs
1385 _state[in_arc] = STATE_TREE;
1386 _state[_pred[u_out]] =
1387 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1389 _state[in_arc] = -_state[in_arc];
1393 // Update the tree structure
1394 void updateTreeStructure() {
1396 int old_rev_thread = _rev_thread[u_out];
1397 int old_succ_num = _succ_num[u_out];
1398 int old_last_succ = _last_succ[u_out];
1399 v_out = _parent[u_out];
1401 u = _last_succ[u_in]; // the last successor of u_in
1402 right = _thread[u]; // the node after it
1404 // Handle the case when old_rev_thread equals to v_in
1405 // (it also means that join and v_out coincide)
1406 if (old_rev_thread == v_in) {
1407 last = _thread[_last_succ[u_out]];
1409 last = _thread[v_in];
1412 // Update _thread and _parent along the stem nodes (i.e. the nodes
1413 // between u_in and u_out, whose parent have to be changed)
1414 _thread[v_in] = stem = u_in;
1415 _dirty_revs.clear();
1416 _dirty_revs.push_back(v_in);
1418 while (stem != u_out) {
1419 // Insert the next stem node into the thread list
1420 new_stem = _parent[stem];
1421 _thread[u] = new_stem;
1422 _dirty_revs.push_back(u);
1424 // Remove the subtree of stem from the thread list
1425 w = _rev_thread[stem];
1427 _rev_thread[right] = w;
1429 // Change the parent node and shift stem nodes
1430 _parent[stem] = par_stem;
1434 // Update u and right
1435 u = _last_succ[stem] == _last_succ[par_stem] ?
1436 _rev_thread[par_stem] : _last_succ[stem];
1439 _parent[u_out] = par_stem;
1441 _rev_thread[last] = u;
1442 _last_succ[u_out] = u;
1444 // Remove the subtree of u_out from the thread list except for
1445 // the case when old_rev_thread equals to v_in
1446 // (it also means that join and v_out coincide)
1447 if (old_rev_thread != v_in) {
1448 _thread[old_rev_thread] = right;
1449 _rev_thread[right] = old_rev_thread;
1452 // Update _rev_thread using the new _thread values
1453 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1455 _rev_thread[_thread[u]] = u;
1458 // Update _pred, _forward, _last_succ and _succ_num for the
1459 // stem nodes from u_out to u_in
1460 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1464 _pred[u] = _pred[w];
1465 _forward[u] = !_forward[w];
1466 tmp_sc += _succ_num[u] - _succ_num[w];
1467 _succ_num[u] = tmp_sc;
1468 _last_succ[w] = tmp_ls;
1471 _pred[u_in] = in_arc;
1472 _forward[u_in] = (u_in == _source[in_arc]);
1473 _succ_num[u_in] = old_succ_num;
1475 // Set limits for updating _last_succ form v_in and v_out
1477 int up_limit_in = -1;
1478 int up_limit_out = -1;
1479 if (_last_succ[join] == v_in) {
1480 up_limit_out = join;
1485 // Update _last_succ from v_in towards the root
1486 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1488 _last_succ[u] = _last_succ[u_out];
1490 // Update _last_succ from v_out towards the root
1491 if (join != old_rev_thread && v_in != old_rev_thread) {
1492 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1494 _last_succ[u] = old_rev_thread;
1497 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1499 _last_succ[u] = _last_succ[u_out];
1503 // Update _succ_num from v_in to join
1504 for (u = v_in; u != join; u = _parent[u]) {
1505 _succ_num[u] += old_succ_num;
1507 // Update _succ_num from v_out to join
1508 for (u = v_out; u != join; u = _parent[u]) {
1509 _succ_num[u] -= old_succ_num;
1513 // Update potentials
1514 void updatePotential() {
1515 Cost sigma = _forward[u_in] ?
1516 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1517 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1518 // Update potentials in the subtree, which has been moved
1519 int end = _thread[_last_succ[u_in]];
1520 for (int u = u_in; u != end; u = _thread[u]) {
1525 // Execute the algorithm
1526 bool start(PivotRule pivot_rule) {
1527 // Select the pivot rule implementation
1528 switch (pivot_rule) {
1529 case FIRST_ELIGIBLE:
1530 return start<FirstEligiblePivotRule>();
1532 return start<BestEligiblePivotRule>();
1534 return start<BlockSearchPivotRule>();
1535 case CANDIDATE_LIST:
1536 return start<CandidateListPivotRule>();
1538 return start<AlteringListPivotRule>();
1543 template <typename PivotRuleImpl>
1545 PivotRuleImpl pivot(*this);
1547 // Execute the Network Simplex algorithm
1548 while (pivot.findEnteringArc()) {
1550 bool change = findLeavingArc();
1553 updateTreeStructure();
1558 // Copy flow values to _flow_map
1560 for (int i = 0; i != _arc_num; ++i) {
1561 Arc e = _arc_ref[i];
1562 _flow_map->set(e, (*_plower)[e] + _flow[i]);
1565 for (int i = 0; i != _arc_num; ++i) {
1566 _flow_map->set(_arc_ref[i], _flow[i]);
1569 // Copy potential values to _potential_map
1570 for (NodeIt n(_graph); n != INVALID; ++n) {
1571 _potential_map->set(n, _pi[_node_id[n]]);
1577 }; //class NetworkSimplex
1583 #endif //LEMON_NETWORK_SIMPLEX_H