1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_NETWORK_SIMPLEX_H
20 #define LEMON_NETWORK_SIMPLEX_H
22 /// \ingroup min_cost_flow_algs
25 /// \brief Network Simplex algorithm for finding a minimum cost flow.
31 #include <lemon/core.h>
32 #include <lemon/math.h>
36 /// \addtogroup min_cost_flow_algs
39 /// \brief Implementation of the primal Network Simplex algorithm
40 /// for finding a \ref min_cost_flow "minimum cost flow".
42 /// \ref NetworkSimplex implements the primal Network Simplex algorithm
43 /// for finding a \ref min_cost_flow "minimum cost flow"
44 /// \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, %NetworkSimplex is the fastest implementation available
51 /// in LEMON for this problem.
52 /// Moreover, it supports both directions of the supply/demand inequality
53 /// constraints. For more information, see \ref SupplyType.
55 /// Most of the parameters of the problem (except for the digraph)
56 /// can be given using separate functions, and the algorithm can be
57 /// executed using the \ref run() function. If some parameters are not
58 /// specified, then default values will be used.
60 /// \tparam GR The digraph type the algorithm runs on.
61 /// \tparam V The number type used for flow amounts, capacity bounds
62 /// and supply values in the algorithm. By default, it is \c int.
63 /// \tparam C The number type used for costs and potentials in the
64 /// algorithm. By default, it is the same as \c V.
66 /// \warning Both number types must be signed and all input data must
69 /// \note %NetworkSimplex provides five different pivot rule
70 /// implementations, from which the most efficient one is used
71 /// by default. For more information, see \ref PivotRule.
72 template <typename GR, typename V = int, typename C = V>
77 /// The type of the flow amounts, capacity bounds and supply values
79 /// The type of the arc costs
84 /// \brief Problem type constants for the \c run() function.
86 /// Enum type containing the problem type constants that can be
87 /// returned by the \ref run() function of the algorithm.
89 /// The problem has no feasible solution (flow).
91 /// The problem has optimal solution (i.e. it is feasible and
92 /// bounded), and the algorithm has found optimal flow and node
93 /// potentials (primal and dual solutions).
95 /// The objective function of the problem is unbounded, i.e.
96 /// there is a directed cycle having negative total cost and
97 /// infinite upper bound.
101 /// \brief Constants for selecting the type of the supply constraints.
103 /// Enum type containing constants for selecting the supply type,
104 /// i.e. the direction of the inequalities in the supply/demand
105 /// constraints of the \ref min_cost_flow "minimum cost flow problem".
107 /// The default supply type is \c GEQ, the \c LEQ type can be
108 /// selected using \ref supplyType().
109 /// The equality form is a special case of both supply types.
111 /// This option means that there are <em>"greater or equal"</em>
112 /// supply/demand constraints in the definition of the problem.
114 /// This option means that there are <em>"less or equal"</em>
115 /// supply/demand constraints in the definition of the problem.
119 /// \brief Constants for selecting the pivot rule.
121 /// Enum type containing constants for selecting the pivot rule for
122 /// the \ref run() function.
124 /// \ref NetworkSimplex provides five different pivot rule
125 /// implementations that significantly affect the running time
126 /// of the algorithm.
127 /// By default, \ref BLOCK_SEARCH "Block Search" is used, which
128 /// proved to be the most efficient and the most robust on various
130 /// However, another pivot rule can be selected using the \ref run()
131 /// function with the proper parameter.
134 /// The \e First \e Eligible pivot rule.
135 /// The next eligible arc is selected in a wraparound fashion
136 /// in every iteration.
139 /// The \e Best \e Eligible pivot rule.
140 /// The best eligible arc is selected in every iteration.
143 /// The \e Block \e Search pivot rule.
144 /// A specified number of arcs are examined in every iteration
145 /// in a wraparound fashion and the best eligible arc is selected
149 /// The \e Candidate \e List pivot rule.
150 /// In a major iteration a candidate list is built from eligible arcs
151 /// in a wraparound fashion and in the following minor iterations
152 /// the best eligible arc is selected from this list.
155 /// The \e Altering \e Candidate \e List pivot rule.
156 /// It is a modified version of the Candidate List method.
157 /// It keeps only the several best eligible arcs from the former
158 /// candidate list and extends this list in every iteration.
164 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
166 typedef std::vector<int> IntVector;
167 typedef std::vector<Value> ValueVector;
168 typedef std::vector<Cost> CostVector;
169 typedef std::vector<char> BoolVector;
170 // Note: vector<char> is used instead of vector<bool> for efficiency reasons
172 // State constants for arcs
181 // Data related to the underlying digraph
188 // Parameters of the problem
193 // Data structures for storing the digraph
209 // Data for storing the spanning tree structure
213 IntVector _rev_thread;
215 IntVector _last_succ;
216 IntVector _dirty_revs;
221 // Temporary data used in the current pivot iteration
222 int in_arc, join, u_in, v_in, u_out, v_out;
223 int first, second, right, last;
224 int stem, par_stem, new_stem;
231 /// \brief Constant for infinite upper bounds (capacities).
233 /// Constant for infinite upper bounds (capacities).
234 /// It is \c std::numeric_limits<Value>::infinity() if available,
235 /// \c std::numeric_limits<Value>::max() otherwise.
240 // Implementation of the First Eligible pivot rule
241 class FirstEligiblePivotRule
245 // References to the NetworkSimplex class
246 const IntVector &_source;
247 const IntVector &_target;
248 const CostVector &_cost;
249 const BoolVector &_state;
250 const CostVector &_pi;
260 FirstEligiblePivotRule(NetworkSimplex &ns) :
261 _source(ns._source), _target(ns._target),
262 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
263 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
267 // Find next entering arc
268 bool findEnteringArc() {
270 for (int e = _next_arc; e != _search_arc_num; ++e) {
271 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
278 for (int e = 0; e != _next_arc; ++e) {
279 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
289 }; //class FirstEligiblePivotRule
292 // Implementation of the Best Eligible pivot rule
293 class BestEligiblePivotRule
297 // References to the NetworkSimplex class
298 const IntVector &_source;
299 const IntVector &_target;
300 const CostVector &_cost;
301 const BoolVector &_state;
302 const CostVector &_pi;
309 BestEligiblePivotRule(NetworkSimplex &ns) :
310 _source(ns._source), _target(ns._target),
311 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
312 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
315 // Find next entering arc
316 bool findEnteringArc() {
318 for (int e = 0; e != _search_arc_num; ++e) {
319 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
328 }; //class BestEligiblePivotRule
331 // Implementation of the Block Search pivot rule
332 class BlockSearchPivotRule
336 // References to the NetworkSimplex class
337 const IntVector &_source;
338 const IntVector &_target;
339 const CostVector &_cost;
340 const BoolVector &_state;
341 const CostVector &_pi;
352 BlockSearchPivotRule(NetworkSimplex &ns) :
353 _source(ns._source), _target(ns._target),
354 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
355 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
358 // The main parameters of the pivot rule
359 const double BLOCK_SIZE_FACTOR = 1.0;
360 const int MIN_BLOCK_SIZE = 10;
362 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
363 std::sqrt(double(_search_arc_num))),
367 // Find next entering arc
368 bool findEnteringArc() {
370 int cnt = _block_size;
372 for (e = _next_arc; e != _search_arc_num; ++e) {
373 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
379 if (min < 0) goto search_end;
383 for (e = 0; e != _next_arc; ++e) {
384 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
390 if (min < 0) goto search_end;
394 if (min >= 0) return false;
401 }; //class BlockSearchPivotRule
404 // Implementation of the Candidate List pivot rule
405 class CandidateListPivotRule
409 // References to the NetworkSimplex class
410 const IntVector &_source;
411 const IntVector &_target;
412 const CostVector &_cost;
413 const BoolVector &_state;
414 const CostVector &_pi;
419 IntVector _candidates;
420 int _list_length, _minor_limit;
421 int _curr_length, _minor_count;
427 CandidateListPivotRule(NetworkSimplex &ns) :
428 _source(ns._source), _target(ns._target),
429 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
430 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
433 // The main parameters of the pivot rule
434 const double LIST_LENGTH_FACTOR = 0.25;
435 const int MIN_LIST_LENGTH = 10;
436 const double MINOR_LIMIT_FACTOR = 0.1;
437 const int MIN_MINOR_LIMIT = 3;
439 _list_length = std::max( int(LIST_LENGTH_FACTOR *
440 std::sqrt(double(_search_arc_num))),
442 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
444 _curr_length = _minor_count = 0;
445 _candidates.resize(_list_length);
448 /// Find next entering arc
449 bool findEnteringArc() {
452 if (_curr_length > 0 && _minor_count < _minor_limit) {
453 // Minor iteration: select the best eligible arc from the
454 // current candidate list
457 for (int i = 0; i < _curr_length; ++i) {
459 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
465 _candidates[i--] = _candidates[--_curr_length];
468 if (min < 0) return true;
471 // Major iteration: build a new candidate list
474 for (e = _next_arc; e != _search_arc_num; ++e) {
475 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
477 _candidates[_curr_length++] = e;
482 if (_curr_length == _list_length) goto search_end;
485 for (e = 0; e != _next_arc; ++e) {
486 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
488 _candidates[_curr_length++] = e;
493 if (_curr_length == _list_length) goto search_end;
496 if (_curr_length == 0) return false;
504 }; //class CandidateListPivotRule
507 // Implementation of the Altering Candidate List pivot rule
508 class AlteringListPivotRule
512 // References to the NetworkSimplex class
513 const IntVector &_source;
514 const IntVector &_target;
515 const CostVector &_cost;
516 const BoolVector &_state;
517 const CostVector &_pi;
522 int _block_size, _head_length, _curr_length;
524 IntVector _candidates;
525 CostVector _cand_cost;
527 // Functor class to compare arcs during sort of the candidate list
531 const CostVector &_map;
533 SortFunc(const CostVector &map) : _map(map) {}
534 bool operator()(int left, int right) {
535 return _map[left] > _map[right];
544 AlteringListPivotRule(NetworkSimplex &ns) :
545 _source(ns._source), _target(ns._target),
546 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
547 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
548 _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
550 // The main parameters of the pivot rule
551 const double BLOCK_SIZE_FACTOR = 1.0;
552 const int MIN_BLOCK_SIZE = 10;
553 const double HEAD_LENGTH_FACTOR = 0.1;
554 const int MIN_HEAD_LENGTH = 3;
556 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
557 std::sqrt(double(_search_arc_num))),
559 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
561 _candidates.resize(_head_length + _block_size);
565 // Find next entering arc
566 bool findEnteringArc() {
567 // Check the current candidate list
569 for (int i = 0; i != _curr_length; ++i) {
571 _cand_cost[e] = _state[e] *
572 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
573 if (_cand_cost[e] >= 0) {
574 _candidates[i--] = _candidates[--_curr_length];
579 int cnt = _block_size;
580 int limit = _head_length;
582 for (e = _next_arc; e != _search_arc_num; ++e) {
583 _cand_cost[e] = _state[e] *
584 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
585 if (_cand_cost[e] < 0) {
586 _candidates[_curr_length++] = e;
589 if (_curr_length > limit) goto search_end;
594 for (e = 0; e != _next_arc; ++e) {
595 _cand_cost[e] = _state[e] *
596 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
597 if (_cand_cost[e] < 0) {
598 _candidates[_curr_length++] = e;
601 if (_curr_length > limit) goto search_end;
606 if (_curr_length == 0) return false;
610 // Make heap of the candidate list (approximating a partial sort)
611 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
614 // Pop the first element of the heap
615 _in_arc = _candidates[0];
617 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
619 _curr_length = std::min(_head_length, _curr_length - 1);
623 }; //class AlteringListPivotRule
627 /// \brief Constructor.
629 /// The constructor of the class.
631 /// \param graph The digraph the algorithm runs on.
632 /// \param arc_mixing Indicate if the arcs have to be stored in a
633 /// mixed order in the internal data structure.
634 /// In special cases, it could lead to better overall performance,
635 /// but it is usually slower. Therefore it is disabled by default.
636 NetworkSimplex(const GR& graph, bool arc_mixing = false) :
637 _graph(graph), _node_id(graph), _arc_id(graph),
638 _arc_mixing(arc_mixing),
639 MAX(std::numeric_limits<Value>::max()),
640 INF(std::numeric_limits<Value>::has_infinity ?
641 std::numeric_limits<Value>::infinity() : MAX)
643 // Check the number types
644 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
645 "The flow type of NetworkSimplex must be signed");
646 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
647 "The cost type of NetworkSimplex must be signed");
649 // Reset data structures
654 /// The parameters of the algorithm can be specified using these
659 /// \brief Set the lower bounds on the arcs.
661 /// This function sets the lower bounds on the arcs.
662 /// If it is not used before calling \ref run(), the lower bounds
663 /// will be set to zero on all arcs.
665 /// \param map An arc map storing the lower bounds.
666 /// Its \c Value type must be convertible to the \c Value type
667 /// of the algorithm.
669 /// \return <tt>(*this)</tt>
670 template <typename LowerMap>
671 NetworkSimplex& lowerMap(const LowerMap& map) {
673 for (ArcIt a(_graph); a != INVALID; ++a) {
674 _lower[_arc_id[a]] = map[a];
679 /// \brief Set the upper bounds (capacities) on the arcs.
681 /// This function sets the upper bounds (capacities) on the arcs.
682 /// If it is not used before calling \ref run(), the upper bounds
683 /// will be set to \ref INF on all arcs (i.e. the flow value will be
684 /// unbounded from above).
686 /// \param map An arc map storing the upper bounds.
687 /// Its \c Value type must be convertible to the \c Value type
688 /// of the algorithm.
690 /// \return <tt>(*this)</tt>
691 template<typename UpperMap>
692 NetworkSimplex& upperMap(const UpperMap& map) {
693 for (ArcIt a(_graph); a != INVALID; ++a) {
694 _upper[_arc_id[a]] = map[a];
699 /// \brief Set the costs of the arcs.
701 /// This function sets the costs of the arcs.
702 /// If it is not used before calling \ref run(), the costs
703 /// will be set to \c 1 on all arcs.
705 /// \param map An arc map storing the costs.
706 /// Its \c Value type must be convertible to the \c Cost type
707 /// of the algorithm.
709 /// \return <tt>(*this)</tt>
710 template<typename CostMap>
711 NetworkSimplex& costMap(const CostMap& map) {
712 for (ArcIt a(_graph); a != INVALID; ++a) {
713 _cost[_arc_id[a]] = map[a];
718 /// \brief Set the supply values of the nodes.
720 /// This function sets the supply values of the nodes.
721 /// If neither this function nor \ref stSupply() is used before
722 /// calling \ref run(), the supply of each node will be set to zero.
724 /// \param map A node map storing the supply values.
725 /// Its \c Value type must be convertible to the \c Value type
726 /// of the algorithm.
728 /// \return <tt>(*this)</tt>
729 template<typename SupplyMap>
730 NetworkSimplex& supplyMap(const SupplyMap& map) {
731 for (NodeIt n(_graph); n != INVALID; ++n) {
732 _supply[_node_id[n]] = map[n];
737 /// \brief Set single source and target nodes and a supply value.
739 /// This function sets a single source node and a single target node
740 /// and the required flow value.
741 /// If neither this function nor \ref supplyMap() is used before
742 /// calling \ref run(), the supply of each node will be set to zero.
744 /// Using this function has the same effect as using \ref supplyMap()
745 /// with such a map in which \c k is assigned to \c s, \c -k is
746 /// assigned to \c t and all other nodes have zero supply value.
748 /// \param s The source node.
749 /// \param t The target node.
750 /// \param k The required amount of flow from node \c s to node \c t
751 /// (i.e. the supply of \c s and the demand of \c t).
753 /// \return <tt>(*this)</tt>
754 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
755 for (int i = 0; i != _node_num; ++i) {
758 _supply[_node_id[s]] = k;
759 _supply[_node_id[t]] = -k;
763 /// \brief Set the type of the supply constraints.
765 /// This function sets the type of the supply/demand constraints.
766 /// If it is not used before calling \ref run(), the \ref GEQ supply
767 /// type will be used.
769 /// For more information, see \ref SupplyType.
771 /// \return <tt>(*this)</tt>
772 NetworkSimplex& supplyType(SupplyType supply_type) {
773 _stype = supply_type;
779 /// \name Execution Control
780 /// The algorithm can be executed using \ref run().
784 /// \brief Run the algorithm.
786 /// This function runs the algorithm.
787 /// The paramters can be specified using functions \ref lowerMap(),
788 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
789 /// \ref supplyType().
792 /// NetworkSimplex<ListDigraph> ns(graph);
793 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
794 /// .supplyMap(sup).run();
797 /// This function can be called more than once. All the given parameters
798 /// are kept for the next call, unless \ref resetParams() or \ref reset()
799 /// is used, thus only the modified parameters have to be set again.
800 /// If the underlying digraph was also modified after the construction
801 /// of the class (or the last \ref reset() call), then the \ref reset()
802 /// function must be called.
804 /// \param pivot_rule The pivot rule that will be used during the
805 /// algorithm. For more information, see \ref PivotRule.
807 /// \return \c INFEASIBLE if no feasible flow exists,
808 /// \n \c OPTIMAL if the problem has optimal solution
809 /// (i.e. it is feasible and bounded), and the algorithm has found
810 /// optimal flow and node potentials (primal and dual solutions),
811 /// \n \c UNBOUNDED if the objective function of the problem is
812 /// unbounded, i.e. there is a directed cycle having negative total
813 /// cost and infinite upper bound.
815 /// \see ProblemType, PivotRule
816 /// \see resetParams(), reset()
817 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
818 if (!init()) return INFEASIBLE;
819 return start(pivot_rule);
822 /// \brief Reset all the parameters that have been given before.
824 /// This function resets all the paramaters that have been given
825 /// before using functions \ref lowerMap(), \ref upperMap(),
826 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
828 /// It is useful for multiple \ref run() calls. Basically, all the given
829 /// parameters are kept for the next \ref run() call, unless
830 /// \ref resetParams() or \ref reset() is used.
831 /// If the underlying digraph was also modified after the construction
832 /// of the class or the last \ref reset() call, then the \ref reset()
833 /// function must be used, otherwise \ref resetParams() is sufficient.
837 /// NetworkSimplex<ListDigraph> ns(graph);
840 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
841 /// .supplyMap(sup).run();
843 /// // Run again with modified cost map (resetParams() is not called,
844 /// // so only the cost map have to be set again)
846 /// ns.costMap(cost).run();
848 /// // Run again from scratch using resetParams()
849 /// // (the lower bounds will be set to zero on all arcs)
850 /// ns.resetParams();
851 /// ns.upperMap(capacity).costMap(cost)
852 /// .supplyMap(sup).run();
855 /// \return <tt>(*this)</tt>
857 /// \see reset(), run()
858 NetworkSimplex& resetParams() {
859 for (int i = 0; i != _node_num; ++i) {
862 for (int i = 0; i != _arc_num; ++i) {
872 /// \brief Reset the internal data structures and all the parameters
873 /// that have been given before.
875 /// This function resets the internal data structures and all the
876 /// paramaters that have been given before using functions \ref lowerMap(),
877 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
878 /// \ref supplyType().
880 /// It is useful for multiple \ref run() calls. Basically, all the given
881 /// parameters are kept for the next \ref run() call, unless
882 /// \ref resetParams() or \ref reset() is used.
883 /// If the underlying digraph was also modified after the construction
884 /// of the class or the last \ref reset() call, then the \ref reset()
885 /// function must be used, otherwise \ref resetParams() is sufficient.
887 /// See \ref resetParams() for examples.
889 /// \return <tt>(*this)</tt>
891 /// \see resetParams(), run()
892 NetworkSimplex& reset() {
894 _node_num = countNodes(_graph);
895 _arc_num = countArcs(_graph);
896 int all_node_num = _node_num + 1;
897 int max_arc_num = _arc_num + 2 * _node_num;
899 _source.resize(max_arc_num);
900 _target.resize(max_arc_num);
902 _lower.resize(_arc_num);
903 _upper.resize(_arc_num);
904 _cap.resize(max_arc_num);
905 _cost.resize(max_arc_num);
906 _supply.resize(all_node_num);
907 _flow.resize(max_arc_num);
908 _pi.resize(all_node_num);
910 _parent.resize(all_node_num);
911 _pred.resize(all_node_num);
912 _forward.resize(all_node_num);
913 _thread.resize(all_node_num);
914 _rev_thread.resize(all_node_num);
915 _succ_num.resize(all_node_num);
916 _last_succ.resize(all_node_num);
917 _state.resize(max_arc_num);
921 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
925 // Store the arcs in a mixed order
926 int k = std::max(int(std::sqrt(double(_arc_num))), 10);
928 for (ArcIt a(_graph); a != INVALID; ++a) {
930 _source[i] = _node_id[_graph.source(a)];
931 _target[i] = _node_id[_graph.target(a)];
932 if ((i += k) >= _arc_num) i = ++j;
935 // Store the arcs in the original order
937 for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
939 _source[i] = _node_id[_graph.source(a)];
940 _target[i] = _node_id[_graph.target(a)];
951 /// \name Query Functions
952 /// The results of the algorithm can be obtained using these
954 /// The \ref run() function must be called before using them.
958 /// \brief Return the total cost of the found flow.
960 /// This function returns the total cost of the found flow.
961 /// Its complexity is O(e).
963 /// \note The return type of the function can be specified as a
964 /// template parameter. For example,
966 /// ns.totalCost<double>();
968 /// It is useful if the total cost cannot be stored in the \c Cost
969 /// type of the algorithm, which is the default return type of the
972 /// \pre \ref run() must be called before using this function.
973 template <typename Number>
974 Number totalCost() const {
976 for (ArcIt a(_graph); a != INVALID; ++a) {
978 c += Number(_flow[i]) * Number(_cost[i]);
984 Cost totalCost() const {
985 return totalCost<Cost>();
989 /// \brief Return the flow on the given arc.
991 /// This function returns the flow on the given arc.
993 /// \pre \ref run() must be called before using this function.
994 Value flow(const Arc& a) const {
995 return _flow[_arc_id[a]];
998 /// \brief Return the flow map (the primal solution).
1000 /// This function copies the flow value on each arc into the given
1001 /// map. The \c Value type of the algorithm must be convertible to
1002 /// the \c Value type of the map.
1004 /// \pre \ref run() must be called before using this function.
1005 template <typename FlowMap>
1006 void flowMap(FlowMap &map) const {
1007 for (ArcIt a(_graph); a != INVALID; ++a) {
1008 map.set(a, _flow[_arc_id[a]]);
1012 /// \brief Return the potential (dual value) of the given node.
1014 /// This function returns the potential (dual value) of the
1017 /// \pre \ref run() must be called before using this function.
1018 Cost potential(const Node& n) const {
1019 return _pi[_node_id[n]];
1022 /// \brief Return the potential map (the dual solution).
1024 /// This function copies the potential (dual value) of each node
1025 /// into the given map.
1026 /// The \c Cost type of the algorithm must be convertible to the
1027 /// \c Value type of the map.
1029 /// \pre \ref run() must be called before using this function.
1030 template <typename PotentialMap>
1031 void potentialMap(PotentialMap &map) const {
1032 for (NodeIt n(_graph); n != INVALID; ++n) {
1033 map.set(n, _pi[_node_id[n]]);
1041 // Initialize internal data structures
1043 if (_node_num == 0) return false;
1045 // Check the sum of supply values
1047 for (int i = 0; i != _node_num; ++i) {
1048 _sum_supply += _supply[i];
1050 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1051 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1053 // Remove non-zero lower bounds
1055 for (int i = 0; i != _arc_num; ++i) {
1056 Value c = _lower[i];
1058 _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1060 _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1062 _supply[_source[i]] -= c;
1063 _supply[_target[i]] += c;
1066 for (int i = 0; i != _arc_num; ++i) {
1067 _cap[i] = _upper[i];
1071 // Initialize artifical cost
1073 if (std::numeric_limits<Cost>::is_exact) {
1074 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1076 ART_COST = std::numeric_limits<Cost>::min();
1077 for (int i = 0; i != _arc_num; ++i) {
1078 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1080 ART_COST = (ART_COST + 1) * _node_num;
1083 // Initialize arc maps
1084 for (int i = 0; i != _arc_num; ++i) {
1086 _state[i] = STATE_LOWER;
1089 // Set data for the artificial root node
1091 _parent[_root] = -1;
1094 _rev_thread[0] = _root;
1095 _succ_num[_root] = _node_num + 1;
1096 _last_succ[_root] = _root - 1;
1097 _supply[_root] = -_sum_supply;
1100 // Add artificial arcs and initialize the spanning tree data structure
1101 if (_sum_supply == 0) {
1102 // EQ supply constraints
1103 _search_arc_num = _arc_num;
1104 _all_arc_num = _arc_num + _node_num;
1105 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1109 _rev_thread[u + 1] = u;
1113 _state[e] = STATE_TREE;
1114 if (_supply[u] >= 0) {
1119 _flow[e] = _supply[u];
1122 _forward[u] = false;
1126 _flow[e] = -_supply[u];
1127 _cost[e] = ART_COST;
1131 else if (_sum_supply > 0) {
1132 // LEQ supply constraints
1133 _search_arc_num = _arc_num + _node_num;
1134 int f = _arc_num + _node_num;
1135 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1138 _rev_thread[u + 1] = u;
1141 if (_supply[u] >= 0) {
1148 _flow[e] = _supply[u];
1150 _state[e] = STATE_TREE;
1152 _forward[u] = false;
1158 _flow[f] = -_supply[u];
1159 _cost[f] = ART_COST;
1160 _state[f] = STATE_TREE;
1166 _state[e] = STATE_LOWER;
1173 // GEQ supply constraints
1174 _search_arc_num = _arc_num + _node_num;
1175 int f = _arc_num + _node_num;
1176 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1179 _rev_thread[u + 1] = u;
1182 if (_supply[u] <= 0) {
1183 _forward[u] = false;
1189 _flow[e] = -_supply[u];
1191 _state[e] = STATE_TREE;
1199 _flow[f] = _supply[u];
1200 _state[f] = STATE_TREE;
1201 _cost[f] = ART_COST;
1207 _state[e] = STATE_LOWER;
1217 // Find the join node
1218 void findJoinNode() {
1219 int u = _source[in_arc];
1220 int v = _target[in_arc];
1222 if (_succ_num[u] < _succ_num[v]) {
1231 // Find the leaving arc of the cycle and returns true if the
1232 // leaving arc is not the same as the entering arc
1233 bool findLeavingArc() {
1234 // Initialize first and second nodes according to the direction
1236 if (_state[in_arc] == STATE_LOWER) {
1237 first = _source[in_arc];
1238 second = _target[in_arc];
1240 first = _target[in_arc];
1241 second = _source[in_arc];
1243 delta = _cap[in_arc];
1248 // Search the cycle along the path form the first node to the root
1249 for (int u = first; u != join; u = _parent[u]) {
1252 _flow[e] : (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]);
1259 // Search the cycle along the path form the second node to the root
1260 for (int u = second; u != join; u = _parent[u]) {
1263 (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]) : _flow[e];
1281 // Change _flow and _state vectors
1282 void changeFlow(bool change) {
1283 // Augment along the cycle
1285 Value val = _state[in_arc] * delta;
1286 _flow[in_arc] += val;
1287 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1288 _flow[_pred[u]] += _forward[u] ? -val : val;
1290 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1291 _flow[_pred[u]] += _forward[u] ? val : -val;
1294 // Update the state of the entering and leaving arcs
1296 _state[in_arc] = STATE_TREE;
1297 _state[_pred[u_out]] =
1298 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1300 _state[in_arc] = -_state[in_arc];
1304 // Update the tree structure
1305 void updateTreeStructure() {
1307 int old_rev_thread = _rev_thread[u_out];
1308 int old_succ_num = _succ_num[u_out];
1309 int old_last_succ = _last_succ[u_out];
1310 v_out = _parent[u_out];
1312 u = _last_succ[u_in]; // the last successor of u_in
1313 right = _thread[u]; // the node after it
1315 // Handle the case when old_rev_thread equals to v_in
1316 // (it also means that join and v_out coincide)
1317 if (old_rev_thread == v_in) {
1318 last = _thread[_last_succ[u_out]];
1320 last = _thread[v_in];
1323 // Update _thread and _parent along the stem nodes (i.e. the nodes
1324 // between u_in and u_out, whose parent have to be changed)
1325 _thread[v_in] = stem = u_in;
1326 _dirty_revs.clear();
1327 _dirty_revs.push_back(v_in);
1329 while (stem != u_out) {
1330 // Insert the next stem node into the thread list
1331 new_stem = _parent[stem];
1332 _thread[u] = new_stem;
1333 _dirty_revs.push_back(u);
1335 // Remove the subtree of stem from the thread list
1336 w = _rev_thread[stem];
1338 _rev_thread[right] = w;
1340 // Change the parent node and shift stem nodes
1341 _parent[stem] = par_stem;
1345 // Update u and right
1346 u = _last_succ[stem] == _last_succ[par_stem] ?
1347 _rev_thread[par_stem] : _last_succ[stem];
1350 _parent[u_out] = par_stem;
1352 _rev_thread[last] = u;
1353 _last_succ[u_out] = u;
1355 // Remove the subtree of u_out from the thread list except for
1356 // the case when old_rev_thread equals to v_in
1357 // (it also means that join and v_out coincide)
1358 if (old_rev_thread != v_in) {
1359 _thread[old_rev_thread] = right;
1360 _rev_thread[right] = old_rev_thread;
1363 // Update _rev_thread using the new _thread values
1364 for (int i = 0; i != int(_dirty_revs.size()); ++i) {
1366 _rev_thread[_thread[u]] = u;
1369 // Update _pred, _forward, _last_succ and _succ_num for the
1370 // stem nodes from u_out to u_in
1371 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1375 _pred[u] = _pred[w];
1376 _forward[u] = !_forward[w];
1377 tmp_sc += _succ_num[u] - _succ_num[w];
1378 _succ_num[u] = tmp_sc;
1379 _last_succ[w] = tmp_ls;
1382 _pred[u_in] = in_arc;
1383 _forward[u_in] = (u_in == _source[in_arc]);
1384 _succ_num[u_in] = old_succ_num;
1386 // Set limits for updating _last_succ form v_in and v_out
1388 int up_limit_in = -1;
1389 int up_limit_out = -1;
1390 if (_last_succ[join] == v_in) {
1391 up_limit_out = join;
1396 // Update _last_succ from v_in towards the root
1397 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1399 _last_succ[u] = _last_succ[u_out];
1401 // Update _last_succ from v_out towards the root
1402 if (join != old_rev_thread && v_in != old_rev_thread) {
1403 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1405 _last_succ[u] = old_rev_thread;
1408 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1410 _last_succ[u] = _last_succ[u_out];
1414 // Update _succ_num from v_in to join
1415 for (u = v_in; u != join; u = _parent[u]) {
1416 _succ_num[u] += old_succ_num;
1418 // Update _succ_num from v_out to join
1419 for (u = v_out; u != join; u = _parent[u]) {
1420 _succ_num[u] -= old_succ_num;
1424 // Update potentials
1425 void updatePotential() {
1426 Cost sigma = _forward[u_in] ?
1427 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1428 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1429 // Update potentials in the subtree, which has been moved
1430 int end = _thread[_last_succ[u_in]];
1431 for (int u = u_in; u != end; u = _thread[u]) {
1436 // Heuristic initial pivots
1437 bool initialPivots() {
1438 Value curr, total = 0;
1439 std::vector<Node> supply_nodes, demand_nodes;
1440 for (NodeIt u(_graph); u != INVALID; ++u) {
1441 curr = _supply[_node_id[u]];
1444 supply_nodes.push_back(u);
1446 else if (curr < 0) {
1447 demand_nodes.push_back(u);
1450 if (_sum_supply > 0) total -= _sum_supply;
1451 if (total <= 0) return true;
1453 IntVector arc_vector;
1454 if (_sum_supply >= 0) {
1455 if (supply_nodes.size() == 1 && demand_nodes.size() == 1) {
1456 // Perform a reverse graph search from the sink to the source
1457 typename GR::template NodeMap<bool> reached(_graph, false);
1458 Node s = supply_nodes[0], t = demand_nodes[0];
1459 std::vector<Node> stack;
1462 while (!stack.empty()) {
1463 Node u, v = stack.back();
1466 for (InArcIt a(_graph, v); a != INVALID; ++a) {
1467 if (reached[u = _graph.source(a)]) continue;
1469 if (_cap[j] >= total) {
1470 arc_vector.push_back(j);
1477 // Find the min. cost incomming arc for each demand node
1478 for (int i = 0; i != int(demand_nodes.size()); ++i) {
1479 Node v = demand_nodes[i];
1480 Cost c, min_cost = std::numeric_limits<Cost>::max();
1481 Arc min_arc = INVALID;
1482 for (InArcIt a(_graph, v); a != INVALID; ++a) {
1483 c = _cost[_arc_id[a]];
1489 if (min_arc != INVALID) {
1490 arc_vector.push_back(_arc_id[min_arc]);
1495 // Find the min. cost outgoing arc for each supply node
1496 for (int i = 0; i != int(supply_nodes.size()); ++i) {
1497 Node u = supply_nodes[i];
1498 Cost c, min_cost = std::numeric_limits<Cost>::max();
1499 Arc min_arc = INVALID;
1500 for (OutArcIt a(_graph, u); a != INVALID; ++a) {
1501 c = _cost[_arc_id[a]];
1507 if (min_arc != INVALID) {
1508 arc_vector.push_back(_arc_id[min_arc]);
1513 // Perform heuristic initial pivots
1514 for (int i = 0; i != int(arc_vector.size()); ++i) {
1515 in_arc = arc_vector[i];
1516 if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -
1517 _pi[_target[in_arc]]) >= 0) continue;
1519 bool change = findLeavingArc();
1520 if (delta >= MAX) return false;
1523 updateTreeStructure();
1530 // Execute the algorithm
1531 ProblemType start(PivotRule pivot_rule) {
1532 // Select the pivot rule implementation
1533 switch (pivot_rule) {
1534 case FIRST_ELIGIBLE:
1535 return start<FirstEligiblePivotRule>();
1537 return start<BestEligiblePivotRule>();
1539 return start<BlockSearchPivotRule>();
1540 case CANDIDATE_LIST:
1541 return start<CandidateListPivotRule>();
1543 return start<AlteringListPivotRule>();
1545 return INFEASIBLE; // avoid warning
1548 template <typename PivotRuleImpl>
1549 ProblemType start() {
1550 PivotRuleImpl pivot(*this);
1552 // Perform heuristic initial pivots
1553 if (!initialPivots()) return UNBOUNDED;
1555 // Execute the Network Simplex algorithm
1556 while (pivot.findEnteringArc()) {
1558 bool change = findLeavingArc();
1559 if (delta >= MAX) return UNBOUNDED;
1562 updateTreeStructure();
1567 // Check feasibility
1568 for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1569 if (_flow[e] != 0) return INFEASIBLE;
1572 // Transform the solution and the supply map to the original form
1574 for (int i = 0; i != _arc_num; ++i) {
1575 Value c = _lower[i];
1578 _supply[_source[i]] += c;
1579 _supply[_target[i]] -= c;
1584 // Shift potentials to meet the requirements of the GEQ/LEQ type
1585 // optimality conditions
1586 if (_sum_supply == 0) {
1587 if (_stype == GEQ) {
1588 Cost max_pot = std::numeric_limits<Cost>::min();
1589 for (int i = 0; i != _node_num; ++i) {
1590 if (_pi[i] > max_pot) max_pot = _pi[i];
1593 for (int i = 0; i != _node_num; ++i)
1597 Cost min_pot = std::numeric_limits<Cost>::max();
1598 for (int i = 0; i != _node_num; ++i) {
1599 if (_pi[i] < min_pot) min_pot = _pi[i];
1602 for (int i = 0; i != _node_num; ++i)
1611 }; //class NetworkSimplex
1617 #endif //LEMON_NETWORK_SIMPLEX_H