1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2010
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 /// \ref amo93networkflows, \ref dantzig63linearprog,
45 /// \ref kellyoneill91netsimplex.
46 /// This algorithm is a highly efficient specialized version of the
47 /// linear programming simplex method directly for the minimum cost
50 /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
51 /// implementations available in LEMON for solving this problem.
52 /// (For more information, see \ref min_cost_flow_algs "the module page".)
53 /// Furthermore, this class supports both directions of the supply/demand
54 /// inequality constraints. For more information, see \ref SupplyType.
56 /// Most of the parameters of the problem (except for the digraph)
57 /// can be given using separate functions, and the algorithm can be
58 /// executed using the \ref run() function. If some parameters are not
59 /// specified, then default values will be used.
61 /// \tparam GR The digraph type the algorithm runs on.
62 /// \tparam V The number type used for flow amounts, capacity bounds
63 /// and supply values in the algorithm. By default, it is \c int.
64 /// \tparam C The number type used for costs and potentials in the
65 /// algorithm. By default, it is the same as \c V.
67 /// \warning Both \c V and \c C must be signed number types.
68 /// \warning All input data (capacities, supply values, and costs) must
71 /// \note %NetworkSimplex provides five different pivot rule
72 /// implementations, from which the most efficient one is used
73 /// by default. For more information, see \ref PivotRule.
74 template <typename GR, typename V = int, typename C = V>
79 /// The type of the flow amounts, capacity bounds and supply values
81 /// The type of the arc costs
86 /// \brief Problem type constants for the \c run() function.
88 /// Enum type containing the problem type constants that can be
89 /// returned by the \ref run() function of the algorithm.
91 /// The problem has no feasible solution (flow).
93 /// The problem has optimal solution (i.e. it is feasible and
94 /// bounded), and the algorithm has found optimal flow and node
95 /// potentials (primal and dual solutions).
97 /// The objective function of the problem is unbounded, i.e.
98 /// there is a directed cycle having negative total cost and
99 /// infinite upper bound.
103 /// \brief Constants for selecting the type of the supply constraints.
105 /// Enum type containing constants for selecting the supply type,
106 /// i.e. the direction of the inequalities in the supply/demand
107 /// constraints of the \ref min_cost_flow "minimum cost flow problem".
109 /// The default supply type is \c GEQ, the \c LEQ type can be
110 /// selected using \ref supplyType().
111 /// The equality form is a special case of both supply types.
113 /// This option means that there are <em>"greater or equal"</em>
114 /// supply/demand constraints in the definition of the problem.
116 /// This option means that there are <em>"less or equal"</em>
117 /// supply/demand constraints in the definition of the problem.
121 /// \brief Constants for selecting the pivot rule.
123 /// Enum type containing constants for selecting the pivot rule for
124 /// the \ref run() function.
126 /// \ref NetworkSimplex provides five different implementations for
127 /// the pivot strategy that significantly affects the running time
128 /// of the algorithm.
129 /// According to experimental tests conducted on various problem
130 /// instances, \ref BLOCK_SEARCH "Block Search" and
131 /// \ref ALTERING_LIST "Altering Candidate List" rules turned out
132 /// to be the most efficient.
133 /// Since \ref BLOCK_SEARCH "Block Search" is a simpler strategy that
134 /// seemed to be slightly more robust, it is used by default.
135 /// However, another pivot rule can easily be selected using the
136 /// \ref run() function with the proper parameter.
139 /// The \e First \e Eligible pivot rule.
140 /// The next eligible arc is selected in a wraparound fashion
141 /// in every iteration.
144 /// The \e Best \e Eligible pivot rule.
145 /// The best eligible arc is selected in every iteration.
148 /// The \e Block \e Search pivot rule.
149 /// A specified number of arcs are examined in every iteration
150 /// in a wraparound fashion and the best eligible arc is selected
154 /// The \e Candidate \e List pivot rule.
155 /// In a major iteration a candidate list is built from eligible arcs
156 /// in a wraparound fashion and in the following minor iterations
157 /// the best eligible arc is selected from this list.
160 /// The \e Altering \e Candidate \e List pivot rule.
161 /// It is a modified version of the Candidate List method.
162 /// It keeps only a few of the best eligible arcs from the former
163 /// candidate list and extends this list in every iteration.
169 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
171 typedef std::vector<int> IntVector;
172 typedef std::vector<Value> ValueVector;
173 typedef std::vector<Cost> CostVector;
174 typedef std::vector<signed char> CharVector;
175 // Note: vector<signed char> is used instead of vector<ArcState> and
176 // vector<ArcDirection> for efficiency reasons
178 // State constants for arcs
185 // Direction constants for tree arcs
193 // Data related to the underlying digraph
200 // Parameters of the problem
205 // Data structures for storing the digraph
221 // Data for storing the spanning tree structure
225 IntVector _rev_thread;
227 IntVector _last_succ;
228 CharVector _pred_dir;
230 IntVector _dirty_revs;
233 // Temporary data used in the current pivot iteration
234 int in_arc, join, u_in, v_in, u_out, v_out;
241 /// \brief Constant for infinite upper bounds (capacities).
243 /// Constant for infinite upper bounds (capacities).
244 /// It is \c std::numeric_limits<Value>::infinity() if available,
245 /// \c std::numeric_limits<Value>::max() otherwise.
250 // Implementation of the First Eligible pivot rule
251 class FirstEligiblePivotRule
255 // References to the NetworkSimplex class
256 const IntVector &_source;
257 const IntVector &_target;
258 const CostVector &_cost;
259 const CharVector &_state;
260 const CostVector &_pi;
270 FirstEligiblePivotRule(NetworkSimplex &ns) :
271 _source(ns._source), _target(ns._target),
272 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
273 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
277 // Find next entering arc
278 bool findEnteringArc() {
280 for (int e = _next_arc; e != _search_arc_num; ++e) {
281 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
288 for (int e = 0; e != _next_arc; ++e) {
289 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
299 }; //class FirstEligiblePivotRule
302 // Implementation of the Best Eligible pivot rule
303 class BestEligiblePivotRule
307 // References to the NetworkSimplex class
308 const IntVector &_source;
309 const IntVector &_target;
310 const CostVector &_cost;
311 const CharVector &_state;
312 const CostVector &_pi;
319 BestEligiblePivotRule(NetworkSimplex &ns) :
320 _source(ns._source), _target(ns._target),
321 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
322 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
325 // Find next entering arc
326 bool findEnteringArc() {
328 for (int e = 0; e != _search_arc_num; ++e) {
329 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
338 }; //class BestEligiblePivotRule
341 // Implementation of the Block Search pivot rule
342 class BlockSearchPivotRule
346 // References to the NetworkSimplex class
347 const IntVector &_source;
348 const IntVector &_target;
349 const CostVector &_cost;
350 const CharVector &_state;
351 const CostVector &_pi;
362 BlockSearchPivotRule(NetworkSimplex &ns) :
363 _source(ns._source), _target(ns._target),
364 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
365 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
368 // The main parameters of the pivot rule
369 const double BLOCK_SIZE_FACTOR = 1.0;
370 const int MIN_BLOCK_SIZE = 10;
372 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
373 std::sqrt(double(_search_arc_num))),
377 // Find next entering arc
378 bool findEnteringArc() {
380 int cnt = _block_size;
382 for (e = _next_arc; e != _search_arc_num; ++e) {
383 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
389 if (min < 0) goto search_end;
393 for (e = 0; e != _next_arc; ++e) {
394 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
400 if (min < 0) goto search_end;
404 if (min >= 0) return false;
411 }; //class BlockSearchPivotRule
414 // Implementation of the Candidate List pivot rule
415 class CandidateListPivotRule
419 // References to the NetworkSimplex class
420 const IntVector &_source;
421 const IntVector &_target;
422 const CostVector &_cost;
423 const CharVector &_state;
424 const CostVector &_pi;
429 IntVector _candidates;
430 int _list_length, _minor_limit;
431 int _curr_length, _minor_count;
437 CandidateListPivotRule(NetworkSimplex &ns) :
438 _source(ns._source), _target(ns._target),
439 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
440 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
443 // The main parameters of the pivot rule
444 const double LIST_LENGTH_FACTOR = 0.25;
445 const int MIN_LIST_LENGTH = 10;
446 const double MINOR_LIMIT_FACTOR = 0.1;
447 const int MIN_MINOR_LIMIT = 3;
449 _list_length = std::max( int(LIST_LENGTH_FACTOR *
450 std::sqrt(double(_search_arc_num))),
452 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
454 _curr_length = _minor_count = 0;
455 _candidates.resize(_list_length);
458 /// Find next entering arc
459 bool findEnteringArc() {
462 if (_curr_length > 0 && _minor_count < _minor_limit) {
463 // Minor iteration: select the best eligible arc from the
464 // current candidate list
467 for (int i = 0; i < _curr_length; ++i) {
469 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
475 _candidates[i--] = _candidates[--_curr_length];
478 if (min < 0) return true;
481 // Major iteration: build a new candidate list
484 for (e = _next_arc; e != _search_arc_num; ++e) {
485 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
487 _candidates[_curr_length++] = e;
492 if (_curr_length == _list_length) goto search_end;
495 for (e = 0; e != _next_arc; ++e) {
496 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
498 _candidates[_curr_length++] = e;
503 if (_curr_length == _list_length) goto search_end;
506 if (_curr_length == 0) return false;
514 }; //class CandidateListPivotRule
517 // Implementation of the Altering Candidate List pivot rule
518 class AlteringListPivotRule
522 // References to the NetworkSimplex class
523 const IntVector &_source;
524 const IntVector &_target;
525 const CostVector &_cost;
526 const CharVector &_state;
527 const CostVector &_pi;
532 int _block_size, _head_length, _curr_length;
534 IntVector _candidates;
535 CostVector _cand_cost;
537 // Functor class to compare arcs during sort of the candidate list
541 const CostVector &_map;
543 SortFunc(const CostVector &map) : _map(map) {}
544 bool operator()(int left, int right) {
545 return _map[left] < _map[right];
554 AlteringListPivotRule(NetworkSimplex &ns) :
555 _source(ns._source), _target(ns._target),
556 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
557 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
558 _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
560 // The main parameters of the pivot rule
561 const double BLOCK_SIZE_FACTOR = 1.0;
562 const int MIN_BLOCK_SIZE = 10;
563 const double HEAD_LENGTH_FACTOR = 0.01;
564 const int MIN_HEAD_LENGTH = 3;
566 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
567 std::sqrt(double(_search_arc_num))),
569 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
571 _candidates.resize(_head_length + _block_size);
575 // Find next entering arc
576 bool findEnteringArc() {
577 // Check the current candidate list
580 for (int i = 0; i != _curr_length; ++i) {
582 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
586 _candidates[i--] = _candidates[--_curr_length];
591 int cnt = _block_size;
592 int limit = _head_length;
594 for (e = _next_arc; e != _search_arc_num; ++e) {
595 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
598 _candidates[_curr_length++] = e;
601 if (_curr_length > limit) goto search_end;
606 for (e = 0; e != _next_arc; ++e) {
607 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
610 _candidates[_curr_length++] = e;
613 if (_curr_length > limit) goto search_end;
618 if (_curr_length == 0) return false;
622 // Perform partial sort operation on the candidate list
623 int new_length = std::min(_head_length + 1, _curr_length);
624 std::partial_sort(_candidates.begin(), _candidates.begin() + new_length,
625 _candidates.begin() + _curr_length, _sort_func);
627 // Select the entering arc and remove it from the list
628 _in_arc = _candidates[0];
630 _candidates[0] = _candidates[new_length - 1];
631 _curr_length = new_length - 1;
635 }; //class AlteringListPivotRule
639 /// \brief Constructor.
641 /// The constructor of the class.
643 /// \param graph The digraph the algorithm runs on.
644 /// \param arc_mixing Indicate if the arcs will be stored in a
645 /// mixed order in the internal data structure.
646 /// In general, it leads to similar performance as using the original
647 /// arc order, but it makes the algorithm more robust and in special
648 /// cases, even significantly faster. Therefore, it is enabled by default.
649 NetworkSimplex(const GR& graph, bool arc_mixing = true) :
650 _graph(graph), _node_id(graph), _arc_id(graph),
651 _arc_mixing(arc_mixing),
652 MAX(std::numeric_limits<Value>::max()),
653 INF(std::numeric_limits<Value>::has_infinity ?
654 std::numeric_limits<Value>::infinity() : MAX)
656 // Check the number types
657 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
658 "The flow type of NetworkSimplex must be signed");
659 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
660 "The cost type of NetworkSimplex must be signed");
662 // Reset data structures
667 /// The parameters of the algorithm can be specified using these
672 /// \brief Set the lower bounds on the arcs.
674 /// This function sets the lower bounds on the arcs.
675 /// If it is not used before calling \ref run(), the lower bounds
676 /// will be set to zero on all arcs.
678 /// \param map An arc map storing the lower bounds.
679 /// Its \c Value type must be convertible to the \c Value type
680 /// of the algorithm.
682 /// \return <tt>(*this)</tt>
683 template <typename LowerMap>
684 NetworkSimplex& lowerMap(const LowerMap& map) {
686 for (ArcIt a(_graph); a != INVALID; ++a) {
687 _lower[_arc_id[a]] = map[a];
692 /// \brief Set the upper bounds (capacities) on the arcs.
694 /// This function sets the upper bounds (capacities) on the arcs.
695 /// If it is not used before calling \ref run(), the upper bounds
696 /// will be set to \ref INF on all arcs (i.e. the flow value will be
697 /// unbounded from above).
699 /// \param map An arc map storing the upper bounds.
700 /// Its \c Value type must be convertible to the \c Value type
701 /// of the algorithm.
703 /// \return <tt>(*this)</tt>
704 template<typename UpperMap>
705 NetworkSimplex& upperMap(const UpperMap& map) {
706 for (ArcIt a(_graph); a != INVALID; ++a) {
707 _upper[_arc_id[a]] = map[a];
712 /// \brief Set the costs of the arcs.
714 /// This function sets the costs of the arcs.
715 /// If it is not used before calling \ref run(), the costs
716 /// will be set to \c 1 on all arcs.
718 /// \param map An arc map storing the costs.
719 /// Its \c Value type must be convertible to the \c Cost type
720 /// of the algorithm.
722 /// \return <tt>(*this)</tt>
723 template<typename CostMap>
724 NetworkSimplex& costMap(const CostMap& map) {
725 for (ArcIt a(_graph); a != INVALID; ++a) {
726 _cost[_arc_id[a]] = map[a];
731 /// \brief Set the supply values of the nodes.
733 /// This function sets the supply values of the nodes.
734 /// If neither this function nor \ref stSupply() is used before
735 /// calling \ref run(), the supply of each node will be set to zero.
737 /// \param map A node map storing the supply values.
738 /// Its \c Value type must be convertible to the \c Value type
739 /// of the algorithm.
741 /// \return <tt>(*this)</tt>
744 template<typename SupplyMap>
745 NetworkSimplex& supplyMap(const SupplyMap& map) {
746 for (NodeIt n(_graph); n != INVALID; ++n) {
747 _supply[_node_id[n]] = map[n];
752 /// \brief Set single source and target nodes and a supply value.
754 /// This function sets a single source node and a single target node
755 /// and the required flow value.
756 /// If neither this function nor \ref supplyMap() is used before
757 /// calling \ref run(), the supply of each node will be set to zero.
759 /// Using this function has the same effect as using \ref supplyMap()
760 /// with a map in which \c k is assigned to \c s, \c -k is
761 /// assigned to \c t and all other nodes have zero supply value.
763 /// \param s The source node.
764 /// \param t The target node.
765 /// \param k The required amount of flow from node \c s to node \c t
766 /// (i.e. the supply of \c s and the demand of \c t).
768 /// \return <tt>(*this)</tt>
769 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
770 for (int i = 0; i != _node_num; ++i) {
773 _supply[_node_id[s]] = k;
774 _supply[_node_id[t]] = -k;
778 /// \brief Set the type of the supply constraints.
780 /// This function sets the type of the supply/demand constraints.
781 /// If it is not used before calling \ref run(), the \ref GEQ supply
782 /// type will be used.
784 /// For more information, see \ref SupplyType.
786 /// \return <tt>(*this)</tt>
787 NetworkSimplex& supplyType(SupplyType supply_type) {
788 _stype = supply_type;
794 /// \name Execution Control
795 /// The algorithm can be executed using \ref run().
799 /// \brief Run the algorithm.
801 /// This function runs the algorithm.
802 /// The paramters can be specified using functions \ref lowerMap(),
803 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
804 /// \ref supplyType().
807 /// NetworkSimplex<ListDigraph> ns(graph);
808 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
809 /// .supplyMap(sup).run();
812 /// This function can be called more than once. All the given parameters
813 /// are kept for the next call, unless \ref resetParams() or \ref reset()
814 /// is used, thus only the modified parameters have to be set again.
815 /// If the underlying digraph was also modified after the construction
816 /// of the class (or the last \ref reset() call), then the \ref reset()
817 /// function must be called.
819 /// \param pivot_rule The pivot rule that will be used during the
820 /// algorithm. For more information, see \ref PivotRule.
822 /// \return \c INFEASIBLE if no feasible flow exists,
823 /// \n \c OPTIMAL if the problem has optimal solution
824 /// (i.e. it is feasible and bounded), and the algorithm has found
825 /// optimal flow and node potentials (primal and dual solutions),
826 /// \n \c UNBOUNDED if the objective function of the problem is
827 /// unbounded, i.e. there is a directed cycle having negative total
828 /// cost and infinite upper bound.
830 /// \see ProblemType, PivotRule
831 /// \see resetParams(), reset()
832 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
833 if (!init()) return INFEASIBLE;
834 return start(pivot_rule);
837 /// \brief Reset all the parameters that have been given before.
839 /// This function resets all the paramaters that have been given
840 /// before using functions \ref lowerMap(), \ref upperMap(),
841 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
843 /// It is useful for multiple \ref run() calls. Basically, all the given
844 /// parameters are kept for the next \ref run() call, unless
845 /// \ref resetParams() or \ref reset() is used.
846 /// If the underlying digraph was also modified after the construction
847 /// of the class or the last \ref reset() call, then the \ref reset()
848 /// function must be used, otherwise \ref resetParams() is sufficient.
852 /// NetworkSimplex<ListDigraph> ns(graph);
855 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
856 /// .supplyMap(sup).run();
858 /// // Run again with modified cost map (resetParams() is not called,
859 /// // so only the cost map have to be set again)
861 /// ns.costMap(cost).run();
863 /// // Run again from scratch using resetParams()
864 /// // (the lower bounds will be set to zero on all arcs)
865 /// ns.resetParams();
866 /// ns.upperMap(capacity).costMap(cost)
867 /// .supplyMap(sup).run();
870 /// \return <tt>(*this)</tt>
872 /// \see reset(), run()
873 NetworkSimplex& resetParams() {
874 for (int i = 0; i != _node_num; ++i) {
877 for (int i = 0; i != _arc_num; ++i) {
887 /// \brief Reset the internal data structures and all the parameters
888 /// that have been given before.
890 /// This function resets the internal data structures and all the
891 /// paramaters that have been given before using functions \ref lowerMap(),
892 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
893 /// \ref supplyType().
895 /// It is useful for multiple \ref run() calls. Basically, all the given
896 /// parameters are kept for the next \ref run() call, unless
897 /// \ref resetParams() or \ref reset() is used.
898 /// If the underlying digraph was also modified after the construction
899 /// of the class or the last \ref reset() call, then the \ref reset()
900 /// function must be used, otherwise \ref resetParams() is sufficient.
902 /// See \ref resetParams() for examples.
904 /// \return <tt>(*this)</tt>
906 /// \see resetParams(), run()
907 NetworkSimplex& reset() {
909 _node_num = countNodes(_graph);
910 _arc_num = countArcs(_graph);
911 int all_node_num = _node_num + 1;
912 int max_arc_num = _arc_num + 2 * _node_num;
914 _source.resize(max_arc_num);
915 _target.resize(max_arc_num);
917 _lower.resize(_arc_num);
918 _upper.resize(_arc_num);
919 _cap.resize(max_arc_num);
920 _cost.resize(max_arc_num);
921 _supply.resize(all_node_num);
922 _flow.resize(max_arc_num);
923 _pi.resize(all_node_num);
925 _parent.resize(all_node_num);
926 _pred.resize(all_node_num);
927 _pred_dir.resize(all_node_num);
928 _thread.resize(all_node_num);
929 _rev_thread.resize(all_node_num);
930 _succ_num.resize(all_node_num);
931 _last_succ.resize(all_node_num);
932 _state.resize(max_arc_num);
936 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
940 // Store the arcs in a mixed order
941 const int skip = std::max(_arc_num / _node_num, 3);
943 for (ArcIt a(_graph); a != INVALID; ++a) {
945 _source[i] = _node_id[_graph.source(a)];
946 _target[i] = _node_id[_graph.target(a)];
947 if ((i += skip) >= _arc_num) i = ++j;
950 // Store the arcs in the original order
952 for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
954 _source[i] = _node_id[_graph.source(a)];
955 _target[i] = _node_id[_graph.target(a)];
966 /// \name Query Functions
967 /// The results of the algorithm can be obtained using these
969 /// The \ref run() function must be called before using them.
973 /// \brief Return the total cost of the found flow.
975 /// This function returns the total cost of the found flow.
976 /// Its complexity is O(e).
978 /// \note The return type of the function can be specified as a
979 /// template parameter. For example,
981 /// ns.totalCost<double>();
983 /// It is useful if the total cost cannot be stored in the \c Cost
984 /// type of the algorithm, which is the default return type of the
987 /// \pre \ref run() must be called before using this function.
988 template <typename Number>
989 Number totalCost() const {
991 for (ArcIt a(_graph); a != INVALID; ++a) {
993 c += Number(_flow[i]) * Number(_cost[i]);
999 Cost totalCost() const {
1000 return totalCost<Cost>();
1004 /// \brief Return the flow on the given arc.
1006 /// This function returns the flow on the given arc.
1008 /// \pre \ref run() must be called before using this function.
1009 Value flow(const Arc& a) const {
1010 return _flow[_arc_id[a]];
1013 /// \brief Copy the flow values (the primal solution) into the
1016 /// This function copies the flow value on each arc into the given
1017 /// map. The \c Value type of the algorithm must be convertible to
1018 /// the \c Value type of the map.
1020 /// \pre \ref run() must be called before using this function.
1021 template <typename FlowMap>
1022 void flowMap(FlowMap &map) const {
1023 for (ArcIt a(_graph); a != INVALID; ++a) {
1024 map.set(a, _flow[_arc_id[a]]);
1028 /// \brief Return the potential (dual value) of the given node.
1030 /// This function returns the potential (dual value) of the
1033 /// \pre \ref run() must be called before using this function.
1034 Cost potential(const Node& n) const {
1035 return _pi[_node_id[n]];
1038 /// \brief Copy the potential values (the dual solution) into the
1041 /// This function copies the potential (dual value) of each node
1042 /// into the given map.
1043 /// The \c Cost type of the algorithm must be convertible to the
1044 /// \c Value type of the map.
1046 /// \pre \ref run() must be called before using this function.
1047 template <typename PotentialMap>
1048 void potentialMap(PotentialMap &map) const {
1049 for (NodeIt n(_graph); n != INVALID; ++n) {
1050 map.set(n, _pi[_node_id[n]]);
1058 // Initialize internal data structures
1060 if (_node_num == 0) return false;
1062 // Check the sum of supply values
1064 for (int i = 0; i != _node_num; ++i) {
1065 _sum_supply += _supply[i];
1067 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1068 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1070 // Remove non-zero lower bounds
1072 for (int i = 0; i != _arc_num; ++i) {
1073 Value c = _lower[i];
1075 _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1077 _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1079 _supply[_source[i]] -= c;
1080 _supply[_target[i]] += c;
1083 for (int i = 0; i != _arc_num; ++i) {
1084 _cap[i] = _upper[i];
1088 // Initialize artifical cost
1090 if (std::numeric_limits<Cost>::is_exact) {
1091 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1094 for (int i = 0; i != _arc_num; ++i) {
1095 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1097 ART_COST = (ART_COST + 1) * _node_num;
1100 // Initialize arc maps
1101 for (int i = 0; i != _arc_num; ++i) {
1103 _state[i] = STATE_LOWER;
1106 // Set data for the artificial root node
1108 _parent[_root] = -1;
1111 _rev_thread[0] = _root;
1112 _succ_num[_root] = _node_num + 1;
1113 _last_succ[_root] = _root - 1;
1114 _supply[_root] = -_sum_supply;
1117 // Add artificial arcs and initialize the spanning tree data structure
1118 if (_sum_supply == 0) {
1119 // EQ supply constraints
1120 _search_arc_num = _arc_num;
1121 _all_arc_num = _arc_num + _node_num;
1122 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1126 _rev_thread[u + 1] = u;
1130 _state[e] = STATE_TREE;
1131 if (_supply[u] >= 0) {
1132 _pred_dir[u] = DIR_UP;
1136 _flow[e] = _supply[u];
1139 _pred_dir[u] = DIR_DOWN;
1143 _flow[e] = -_supply[u];
1144 _cost[e] = ART_COST;
1148 else if (_sum_supply > 0) {
1149 // LEQ supply constraints
1150 _search_arc_num = _arc_num + _node_num;
1151 int f = _arc_num + _node_num;
1152 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1155 _rev_thread[u + 1] = u;
1158 if (_supply[u] >= 0) {
1159 _pred_dir[u] = DIR_UP;
1165 _flow[e] = _supply[u];
1167 _state[e] = STATE_TREE;
1169 _pred_dir[u] = DIR_DOWN;
1175 _flow[f] = -_supply[u];
1176 _cost[f] = ART_COST;
1177 _state[f] = STATE_TREE;
1183 _state[e] = STATE_LOWER;
1190 // GEQ supply constraints
1191 _search_arc_num = _arc_num + _node_num;
1192 int f = _arc_num + _node_num;
1193 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1196 _rev_thread[u + 1] = u;
1199 if (_supply[u] <= 0) {
1200 _pred_dir[u] = DIR_DOWN;
1206 _flow[e] = -_supply[u];
1208 _state[e] = STATE_TREE;
1210 _pred_dir[u] = DIR_UP;
1216 _flow[f] = _supply[u];
1217 _state[f] = STATE_TREE;
1218 _cost[f] = ART_COST;
1224 _state[e] = STATE_LOWER;
1234 // Find the join node
1235 void findJoinNode() {
1236 int u = _source[in_arc];
1237 int v = _target[in_arc];
1239 if (_succ_num[u] < _succ_num[v]) {
1248 // Find the leaving arc of the cycle and returns true if the
1249 // leaving arc is not the same as the entering arc
1250 bool findLeavingArc() {
1251 // Initialize first and second nodes according to the direction
1254 if (_state[in_arc] == STATE_LOWER) {
1255 first = _source[in_arc];
1256 second = _target[in_arc];
1258 first = _target[in_arc];
1259 second = _source[in_arc];
1261 delta = _cap[in_arc];
1266 // Search the cycle form the first node to the join node
1267 for (int u = first; u != join; u = _parent[u]) {
1270 if (_pred_dir[u] == DIR_DOWN) {
1272 d = c >= MAX ? INF : c - d;
1281 // Search the cycle form the second node to the join node
1282 for (int u = second; u != join; u = _parent[u]) {
1285 if (_pred_dir[u] == DIR_UP) {
1287 d = c >= MAX ? INF : c - d;
1306 // Change _flow and _state vectors
1307 void changeFlow(bool change) {
1308 // Augment along the cycle
1310 Value val = _state[in_arc] * delta;
1311 _flow[in_arc] += val;
1312 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1313 _flow[_pred[u]] -= _pred_dir[u] * val;
1315 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1316 _flow[_pred[u]] += _pred_dir[u] * val;
1319 // Update the state of the entering and leaving arcs
1321 _state[in_arc] = STATE_TREE;
1322 _state[_pred[u_out]] =
1323 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1325 _state[in_arc] = -_state[in_arc];
1329 // Update the tree structure
1330 void updateTreeStructure() {
1331 int old_rev_thread = _rev_thread[u_out];
1332 int old_succ_num = _succ_num[u_out];
1333 int old_last_succ = _last_succ[u_out];
1334 v_out = _parent[u_out];
1336 // Check if u_in and u_out coincide
1337 if (u_in == u_out) {
1338 // Update _parent, _pred, _pred_dir
1339 _parent[u_in] = v_in;
1340 _pred[u_in] = in_arc;
1341 _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1343 // Update _thread and _rev_thread
1344 if (_thread[v_in] != u_out) {
1345 int after = _thread[old_last_succ];
1346 _thread[old_rev_thread] = after;
1347 _rev_thread[after] = old_rev_thread;
1348 after = _thread[v_in];
1349 _thread[v_in] = u_out;
1350 _rev_thread[u_out] = v_in;
1351 _thread[old_last_succ] = after;
1352 _rev_thread[after] = old_last_succ;
1355 // Handle the case when old_rev_thread equals to v_in
1356 // (it also means that join and v_out coincide)
1357 int thread_continue = old_rev_thread == v_in ?
1358 _thread[old_last_succ] : _thread[v_in];
1360 // Update _thread and _parent along the stem nodes (i.e. the nodes
1361 // between u_in and u_out, whose parent have to be changed)
1362 int stem = u_in; // the current stem node
1363 int par_stem = v_in; // the new parent of stem
1364 int next_stem; // the next stem node
1365 int last = _last_succ[u_in]; // the last successor of stem
1366 int before, after = _thread[last];
1367 _thread[v_in] = u_in;
1368 _dirty_revs.clear();
1369 _dirty_revs.push_back(v_in);
1370 while (stem != u_out) {
1371 // Insert the next stem node into the thread list
1372 next_stem = _parent[stem];
1373 _thread[last] = next_stem;
1374 _dirty_revs.push_back(last);
1376 // Remove the subtree of stem from the thread list
1377 before = _rev_thread[stem];
1378 _thread[before] = after;
1379 _rev_thread[after] = before;
1381 // Change the parent node and shift stem nodes
1382 _parent[stem] = par_stem;
1386 // Update last and after
1387 last = _last_succ[stem] == _last_succ[par_stem] ?
1388 _rev_thread[par_stem] : _last_succ[stem];
1389 after = _thread[last];
1391 _parent[u_out] = par_stem;
1392 _thread[last] = thread_continue;
1393 _rev_thread[thread_continue] = last;
1394 _last_succ[u_out] = last;
1396 // Remove the subtree of u_out from the thread list except for
1397 // the case when old_rev_thread equals to v_in
1398 if (old_rev_thread != v_in) {
1399 _thread[old_rev_thread] = after;
1400 _rev_thread[after] = old_rev_thread;
1403 // Update _rev_thread using the new _thread values
1404 for (int i = 0; i != int(_dirty_revs.size()); ++i) {
1405 int u = _dirty_revs[i];
1406 _rev_thread[_thread[u]] = u;
1409 // Update _pred, _pred_dir, _last_succ and _succ_num for the
1410 // stem nodes from u_out to u_in
1411 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1412 for (int u = u_out, p = _parent[u]; u != u_in; u = p, p = _parent[u]) {
1413 _pred[u] = _pred[p];
1414 _pred_dir[u] = -_pred_dir[p];
1415 tmp_sc += _succ_num[u] - _succ_num[p];
1416 _succ_num[u] = tmp_sc;
1417 _last_succ[p] = tmp_ls;
1419 _pred[u_in] = in_arc;
1420 _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1421 _succ_num[u_in] = old_succ_num;
1424 // Update _last_succ from v_in towards the root
1425 int up_limit_out = _last_succ[join] == v_in ? join : -1;
1426 int last_succ_out = _last_succ[u_out];
1427 for (int u = v_in; u != -1 && _last_succ[u] == v_in; u = _parent[u]) {
1428 _last_succ[u] = last_succ_out;
1431 // Update _last_succ from v_out towards the root
1432 if (join != old_rev_thread && v_in != old_rev_thread) {
1433 for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1435 _last_succ[u] = old_rev_thread;
1438 else if (last_succ_out != old_last_succ) {
1439 for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1441 _last_succ[u] = last_succ_out;
1445 // Update _succ_num from v_in to join
1446 for (int u = v_in; u != join; u = _parent[u]) {
1447 _succ_num[u] += old_succ_num;
1449 // Update _succ_num from v_out to join
1450 for (int u = v_out; u != join; u = _parent[u]) {
1451 _succ_num[u] -= old_succ_num;
1455 // Update potentials in the subtree that has been moved
1456 void updatePotential() {
1457 Cost sigma = _pi[v_in] - _pi[u_in] -
1458 _pred_dir[u_in] * _cost[in_arc];
1459 int end = _thread[_last_succ[u_in]];
1460 for (int u = u_in; u != end; u = _thread[u]) {
1465 // Heuristic initial pivots
1466 bool initialPivots() {
1467 Value curr, total = 0;
1468 std::vector<Node> supply_nodes, demand_nodes;
1469 for (NodeIt u(_graph); u != INVALID; ++u) {
1470 curr = _supply[_node_id[u]];
1473 supply_nodes.push_back(u);
1475 else if (curr < 0) {
1476 demand_nodes.push_back(u);
1479 if (_sum_supply > 0) total -= _sum_supply;
1480 if (total <= 0) return true;
1482 IntVector arc_vector;
1483 if (_sum_supply >= 0) {
1484 if (supply_nodes.size() == 1 && demand_nodes.size() == 1) {
1485 // Perform a reverse graph search from the sink to the source
1486 typename GR::template NodeMap<bool> reached(_graph, false);
1487 Node s = supply_nodes[0], t = demand_nodes[0];
1488 std::vector<Node> stack;
1491 while (!stack.empty()) {
1492 Node u, v = stack.back();
1495 for (InArcIt a(_graph, v); a != INVALID; ++a) {
1496 if (reached[u = _graph.source(a)]) continue;
1498 if (_cap[j] >= total) {
1499 arc_vector.push_back(j);
1506 // Find the min. cost incoming arc for each demand node
1507 for (int i = 0; i != int(demand_nodes.size()); ++i) {
1508 Node v = demand_nodes[i];
1509 Cost c, min_cost = std::numeric_limits<Cost>::max();
1510 Arc min_arc = INVALID;
1511 for (InArcIt a(_graph, v); a != INVALID; ++a) {
1512 c = _cost[_arc_id[a]];
1518 if (min_arc != INVALID) {
1519 arc_vector.push_back(_arc_id[min_arc]);
1524 // Find the min. cost outgoing arc for each supply node
1525 for (int i = 0; i != int(supply_nodes.size()); ++i) {
1526 Node u = supply_nodes[i];
1527 Cost c, min_cost = std::numeric_limits<Cost>::max();
1528 Arc min_arc = INVALID;
1529 for (OutArcIt a(_graph, u); a != INVALID; ++a) {
1530 c = _cost[_arc_id[a]];
1536 if (min_arc != INVALID) {
1537 arc_vector.push_back(_arc_id[min_arc]);
1542 // Perform heuristic initial pivots
1543 for (int i = 0; i != int(arc_vector.size()); ++i) {
1544 in_arc = arc_vector[i];
1545 if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -
1546 _pi[_target[in_arc]]) >= 0) continue;
1548 bool change = findLeavingArc();
1549 if (delta >= MAX) return false;
1552 updateTreeStructure();
1559 // Execute the algorithm
1560 ProblemType start(PivotRule pivot_rule) {
1561 // Select the pivot rule implementation
1562 switch (pivot_rule) {
1563 case FIRST_ELIGIBLE:
1564 return start<FirstEligiblePivotRule>();
1566 return start<BestEligiblePivotRule>();
1568 return start<BlockSearchPivotRule>();
1569 case CANDIDATE_LIST:
1570 return start<CandidateListPivotRule>();
1572 return start<AlteringListPivotRule>();
1574 return INFEASIBLE; // avoid warning
1577 template <typename PivotRuleImpl>
1578 ProblemType start() {
1579 PivotRuleImpl pivot(*this);
1581 // Perform heuristic initial pivots
1582 if (!initialPivots()) return UNBOUNDED;
1584 // Execute the Network Simplex algorithm
1585 while (pivot.findEnteringArc()) {
1587 bool change = findLeavingArc();
1588 if (delta >= MAX) return UNBOUNDED;
1591 updateTreeStructure();
1596 // Check feasibility
1597 for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1598 if (_flow[e] != 0) return INFEASIBLE;
1601 // Transform the solution and the supply map to the original form
1603 for (int i = 0; i != _arc_num; ++i) {
1604 Value c = _lower[i];
1607 _supply[_source[i]] += c;
1608 _supply[_target[i]] -= c;
1613 // Shift potentials to meet the requirements of the GEQ/LEQ type
1614 // optimality conditions
1615 if (_sum_supply == 0) {
1616 if (_stype == GEQ) {
1617 Cost max_pot = -std::numeric_limits<Cost>::max();
1618 for (int i = 0; i != _node_num; ++i) {
1619 if (_pi[i] > max_pot) max_pot = _pi[i];
1622 for (int i = 0; i != _node_num; ++i)
1626 Cost min_pot = std::numeric_limits<Cost>::max();
1627 for (int i = 0; i != _node_num; ++i) {
1628 if (_pi[i] < min_pot) min_pot = _pi[i];
1631 for (int i = 0; i != _node_num; ++i)
1640 }; //class NetworkSimplex
1646 #endif //LEMON_NETWORK_SIMPLEX_H