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.
51 /// \tparam GR The digraph type the algorithm runs on.
52 /// \tparam F The value type used for flow amounts, capacity bounds
53 /// and supply values in the algorithm. By default it is \c int.
54 /// \tparam C The value type used for costs and potentials in the
55 /// algorithm. By default it is the same as \c F.
57 /// \warning Both value types must be signed integer types.
59 /// \note %NetworkSimplex provides five different pivot rule
60 /// implementations. For more information see \ref PivotRule.
61 template <typename GR, typename F = int, typename C = F>
66 /// The flow type of the algorithm
68 /// The cost type of the algorithm
70 /// The type of the flow map
71 typedef typename GR::template ArcMap<Flow> FlowMap;
72 /// The type of the potential map
73 typedef typename GR::template NodeMap<Cost> PotentialMap;
77 /// \brief Enum type for selecting the pivot rule.
79 /// Enum type for selecting the pivot rule for the \ref run()
82 /// \ref NetworkSimplex provides five different pivot rule
83 /// implementations that significantly affect the running time
85 /// By default \ref BLOCK_SEARCH "Block Search" is used, which
86 /// proved to be the most efficient and the most robust on various
87 /// test inputs according to our benchmark tests.
88 /// However another pivot rule can be selected using the \ref run()
89 /// function with the proper parameter.
92 /// The First Eligible pivot rule.
93 /// The next eligible arc is selected in a wraparound fashion
94 /// in every iteration.
97 /// The Best Eligible pivot rule.
98 /// The best eligible arc is selected in every iteration.
101 /// The Block Search pivot rule.
102 /// A specified number of arcs are examined in every iteration
103 /// in a wraparound fashion and the best eligible arc is selected
107 /// The Candidate List pivot rule.
108 /// In a major iteration a candidate list is built from eligible arcs
109 /// in a wraparound fashion and in the following minor iterations
110 /// the best eligible arc is selected from this list.
113 /// The Altering Candidate List pivot rule.
114 /// It is a modified version of the Candidate List method.
115 /// It keeps only the several best eligible arcs from the former
116 /// candidate list and extends this list in every iteration.
122 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
124 typedef typename GR::template ArcMap<Flow> FlowArcMap;
125 typedef typename GR::template ArcMap<Cost> CostArcMap;
126 typedef typename GR::template NodeMap<Flow> FlowNodeMap;
128 typedef std::vector<Arc> ArcVector;
129 typedef std::vector<Node> NodeVector;
130 typedef std::vector<int> IntVector;
131 typedef std::vector<bool> BoolVector;
132 typedef std::vector<Flow> FlowVector;
133 typedef std::vector<Cost> CostVector;
135 // State constants for arcs
144 // Data related to the underlying digraph
149 // Parameters of the problem
153 FlowNodeMap *_psupply;
155 Node _psource, _ptarget;
160 PotentialMap *_potential_map;
162 bool _local_potential;
164 // Data structures for storing the digraph
177 // Data for storing the spanning tree structure
181 IntVector _rev_thread;
183 IntVector _last_succ;
184 IntVector _dirty_revs;
189 // Temporary data used in the current pivot iteration
190 int in_arc, join, u_in, v_in, u_out, v_out;
191 int first, second, right, last;
192 int stem, par_stem, new_stem;
197 // Implementation of the First Eligible pivot rule
198 class FirstEligiblePivotRule
202 // References to the NetworkSimplex class
203 const IntVector &_source;
204 const IntVector &_target;
205 const CostVector &_cost;
206 const IntVector &_state;
207 const CostVector &_pi;
217 FirstEligiblePivotRule(NetworkSimplex &ns) :
218 _source(ns._source), _target(ns._target),
219 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
220 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
223 // Find next entering arc
224 bool findEnteringArc() {
226 for (int e = _next_arc; e < _arc_num; ++e) {
227 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
234 for (int e = 0; e < _next_arc; ++e) {
235 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
245 }; //class FirstEligiblePivotRule
248 // Implementation of the Best Eligible pivot rule
249 class BestEligiblePivotRule
253 // References to the NetworkSimplex class
254 const IntVector &_source;
255 const IntVector &_target;
256 const CostVector &_cost;
257 const IntVector &_state;
258 const CostVector &_pi;
265 BestEligiblePivotRule(NetworkSimplex &ns) :
266 _source(ns._source), _target(ns._target),
267 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
268 _in_arc(ns.in_arc), _arc_num(ns._arc_num)
271 // Find next entering arc
272 bool findEnteringArc() {
274 for (int e = 0; e < _arc_num; ++e) {
275 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
284 }; //class BestEligiblePivotRule
287 // Implementation of the Block Search pivot rule
288 class BlockSearchPivotRule
292 // References to the NetworkSimplex class
293 const IntVector &_source;
294 const IntVector &_target;
295 const CostVector &_cost;
296 const IntVector &_state;
297 const CostVector &_pi;
308 BlockSearchPivotRule(NetworkSimplex &ns) :
309 _source(ns._source), _target(ns._target),
310 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
311 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
313 // The main parameters of the pivot rule
314 const double BLOCK_SIZE_FACTOR = 2.0;
315 const int MIN_BLOCK_SIZE = 10;
317 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
321 // Find next entering arc
322 bool findEnteringArc() {
324 int cnt = _block_size;
325 int e, min_arc = _next_arc;
326 for (e = _next_arc; e < _arc_num; ++e) {
327 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
337 if (min == 0 || cnt > 0) {
338 for (e = 0; e < _next_arc; ++e) {
339 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
350 if (min >= 0) return false;
356 }; //class BlockSearchPivotRule
359 // Implementation of the Candidate List pivot rule
360 class CandidateListPivotRule
364 // References to the NetworkSimplex class
365 const IntVector &_source;
366 const IntVector &_target;
367 const CostVector &_cost;
368 const IntVector &_state;
369 const CostVector &_pi;
374 IntVector _candidates;
375 int _list_length, _minor_limit;
376 int _curr_length, _minor_count;
382 CandidateListPivotRule(NetworkSimplex &ns) :
383 _source(ns._source), _target(ns._target),
384 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
385 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
387 // The main parameters of the pivot rule
388 const double LIST_LENGTH_FACTOR = 1.0;
389 const int MIN_LIST_LENGTH = 10;
390 const double MINOR_LIMIT_FACTOR = 0.1;
391 const int MIN_MINOR_LIMIT = 3;
393 _list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_arc_num)),
395 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
397 _curr_length = _minor_count = 0;
398 _candidates.resize(_list_length);
401 /// Find next entering arc
402 bool findEnteringArc() {
404 int e, min_arc = _next_arc;
405 if (_curr_length > 0 && _minor_count < _minor_limit) {
406 // Minor iteration: select the best eligible arc from the
407 // current candidate list
410 for (int i = 0; i < _curr_length; ++i) {
412 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
418 _candidates[i--] = _candidates[--_curr_length];
427 // Major iteration: build a new candidate list
430 for (e = _next_arc; e < _arc_num; ++e) {
431 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
433 _candidates[_curr_length++] = e;
438 if (_curr_length == _list_length) break;
441 if (_curr_length < _list_length) {
442 for (e = 0; e < _next_arc; ++e) {
443 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
445 _candidates[_curr_length++] = e;
450 if (_curr_length == _list_length) break;
454 if (_curr_length == 0) return false;
461 }; //class CandidateListPivotRule
464 // Implementation of the Altering Candidate List pivot rule
465 class AlteringListPivotRule
469 // References to the NetworkSimplex class
470 const IntVector &_source;
471 const IntVector &_target;
472 const CostVector &_cost;
473 const IntVector &_state;
474 const CostVector &_pi;
479 int _block_size, _head_length, _curr_length;
481 IntVector _candidates;
482 CostVector _cand_cost;
484 // Functor class to compare arcs during sort of the candidate list
488 const CostVector &_map;
490 SortFunc(const CostVector &map) : _map(map) {}
491 bool operator()(int left, int right) {
492 return _map[left] > _map[right];
501 AlteringListPivotRule(NetworkSimplex &ns) :
502 _source(ns._source), _target(ns._target),
503 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
504 _in_arc(ns.in_arc), _arc_num(ns._arc_num),
505 _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
507 // The main parameters of the pivot rule
508 const double BLOCK_SIZE_FACTOR = 1.5;
509 const int MIN_BLOCK_SIZE = 10;
510 const double HEAD_LENGTH_FACTOR = 0.1;
511 const int MIN_HEAD_LENGTH = 3;
513 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
515 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
517 _candidates.resize(_head_length + _block_size);
521 // Find next entering arc
522 bool findEnteringArc() {
523 // Check the current candidate list
525 for (int i = 0; i < _curr_length; ++i) {
527 _cand_cost[e] = _state[e] *
528 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
529 if (_cand_cost[e] >= 0) {
530 _candidates[i--] = _candidates[--_curr_length];
535 int cnt = _block_size;
537 int limit = _head_length;
539 for (int e = _next_arc; e < _arc_num; ++e) {
540 _cand_cost[e] = _state[e] *
541 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
542 if (_cand_cost[e] < 0) {
543 _candidates[_curr_length++] = e;
547 if (_curr_length > limit) break;
552 if (_curr_length <= limit) {
553 for (int e = 0; e < _next_arc; ++e) {
554 _cand_cost[e] = _state[e] *
555 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
556 if (_cand_cost[e] < 0) {
557 _candidates[_curr_length++] = e;
561 if (_curr_length > limit) break;
567 if (_curr_length == 0) return false;
568 _next_arc = last_arc + 1;
570 // Make heap of the candidate list (approximating a partial sort)
571 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
574 // Pop the first element of the heap
575 _in_arc = _candidates[0];
576 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
578 _curr_length = std::min(_head_length, _curr_length - 1);
582 }; //class AlteringListPivotRule
586 /// \brief Constructor.
590 /// \param graph The digraph the algorithm runs on.
591 NetworkSimplex(const GR& graph) :
593 _plower(NULL), _pupper(NULL), _pcost(NULL),
594 _psupply(NULL), _pstsup(false),
595 _flow_map(NULL), _potential_map(NULL),
596 _local_flow(false), _local_potential(false),
599 LEMON_ASSERT(std::numeric_limits<Flow>::is_integer &&
600 std::numeric_limits<Flow>::is_signed,
601 "The flow type of NetworkSimplex must be signed integer");
602 LEMON_ASSERT(std::numeric_limits<Cost>::is_integer &&
603 std::numeric_limits<Cost>::is_signed,
604 "The cost type of NetworkSimplex must be signed integer");
609 if (_local_flow) delete _flow_map;
610 if (_local_potential) delete _potential_map;
613 /// \brief Set the lower bounds on the arcs.
615 /// This function sets the lower bounds on the arcs.
616 /// If neither this function nor \ref boundMaps() is used before
617 /// calling \ref run(), the lower bounds will be set to zero
620 /// \param map An arc map storing the lower bounds.
621 /// Its \c Value type must be convertible to the \c Flow type
622 /// of the algorithm.
624 /// \return <tt>(*this)</tt>
625 template <typename LOWER>
626 NetworkSimplex& lowerMap(const LOWER& map) {
628 _plower = new FlowArcMap(_graph);
629 for (ArcIt a(_graph); a != INVALID; ++a) {
630 (*_plower)[a] = map[a];
635 /// \brief Set the upper bounds (capacities) on the arcs.
637 /// This function sets the upper bounds (capacities) on the arcs.
638 /// If none of the functions \ref upperMap(), \ref capacityMap()
639 /// and \ref boundMaps() is used before calling \ref run(),
640 /// the upper bounds (capacities) will be set to
641 /// \c std::numeric_limits<Flow>::max() on all arcs.
643 /// \param map An arc map storing the upper bounds.
644 /// Its \c Value type must be convertible to the \c Flow type
645 /// of the algorithm.
647 /// \return <tt>(*this)</tt>
648 template<typename UPPER>
649 NetworkSimplex& upperMap(const UPPER& map) {
651 _pupper = new FlowArcMap(_graph);
652 for (ArcIt a(_graph); a != INVALID; ++a) {
653 (*_pupper)[a] = map[a];
658 /// \brief Set the upper bounds (capacities) on the arcs.
660 /// This function sets the upper bounds (capacities) on the arcs.
661 /// It is just an alias for \ref upperMap().
663 /// \return <tt>(*this)</tt>
664 template<typename CAP>
665 NetworkSimplex& capacityMap(const CAP& map) {
666 return upperMap(map);
669 /// \brief Set the lower and upper bounds on the arcs.
671 /// This function sets the lower and upper bounds on the arcs.
672 /// If neither this function nor \ref lowerMap() is used before
673 /// calling \ref run(), the lower bounds will be set to zero
675 /// If none of the functions \ref upperMap(), \ref capacityMap()
676 /// and \ref boundMaps() is used before calling \ref run(),
677 /// the upper bounds (capacities) will be set to
678 /// \c std::numeric_limits<Flow>::max() on all arcs.
680 /// \param lower An arc map storing the lower bounds.
681 /// \param upper An arc map storing the upper bounds.
683 /// The \c Value type of the maps must be convertible to the
684 /// \c Flow type of the algorithm.
686 /// \note This function is just a shortcut of calling \ref lowerMap()
687 /// and \ref upperMap() separately.
689 /// \return <tt>(*this)</tt>
690 template <typename LOWER, typename UPPER>
691 NetworkSimplex& boundMaps(const LOWER& lower, const UPPER& upper) {
692 return lowerMap(lower).upperMap(upper);
695 /// \brief Set the costs of the arcs.
697 /// This function sets the costs of the arcs.
698 /// If it is not used before calling \ref run(), the costs
699 /// will be set to \c 1 on all arcs.
701 /// \param map An arc map storing the costs.
702 /// Its \c Value type must be convertible to the \c Cost type
703 /// of the algorithm.
705 /// \return <tt>(*this)</tt>
706 template<typename COST>
707 NetworkSimplex& costMap(const COST& map) {
709 _pcost = new CostArcMap(_graph);
710 for (ArcIt a(_graph); a != INVALID; ++a) {
711 (*_pcost)[a] = map[a];
716 /// \brief Set the supply values of the nodes.
718 /// This function sets the supply values of the nodes.
719 /// If neither this function nor \ref stSupply() is used before
720 /// calling \ref run(), the supply of each node will be set to zero.
721 /// (It makes sense only if non-zero lower bounds are given.)
723 /// \param map A node map storing the supply values.
724 /// Its \c Value type must be convertible to the \c Flow type
725 /// of the algorithm.
727 /// \return <tt>(*this)</tt>
728 template<typename SUP>
729 NetworkSimplex& supplyMap(const SUP& map) {
732 _psupply = new FlowNodeMap(_graph);
733 for (NodeIt n(_graph); n != INVALID; ++n) {
734 (*_psupply)[n] = map[n];
739 /// \brief Set single source and target nodes and a supply value.
741 /// This function sets a single source node and a single target node
742 /// and the required flow value.
743 /// If neither this function nor \ref supplyMap() is used before
744 /// calling \ref run(), the supply of each node will be set to zero.
745 /// (It makes sense only if non-zero lower bounds are given.)
747 /// \param s The source node.
748 /// \param t The target node.
749 /// \param k The required amount of flow from node \c s to node \c t
750 /// (i.e. the supply of \c s and the demand of \c t).
752 /// \return <tt>(*this)</tt>
753 NetworkSimplex& stSupply(const Node& s, const Node& t, Flow k) {
763 /// \brief Set the flow map.
765 /// This function sets the flow map.
766 /// If it is not used before calling \ref run(), an instance will
767 /// be allocated automatically. The destructor deallocates this
768 /// automatically allocated map, of course.
770 /// \return <tt>(*this)</tt>
771 NetworkSimplex& flowMap(FlowMap& map) {
780 /// \brief Set the potential map.
782 /// This function sets the potential map, which is used for storing
783 /// the dual solution.
784 /// If it is not used before calling \ref run(), an instance will
785 /// be allocated automatically. The destructor deallocates this
786 /// automatically allocated map, of course.
788 /// \return <tt>(*this)</tt>
789 NetworkSimplex& potentialMap(PotentialMap& map) {
790 if (_local_potential) {
791 delete _potential_map;
792 _local_potential = false;
794 _potential_map = ↦
798 /// \name Execution Control
799 /// The algorithm can be executed using \ref run().
803 /// \brief Run the algorithm.
805 /// This function runs the algorithm.
806 /// The paramters can be specified using \ref lowerMap(),
807 /// \ref upperMap(), \ref capacityMap(), \ref boundMaps(),
808 /// \ref costMap(), \ref supplyMap() and \ref stSupply()
809 /// functions. For example,
811 /// NetworkSimplex<ListDigraph> ns(graph);
812 /// ns.boundMaps(lower, upper).costMap(cost)
813 /// .supplyMap(sup).run();
816 /// This function can be called more than once. All the parameters
817 /// that have been given are kept for the next call, unless
818 /// \ref reset() is called, thus only the modified parameters
819 /// have to be set again. See \ref reset() for examples.
821 /// \param pivot_rule The pivot rule that will be used during the
822 /// algorithm. For more information see \ref PivotRule.
824 /// \return \c true if a feasible flow can be found.
825 bool run(PivotRule pivot_rule = BLOCK_SEARCH) {
826 return init() && start(pivot_rule);
829 /// \brief Reset all the parameters that have been given before.
831 /// This function resets all the paramaters that have been given
832 /// using \ref lowerMap(), \ref upperMap(), \ref capacityMap(),
833 /// \ref boundMaps(), \ref costMap(), \ref supplyMap() and
834 /// \ref stSupply() functions before.
836 /// It is useful for multiple run() calls. If this function is not
837 /// used, all the parameters given before are kept for the next
842 /// NetworkSimplex<ListDigraph> ns(graph);
845 /// ns.lowerMap(lower).capacityMap(cap).costMap(cost)
846 /// .supplyMap(sup).run();
848 /// // Run again with modified cost map (reset() is not called,
849 /// // so only the cost map have to be set again)
851 /// ns.costMap(cost).run();
853 /// // Run again from scratch using reset()
854 /// // (the lower bounds will be set to zero on all arcs)
856 /// ns.capacityMap(cap).costMap(cost)
857 /// .supplyMap(sup).run();
860 /// \return <tt>(*this)</tt>
861 NetworkSimplex& reset() {
876 /// \name Query Functions
877 /// The results of the algorithm can be obtained using these
879 /// The \ref run() function must be called before using them.
883 /// \brief Return the total cost of the found flow.
885 /// This function returns the total cost of the found flow.
886 /// The complexity of the function is O(e).
888 /// \note The return type of the function can be specified as a
889 /// template parameter. For example,
891 /// ns.totalCost<double>();
893 /// It is useful if the total cost cannot be stored in the \c Cost
894 /// type of the algorithm, which is the default return type of the
897 /// \pre \ref run() must be called before using this function.
898 template <typename Num>
899 Num totalCost() const {
902 for (ArcIt e(_graph); e != INVALID; ++e)
903 c += (*_flow_map)[e] * (*_pcost)[e];
905 for (ArcIt e(_graph); e != INVALID; ++e)
906 c += (*_flow_map)[e];
912 Cost totalCost() const {
913 return totalCost<Cost>();
917 /// \brief Return the flow on the given arc.
919 /// This function returns the flow on the given arc.
921 /// \pre \ref run() must be called before using this function.
922 Flow flow(const Arc& a) const {
923 return (*_flow_map)[a];
926 /// \brief Return a const reference to the flow map.
928 /// This function returns a const reference to an arc map storing
931 /// \pre \ref run() must be called before using this function.
932 const FlowMap& flowMap() const {
936 /// \brief Return the potential (dual value) of the given node.
938 /// This function returns the potential (dual value) of the
941 /// \pre \ref run() must be called before using this function.
942 Cost potential(const Node& n) const {
943 return (*_potential_map)[n];
946 /// \brief Return a const reference to the potential map
947 /// (the dual solution).
949 /// This function returns a const reference to a node map storing
950 /// the found potentials, which form the dual solution of the
951 /// \ref min_cost_flow "minimum cost flow" problem.
953 /// \pre \ref run() must be called before using this function.
954 const PotentialMap& potentialMap() const {
955 return *_potential_map;
962 // Initialize internal data structures
964 // Initialize result maps
966 _flow_map = new FlowMap(_graph);
969 if (!_potential_map) {
970 _potential_map = new PotentialMap(_graph);
971 _local_potential = true;
974 // Initialize vectors
975 _node_num = countNodes(_graph);
976 _arc_num = countArcs(_graph);
977 int all_node_num = _node_num + 1;
978 int all_arc_num = _arc_num + _node_num;
979 if (_node_num == 0) return false;
981 _arc_ref.resize(_arc_num);
982 _source.resize(all_arc_num);
983 _target.resize(all_arc_num);
985 _cap.resize(all_arc_num);
986 _cost.resize(all_arc_num);
987 _supply.resize(all_node_num);
988 _flow.resize(all_arc_num);
989 _pi.resize(all_node_num);
991 _parent.resize(all_node_num);
992 _pred.resize(all_node_num);
993 _forward.resize(all_node_num);
994 _thread.resize(all_node_num);
995 _rev_thread.resize(all_node_num);
996 _succ_num.resize(all_node_num);
997 _last_succ.resize(all_node_num);
998 _state.resize(all_arc_num);
1000 // Initialize node related data
1001 bool valid_supply = true;
1002 if (!_pstsup && !_psupply) {
1004 _psource = _ptarget = NodeIt(_graph);
1010 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1012 _supply[i] = (*_psupply)[n];
1015 valid_supply = (sum == 0);
1018 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1022 _supply[_node_id[_psource]] = _pstflow;
1023 _supply[_node_id[_ptarget]] = -_pstflow;
1025 if (!valid_supply) return false;
1027 // Set data for the artificial root node
1029 _parent[_root] = -1;
1032 _rev_thread[0] = _root;
1033 _succ_num[_root] = all_node_num;
1034 _last_succ[_root] = _root - 1;
1038 // Store the arcs in a mixed order
1039 int k = std::max(int(sqrt(_arc_num)), 10);
1041 for (ArcIt e(_graph); e != INVALID; ++e) {
1043 if ((i += k) >= _arc_num) i = (i % k) + 1;
1046 // Initialize arc maps
1047 Flow max_cap = std::numeric_limits<Flow>::max();
1048 Cost max_cost = std::numeric_limits<Cost>::max() / 4;
1049 if (_pupper && _pcost) {
1050 for (int i = 0; i != _arc_num; ++i) {
1051 Arc e = _arc_ref[i];
1052 _source[i] = _node_id[_graph.source(e)];
1053 _target[i] = _node_id[_graph.target(e)];
1054 _cap[i] = (*_pupper)[e];
1055 _cost[i] = (*_pcost)[e];
1057 _state[i] = STATE_LOWER;
1060 for (int i = 0; i != _arc_num; ++i) {
1061 Arc e = _arc_ref[i];
1062 _source[i] = _node_id[_graph.source(e)];
1063 _target[i] = _node_id[_graph.target(e)];
1065 _state[i] = STATE_LOWER;
1068 for (int i = 0; i != _arc_num; ++i)
1069 _cap[i] = (*_pupper)[_arc_ref[i]];
1071 for (int i = 0; i != _arc_num; ++i)
1075 for (int i = 0; i != _arc_num; ++i)
1076 _cost[i] = (*_pcost)[_arc_ref[i]];
1078 for (int i = 0; i != _arc_num; ++i)
1083 // Remove non-zero lower bounds
1085 for (int i = 0; i != _arc_num; ++i) {
1086 Flow c = (*_plower)[_arc_ref[i]];
1089 _supply[_source[i]] -= c;
1090 _supply[_target[i]] += c;
1095 // Add artificial arcs and initialize the spanning tree data structure
1096 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1098 _rev_thread[u + 1] = u;
1103 _cost[e] = max_cost;
1105 _state[e] = STATE_TREE;
1106 if (_supply[u] >= 0) {
1107 _flow[e] = _supply[u];
1111 _flow[e] = -_supply[u];
1112 _forward[u] = false;
1120 // Find the join node
1121 void findJoinNode() {
1122 int u = _source[in_arc];
1123 int v = _target[in_arc];
1125 if (_succ_num[u] < _succ_num[v]) {
1134 // Find the leaving arc of the cycle and returns true if the
1135 // leaving arc is not the same as the entering arc
1136 bool findLeavingArc() {
1137 // Initialize first and second nodes according to the direction
1139 if (_state[in_arc] == STATE_LOWER) {
1140 first = _source[in_arc];
1141 second = _target[in_arc];
1143 first = _target[in_arc];
1144 second = _source[in_arc];
1146 delta = _cap[in_arc];
1151 // Search the cycle along the path form the first node to the root
1152 for (int u = first; u != join; u = _parent[u]) {
1154 d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
1161 // Search the cycle along the path form the second node to the root
1162 for (int u = second; u != join; u = _parent[u]) {
1164 d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
1182 // Change _flow and _state vectors
1183 void changeFlow(bool change) {
1184 // Augment along the cycle
1186 Flow val = _state[in_arc] * delta;
1187 _flow[in_arc] += val;
1188 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1189 _flow[_pred[u]] += _forward[u] ? -val : val;
1191 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1192 _flow[_pred[u]] += _forward[u] ? val : -val;
1195 // Update the state of the entering and leaving arcs
1197 _state[in_arc] = STATE_TREE;
1198 _state[_pred[u_out]] =
1199 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1201 _state[in_arc] = -_state[in_arc];
1205 // Update the tree structure
1206 void updateTreeStructure() {
1208 int old_rev_thread = _rev_thread[u_out];
1209 int old_succ_num = _succ_num[u_out];
1210 int old_last_succ = _last_succ[u_out];
1211 v_out = _parent[u_out];
1213 u = _last_succ[u_in]; // the last successor of u_in
1214 right = _thread[u]; // the node after it
1216 // Handle the case when old_rev_thread equals to v_in
1217 // (it also means that join and v_out coincide)
1218 if (old_rev_thread == v_in) {
1219 last = _thread[_last_succ[u_out]];
1221 last = _thread[v_in];
1224 // Update _thread and _parent along the stem nodes (i.e. the nodes
1225 // between u_in and u_out, whose parent have to be changed)
1226 _thread[v_in] = stem = u_in;
1227 _dirty_revs.clear();
1228 _dirty_revs.push_back(v_in);
1230 while (stem != u_out) {
1231 // Insert the next stem node into the thread list
1232 new_stem = _parent[stem];
1233 _thread[u] = new_stem;
1234 _dirty_revs.push_back(u);
1236 // Remove the subtree of stem from the thread list
1237 w = _rev_thread[stem];
1239 _rev_thread[right] = w;
1241 // Change the parent node and shift stem nodes
1242 _parent[stem] = par_stem;
1246 // Update u and right
1247 u = _last_succ[stem] == _last_succ[par_stem] ?
1248 _rev_thread[par_stem] : _last_succ[stem];
1251 _parent[u_out] = par_stem;
1253 _rev_thread[last] = u;
1254 _last_succ[u_out] = u;
1256 // Remove the subtree of u_out from the thread list except for
1257 // the case when old_rev_thread equals to v_in
1258 // (it also means that join and v_out coincide)
1259 if (old_rev_thread != v_in) {
1260 _thread[old_rev_thread] = right;
1261 _rev_thread[right] = old_rev_thread;
1264 // Update _rev_thread using the new _thread values
1265 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1267 _rev_thread[_thread[u]] = u;
1270 // Update _pred, _forward, _last_succ and _succ_num for the
1271 // stem nodes from u_out to u_in
1272 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1276 _pred[u] = _pred[w];
1277 _forward[u] = !_forward[w];
1278 tmp_sc += _succ_num[u] - _succ_num[w];
1279 _succ_num[u] = tmp_sc;
1280 _last_succ[w] = tmp_ls;
1283 _pred[u_in] = in_arc;
1284 _forward[u_in] = (u_in == _source[in_arc]);
1285 _succ_num[u_in] = old_succ_num;
1287 // Set limits for updating _last_succ form v_in and v_out
1289 int up_limit_in = -1;
1290 int up_limit_out = -1;
1291 if (_last_succ[join] == v_in) {
1292 up_limit_out = join;
1297 // Update _last_succ from v_in towards the root
1298 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1300 _last_succ[u] = _last_succ[u_out];
1302 // Update _last_succ from v_out towards the root
1303 if (join != old_rev_thread && v_in != old_rev_thread) {
1304 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1306 _last_succ[u] = old_rev_thread;
1309 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1311 _last_succ[u] = _last_succ[u_out];
1315 // Update _succ_num from v_in to join
1316 for (u = v_in; u != join; u = _parent[u]) {
1317 _succ_num[u] += old_succ_num;
1319 // Update _succ_num from v_out to join
1320 for (u = v_out; u != join; u = _parent[u]) {
1321 _succ_num[u] -= old_succ_num;
1325 // Update potentials
1326 void updatePotential() {
1327 Cost sigma = _forward[u_in] ?
1328 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1329 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1330 if (_succ_num[u_in] > _node_num / 2) {
1331 // Update in the upper subtree (which contains the root)
1332 int before = _rev_thread[u_in];
1333 int after = _thread[_last_succ[u_in]];
1334 _thread[before] = after;
1335 _pi[_root] -= sigma;
1336 for (int u = _thread[_root]; u != _root; u = _thread[u]) {
1339 _thread[before] = u_in;
1341 // Update in the lower subtree (which has been moved)
1342 int end = _thread[_last_succ[u_in]];
1343 for (int u = u_in; u != end; u = _thread[u]) {
1349 // Execute the algorithm
1350 bool start(PivotRule pivot_rule) {
1351 // Select the pivot rule implementation
1352 switch (pivot_rule) {
1353 case FIRST_ELIGIBLE:
1354 return start<FirstEligiblePivotRule>();
1356 return start<BestEligiblePivotRule>();
1358 return start<BlockSearchPivotRule>();
1359 case CANDIDATE_LIST:
1360 return start<CandidateListPivotRule>();
1362 return start<AlteringListPivotRule>();
1367 template <typename PivotRuleImpl>
1369 PivotRuleImpl pivot(*this);
1371 // Execute the Network Simplex algorithm
1372 while (pivot.findEnteringArc()) {
1374 bool change = findLeavingArc();
1377 updateTreeStructure();
1382 // Check if the flow amount equals zero on all the artificial arcs
1383 for (int e = _arc_num; e != _arc_num + _node_num; ++e) {
1384 if (_flow[e] > 0) return false;
1387 // Copy flow values to _flow_map
1389 for (int i = 0; i != _arc_num; ++i) {
1390 Arc e = _arc_ref[i];
1391 _flow_map->set(e, (*_plower)[e] + _flow[i]);
1394 for (int i = 0; i != _arc_num; ++i) {
1395 _flow_map->set(_arc_ref[i], _flow[i]);
1398 // Copy potential values to _potential_map
1399 for (NodeIt n(_graph); n != INVALID; ++n) {
1400 _potential_map->set(n, _pi[_node_id[n]]);
1406 }; //class NetworkSimplex
1412 #endif //LEMON_NETWORK_SIMPLEX_H