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, %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<signed char> CharVector;
170 // Note: vector<signed char> is used instead of vector<ArcState> and
171 // vector<ArcDirection> for efficiency reasons
173 // State constants for arcs
180 // Direction constants for tree arcs
188 // Data related to the underlying digraph
195 // Parameters of the problem
200 // Data structures for storing the digraph
216 // Data for storing the spanning tree structure
220 IntVector _rev_thread;
222 IntVector _last_succ;
223 CharVector _pred_dir;
225 IntVector _dirty_revs;
228 // Temporary data used in the current pivot iteration
229 int in_arc, join, u_in, v_in, u_out, v_out;
236 /// \brief Constant for infinite upper bounds (capacities).
238 /// Constant for infinite upper bounds (capacities).
239 /// It is \c std::numeric_limits<Value>::infinity() if available,
240 /// \c std::numeric_limits<Value>::max() otherwise.
245 // Implementation of the First Eligible pivot rule
246 class FirstEligiblePivotRule
250 // References to the NetworkSimplex class
251 const IntVector &_source;
252 const IntVector &_target;
253 const CostVector &_cost;
254 const CharVector &_state;
255 const CostVector &_pi;
265 FirstEligiblePivotRule(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), _search_arc_num(ns._search_arc_num),
272 // Find next entering arc
273 bool findEnteringArc() {
275 for (int e = _next_arc; e != _search_arc_num; ++e) {
276 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
283 for (int e = 0; e != _next_arc; ++e) {
284 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
294 }; //class FirstEligiblePivotRule
297 // Implementation of the Best Eligible pivot rule
298 class BestEligiblePivotRule
302 // References to the NetworkSimplex class
303 const IntVector &_source;
304 const IntVector &_target;
305 const CostVector &_cost;
306 const CharVector &_state;
307 const CostVector &_pi;
314 BestEligiblePivotRule(NetworkSimplex &ns) :
315 _source(ns._source), _target(ns._target),
316 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
317 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
320 // Find next entering arc
321 bool findEnteringArc() {
323 for (int e = 0; e != _search_arc_num; ++e) {
324 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
333 }; //class BestEligiblePivotRule
336 // Implementation of the Block Search pivot rule
337 class BlockSearchPivotRule
341 // References to the NetworkSimplex class
342 const IntVector &_source;
343 const IntVector &_target;
344 const CostVector &_cost;
345 const CharVector &_state;
346 const CostVector &_pi;
357 BlockSearchPivotRule(NetworkSimplex &ns) :
358 _source(ns._source), _target(ns._target),
359 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
360 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
363 // The main parameters of the pivot rule
364 const double BLOCK_SIZE_FACTOR = 1.0;
365 const int MIN_BLOCK_SIZE = 10;
367 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
368 std::sqrt(double(_search_arc_num))),
372 // Find next entering arc
373 bool findEnteringArc() {
375 int cnt = _block_size;
377 for (e = _next_arc; e != _search_arc_num; ++e) {
378 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
384 if (min < 0) goto search_end;
388 for (e = 0; e != _next_arc; ++e) {
389 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
395 if (min < 0) goto search_end;
399 if (min >= 0) return false;
406 }; //class BlockSearchPivotRule
409 // Implementation of the Candidate List pivot rule
410 class CandidateListPivotRule
414 // References to the NetworkSimplex class
415 const IntVector &_source;
416 const IntVector &_target;
417 const CostVector &_cost;
418 const CharVector &_state;
419 const CostVector &_pi;
424 IntVector _candidates;
425 int _list_length, _minor_limit;
426 int _curr_length, _minor_count;
432 CandidateListPivotRule(NetworkSimplex &ns) :
433 _source(ns._source), _target(ns._target),
434 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
435 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
438 // The main parameters of the pivot rule
439 const double LIST_LENGTH_FACTOR = 0.25;
440 const int MIN_LIST_LENGTH = 10;
441 const double MINOR_LIMIT_FACTOR = 0.1;
442 const int MIN_MINOR_LIMIT = 3;
444 _list_length = std::max( int(LIST_LENGTH_FACTOR *
445 std::sqrt(double(_search_arc_num))),
447 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
449 _curr_length = _minor_count = 0;
450 _candidates.resize(_list_length);
453 /// Find next entering arc
454 bool findEnteringArc() {
457 if (_curr_length > 0 && _minor_count < _minor_limit) {
458 // Minor iteration: select the best eligible arc from the
459 // current candidate list
462 for (int i = 0; i < _curr_length; ++i) {
464 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
470 _candidates[i--] = _candidates[--_curr_length];
473 if (min < 0) return true;
476 // Major iteration: build a new candidate list
479 for (e = _next_arc; e != _search_arc_num; ++e) {
480 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
482 _candidates[_curr_length++] = e;
487 if (_curr_length == _list_length) goto search_end;
490 for (e = 0; e != _next_arc; ++e) {
491 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
493 _candidates[_curr_length++] = e;
498 if (_curr_length == _list_length) goto search_end;
501 if (_curr_length == 0) return false;
509 }; //class CandidateListPivotRule
512 // Implementation of the Altering Candidate List pivot rule
513 class AlteringListPivotRule
517 // References to the NetworkSimplex class
518 const IntVector &_source;
519 const IntVector &_target;
520 const CostVector &_cost;
521 const CharVector &_state;
522 const CostVector &_pi;
527 int _block_size, _head_length, _curr_length;
529 IntVector _candidates;
530 CostVector _cand_cost;
532 // Functor class to compare arcs during sort of the candidate list
536 const CostVector &_map;
538 SortFunc(const CostVector &map) : _map(map) {}
539 bool operator()(int left, int right) {
540 return _map[left] > _map[right];
549 AlteringListPivotRule(NetworkSimplex &ns) :
550 _source(ns._source), _target(ns._target),
551 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
552 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
553 _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
555 // The main parameters of the pivot rule
556 const double BLOCK_SIZE_FACTOR = 1.0;
557 const int MIN_BLOCK_SIZE = 10;
558 const double HEAD_LENGTH_FACTOR = 0.1;
559 const int MIN_HEAD_LENGTH = 3;
561 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
562 std::sqrt(double(_search_arc_num))),
564 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
566 _candidates.resize(_head_length + _block_size);
570 // Find next entering arc
571 bool findEnteringArc() {
572 // Check the current candidate list
575 for (int i = 0; i != _curr_length; ++i) {
577 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
581 _candidates[i--] = _candidates[--_curr_length];
586 int cnt = _block_size;
587 int limit = _head_length;
589 for (e = _next_arc; e != _search_arc_num; ++e) {
590 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
593 _candidates[_curr_length++] = e;
596 if (_curr_length > limit) goto search_end;
601 for (e = 0; e != _next_arc; ++e) {
602 _cand_cost[e] = _state[e] *
603 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
604 if (_cand_cost[e] < 0) {
605 _candidates[_curr_length++] = e;
608 if (_curr_length > limit) goto search_end;
613 if (_curr_length == 0) return false;
617 // Make heap of the candidate list (approximating a partial sort)
618 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
621 // Pop the first element of the heap
622 _in_arc = _candidates[0];
624 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
626 _curr_length = std::min(_head_length, _curr_length - 1);
630 }; //class AlteringListPivotRule
634 /// \brief Constructor.
636 /// The constructor of the class.
638 /// \param graph The digraph the algorithm runs on.
639 /// \param arc_mixing Indicate if the arcs will be stored in a
640 /// mixed order in the internal data structure.
641 /// In general, it leads to similar performance as using the original
642 /// arc order, but it makes the algorithm more robust and in special
643 /// cases, even significantly faster. Therefore, it is enabled by default.
644 NetworkSimplex(const GR& graph, bool arc_mixing = true) :
645 _graph(graph), _node_id(graph), _arc_id(graph),
646 _arc_mixing(arc_mixing),
647 MAX(std::numeric_limits<Value>::max()),
648 INF(std::numeric_limits<Value>::has_infinity ?
649 std::numeric_limits<Value>::infinity() : MAX)
651 // Check the number types
652 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
653 "The flow type of NetworkSimplex must be signed");
654 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
655 "The cost type of NetworkSimplex must be signed");
657 // Reset data structures
662 /// The parameters of the algorithm can be specified using these
667 /// \brief Set the lower bounds on the arcs.
669 /// This function sets the lower bounds on the arcs.
670 /// If it is not used before calling \ref run(), the lower bounds
671 /// will be set to zero on all arcs.
673 /// \param map An arc map storing the lower bounds.
674 /// Its \c Value type must be convertible to the \c Value type
675 /// of the algorithm.
677 /// \return <tt>(*this)</tt>
678 template <typename LowerMap>
679 NetworkSimplex& lowerMap(const LowerMap& map) {
681 for (ArcIt a(_graph); a != INVALID; ++a) {
682 _lower[_arc_id[a]] = map[a];
687 /// \brief Set the upper bounds (capacities) on the arcs.
689 /// This function sets the upper bounds (capacities) on the arcs.
690 /// If it is not used before calling \ref run(), the upper bounds
691 /// will be set to \ref INF on all arcs (i.e. the flow value will be
692 /// unbounded from above).
694 /// \param map An arc map storing the upper bounds.
695 /// Its \c Value type must be convertible to the \c Value type
696 /// of the algorithm.
698 /// \return <tt>(*this)</tt>
699 template<typename UpperMap>
700 NetworkSimplex& upperMap(const UpperMap& map) {
701 for (ArcIt a(_graph); a != INVALID; ++a) {
702 _upper[_arc_id[a]] = map[a];
707 /// \brief Set the costs of the arcs.
709 /// This function sets the costs of the arcs.
710 /// If it is not used before calling \ref run(), the costs
711 /// will be set to \c 1 on all arcs.
713 /// \param map An arc map storing the costs.
714 /// Its \c Value type must be convertible to the \c Cost type
715 /// of the algorithm.
717 /// \return <tt>(*this)</tt>
718 template<typename CostMap>
719 NetworkSimplex& costMap(const CostMap& map) {
720 for (ArcIt a(_graph); a != INVALID; ++a) {
721 _cost[_arc_id[a]] = map[a];
726 /// \brief Set the supply values of the nodes.
728 /// This function sets the supply values of the nodes.
729 /// If neither this function nor \ref stSupply() is used before
730 /// calling \ref run(), the supply of each node will be set to zero.
732 /// \param map A node map storing the supply values.
733 /// Its \c Value type must be convertible to the \c Value type
734 /// of the algorithm.
736 /// \return <tt>(*this)</tt>
737 template<typename SupplyMap>
738 NetworkSimplex& supplyMap(const SupplyMap& map) {
739 for (NodeIt n(_graph); n != INVALID; ++n) {
740 _supply[_node_id[n]] = map[n];
745 /// \brief Set single source and target nodes and a supply value.
747 /// This function sets a single source node and a single target node
748 /// and the required flow value.
749 /// If neither this function nor \ref supplyMap() is used before
750 /// calling \ref run(), the supply of each node will be set to zero.
752 /// Using this function has the same effect as using \ref supplyMap()
753 /// with such a map in which \c k is assigned to \c s, \c -k is
754 /// assigned to \c t and all other nodes have zero supply value.
756 /// \param s The source node.
757 /// \param t The target node.
758 /// \param k The required amount of flow from node \c s to node \c t
759 /// (i.e. the supply of \c s and the demand of \c t).
761 /// \return <tt>(*this)</tt>
762 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
763 for (int i = 0; i != _node_num; ++i) {
766 _supply[_node_id[s]] = k;
767 _supply[_node_id[t]] = -k;
771 /// \brief Set the type of the supply constraints.
773 /// This function sets the type of the supply/demand constraints.
774 /// If it is not used before calling \ref run(), the \ref GEQ supply
775 /// type will be used.
777 /// For more information, see \ref SupplyType.
779 /// \return <tt>(*this)</tt>
780 NetworkSimplex& supplyType(SupplyType supply_type) {
781 _stype = supply_type;
787 /// \name Execution Control
788 /// The algorithm can be executed using \ref run().
792 /// \brief Run the algorithm.
794 /// This function runs the algorithm.
795 /// The paramters can be specified using functions \ref lowerMap(),
796 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
797 /// \ref supplyType().
800 /// NetworkSimplex<ListDigraph> ns(graph);
801 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
802 /// .supplyMap(sup).run();
805 /// This function can be called more than once. All the given parameters
806 /// are kept for the next call, unless \ref resetParams() or \ref reset()
807 /// is used, thus only the modified parameters have to be set again.
808 /// If the underlying digraph was also modified after the construction
809 /// of the class (or the last \ref reset() call), then the \ref reset()
810 /// function must be called.
812 /// \param pivot_rule The pivot rule that will be used during the
813 /// algorithm. For more information, see \ref PivotRule.
815 /// \return \c INFEASIBLE if no feasible flow exists,
816 /// \n \c OPTIMAL if the problem has optimal solution
817 /// (i.e. it is feasible and bounded), and the algorithm has found
818 /// optimal flow and node potentials (primal and dual solutions),
819 /// \n \c UNBOUNDED if the objective function of the problem is
820 /// unbounded, i.e. there is a directed cycle having negative total
821 /// cost and infinite upper bound.
823 /// \see ProblemType, PivotRule
824 /// \see resetParams(), reset()
825 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
826 if (!init()) return INFEASIBLE;
827 return start(pivot_rule);
830 /// \brief Reset all the parameters that have been given before.
832 /// This function resets all the paramaters that have been given
833 /// before using functions \ref lowerMap(), \ref upperMap(),
834 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
836 /// It is useful for multiple \ref run() calls. Basically, all the given
837 /// parameters are kept for the next \ref run() call, unless
838 /// \ref resetParams() or \ref reset() is used.
839 /// If the underlying digraph was also modified after the construction
840 /// of the class or the last \ref reset() call, then the \ref reset()
841 /// function must be used, otherwise \ref resetParams() is sufficient.
845 /// NetworkSimplex<ListDigraph> ns(graph);
848 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
849 /// .supplyMap(sup).run();
851 /// // Run again with modified cost map (resetParams() is not called,
852 /// // so only the cost map have to be set again)
854 /// ns.costMap(cost).run();
856 /// // Run again from scratch using resetParams()
857 /// // (the lower bounds will be set to zero on all arcs)
858 /// ns.resetParams();
859 /// ns.upperMap(capacity).costMap(cost)
860 /// .supplyMap(sup).run();
863 /// \return <tt>(*this)</tt>
865 /// \see reset(), run()
866 NetworkSimplex& resetParams() {
867 for (int i = 0; i != _node_num; ++i) {
870 for (int i = 0; i != _arc_num; ++i) {
880 /// \brief Reset the internal data structures and all the parameters
881 /// that have been given before.
883 /// This function resets the internal data structures and all the
884 /// paramaters that have been given before using functions \ref lowerMap(),
885 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
886 /// \ref supplyType().
888 /// It is useful for multiple \ref run() calls. Basically, all the given
889 /// parameters are kept for the next \ref run() call, unless
890 /// \ref resetParams() or \ref reset() is used.
891 /// If the underlying digraph was also modified after the construction
892 /// of the class or the last \ref reset() call, then the \ref reset()
893 /// function must be used, otherwise \ref resetParams() is sufficient.
895 /// See \ref resetParams() for examples.
897 /// \return <tt>(*this)</tt>
899 /// \see resetParams(), run()
900 NetworkSimplex& reset() {
902 _node_num = countNodes(_graph);
903 _arc_num = countArcs(_graph);
904 int all_node_num = _node_num + 1;
905 int max_arc_num = _arc_num + 2 * _node_num;
907 _source.resize(max_arc_num);
908 _target.resize(max_arc_num);
910 _lower.resize(_arc_num);
911 _upper.resize(_arc_num);
912 _cap.resize(max_arc_num);
913 _cost.resize(max_arc_num);
914 _supply.resize(all_node_num);
915 _flow.resize(max_arc_num);
916 _pi.resize(all_node_num);
918 _parent.resize(all_node_num);
919 _pred.resize(all_node_num);
920 _pred_dir.resize(all_node_num);
921 _thread.resize(all_node_num);
922 _rev_thread.resize(all_node_num);
923 _succ_num.resize(all_node_num);
924 _last_succ.resize(all_node_num);
925 _state.resize(max_arc_num);
929 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
933 // Store the arcs in a mixed order
934 const int skip = std::max(_arc_num / _node_num, 3);
936 for (ArcIt a(_graph); a != INVALID; ++a) {
938 _source[i] = _node_id[_graph.source(a)];
939 _target[i] = _node_id[_graph.target(a)];
940 if ((i += skip) >= _arc_num) i = ++j;
943 // Store the arcs in the original order
945 for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
947 _source[i] = _node_id[_graph.source(a)];
948 _target[i] = _node_id[_graph.target(a)];
959 /// \name Query Functions
960 /// The results of the algorithm can be obtained using these
962 /// The \ref run() function must be called before using them.
966 /// \brief Return the total cost of the found flow.
968 /// This function returns the total cost of the found flow.
969 /// Its complexity is O(e).
971 /// \note The return type of the function can be specified as a
972 /// template parameter. For example,
974 /// ns.totalCost<double>();
976 /// It is useful if the total cost cannot be stored in the \c Cost
977 /// type of the algorithm, which is the default return type of the
980 /// \pre \ref run() must be called before using this function.
981 template <typename Number>
982 Number totalCost() const {
984 for (ArcIt a(_graph); a != INVALID; ++a) {
986 c += Number(_flow[i]) * Number(_cost[i]);
992 Cost totalCost() const {
993 return totalCost<Cost>();
997 /// \brief Return the flow on the given arc.
999 /// This function returns the flow on the given arc.
1001 /// \pre \ref run() must be called before using this function.
1002 Value flow(const Arc& a) const {
1003 return _flow[_arc_id[a]];
1006 /// \brief Return the flow map (the primal solution).
1008 /// This function copies the flow value on each arc into the given
1009 /// map. The \c Value type of the algorithm must be convertible to
1010 /// the \c Value type of the map.
1012 /// \pre \ref run() must be called before using this function.
1013 template <typename FlowMap>
1014 void flowMap(FlowMap &map) const {
1015 for (ArcIt a(_graph); a != INVALID; ++a) {
1016 map.set(a, _flow[_arc_id[a]]);
1020 /// \brief Return the potential (dual value) of the given node.
1022 /// This function returns the potential (dual value) of the
1025 /// \pre \ref run() must be called before using this function.
1026 Cost potential(const Node& n) const {
1027 return _pi[_node_id[n]];
1030 /// \brief Return the potential map (the dual solution).
1032 /// This function copies the potential (dual value) of each node
1033 /// into the given map.
1034 /// The \c Cost type of the algorithm must be convertible to the
1035 /// \c Value type of the map.
1037 /// \pre \ref run() must be called before using this function.
1038 template <typename PotentialMap>
1039 void potentialMap(PotentialMap &map) const {
1040 for (NodeIt n(_graph); n != INVALID; ++n) {
1041 map.set(n, _pi[_node_id[n]]);
1049 // Initialize internal data structures
1051 if (_node_num == 0) return false;
1053 // Check the sum of supply values
1055 for (int i = 0; i != _node_num; ++i) {
1056 _sum_supply += _supply[i];
1058 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1059 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1061 // Remove non-zero lower bounds
1063 for (int i = 0; i != _arc_num; ++i) {
1064 Value c = _lower[i];
1066 _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1068 _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1070 _supply[_source[i]] -= c;
1071 _supply[_target[i]] += c;
1074 for (int i = 0; i != _arc_num; ++i) {
1075 _cap[i] = _upper[i];
1079 // Initialize artifical cost
1081 if (std::numeric_limits<Cost>::is_exact) {
1082 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1085 for (int i = 0; i != _arc_num; ++i) {
1086 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1088 ART_COST = (ART_COST + 1) * _node_num;
1091 // Initialize arc maps
1092 for (int i = 0; i != _arc_num; ++i) {
1094 _state[i] = STATE_LOWER;
1097 // Set data for the artificial root node
1099 _parent[_root] = -1;
1102 _rev_thread[0] = _root;
1103 _succ_num[_root] = _node_num + 1;
1104 _last_succ[_root] = _root - 1;
1105 _supply[_root] = -_sum_supply;
1108 // Add artificial arcs and initialize the spanning tree data structure
1109 if (_sum_supply == 0) {
1110 // EQ supply constraints
1111 _search_arc_num = _arc_num;
1112 _all_arc_num = _arc_num + _node_num;
1113 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1117 _rev_thread[u + 1] = u;
1121 _state[e] = STATE_TREE;
1122 if (_supply[u] >= 0) {
1123 _pred_dir[u] = DIR_UP;
1127 _flow[e] = _supply[u];
1130 _pred_dir[u] = DIR_DOWN;
1134 _flow[e] = -_supply[u];
1135 _cost[e] = ART_COST;
1139 else if (_sum_supply > 0) {
1140 // LEQ supply constraints
1141 _search_arc_num = _arc_num + _node_num;
1142 int f = _arc_num + _node_num;
1143 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1146 _rev_thread[u + 1] = u;
1149 if (_supply[u] >= 0) {
1150 _pred_dir[u] = DIR_UP;
1156 _flow[e] = _supply[u];
1158 _state[e] = STATE_TREE;
1160 _pred_dir[u] = DIR_DOWN;
1166 _flow[f] = -_supply[u];
1167 _cost[f] = ART_COST;
1168 _state[f] = STATE_TREE;
1174 _state[e] = STATE_LOWER;
1181 // GEQ supply constraints
1182 _search_arc_num = _arc_num + _node_num;
1183 int f = _arc_num + _node_num;
1184 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1187 _rev_thread[u + 1] = u;
1190 if (_supply[u] <= 0) {
1191 _pred_dir[u] = DIR_DOWN;
1197 _flow[e] = -_supply[u];
1199 _state[e] = STATE_TREE;
1201 _pred_dir[u] = DIR_UP;
1207 _flow[f] = _supply[u];
1208 _state[f] = STATE_TREE;
1209 _cost[f] = ART_COST;
1215 _state[e] = STATE_LOWER;
1225 // Find the join node
1226 void findJoinNode() {
1227 int u = _source[in_arc];
1228 int v = _target[in_arc];
1230 if (_succ_num[u] < _succ_num[v]) {
1239 // Find the leaving arc of the cycle and returns true if the
1240 // leaving arc is not the same as the entering arc
1241 bool findLeavingArc() {
1242 // Initialize first and second nodes according to the direction
1245 if (_state[in_arc] == STATE_LOWER) {
1246 first = _source[in_arc];
1247 second = _target[in_arc];
1249 first = _target[in_arc];
1250 second = _source[in_arc];
1252 delta = _cap[in_arc];
1257 // Search the cycle form the first node to the join node
1258 for (int u = first; u != join; u = _parent[u]) {
1261 if (_pred_dir[u] == DIR_DOWN) {
1263 d = c >= MAX ? INF : c - d;
1272 // Search the cycle form the second node to the join node
1273 for (int u = second; u != join; u = _parent[u]) {
1276 if (_pred_dir[u] == DIR_UP) {
1278 d = c >= MAX ? INF : c - d;
1297 // Change _flow and _state vectors
1298 void changeFlow(bool change) {
1299 // Augment along the cycle
1301 Value val = _state[in_arc] * delta;
1302 _flow[in_arc] += val;
1303 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1304 _flow[_pred[u]] -= _pred_dir[u] * val;
1306 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1307 _flow[_pred[u]] += _pred_dir[u] * val;
1310 // Update the state of the entering and leaving arcs
1312 _state[in_arc] = STATE_TREE;
1313 _state[_pred[u_out]] =
1314 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1316 _state[in_arc] = -_state[in_arc];
1320 // Update the tree structure
1321 void updateTreeStructure() {
1322 int old_rev_thread = _rev_thread[u_out];
1323 int old_succ_num = _succ_num[u_out];
1324 int old_last_succ = _last_succ[u_out];
1325 v_out = _parent[u_out];
1327 // Check if u_in and u_out coincide
1328 if (u_in == u_out) {
1329 // Update _parent, _pred, _pred_dir
1330 _parent[u_in] = v_in;
1331 _pred[u_in] = in_arc;
1332 _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1334 // Update _thread and _rev_thread
1335 if (_thread[v_in] != u_out) {
1336 int after = _thread[old_last_succ];
1337 _thread[old_rev_thread] = after;
1338 _rev_thread[after] = old_rev_thread;
1339 after = _thread[v_in];
1340 _thread[v_in] = u_out;
1341 _rev_thread[u_out] = v_in;
1342 _thread[old_last_succ] = after;
1343 _rev_thread[after] = old_last_succ;
1346 // Handle the case when old_rev_thread equals to v_in
1347 // (it also means that join and v_out coincide)
1348 int thread_continue = old_rev_thread == v_in ?
1349 _thread[old_last_succ] : _thread[v_in];
1351 // Update _thread and _parent along the stem nodes (i.e. the nodes
1352 // between u_in and u_out, whose parent have to be changed)
1353 int stem = u_in; // the current stem node
1354 int par_stem = v_in; // the new parent of stem
1355 int next_stem; // the next stem node
1356 int last = _last_succ[u_in]; // the last successor of stem
1357 int before, after = _thread[last];
1358 _thread[v_in] = u_in;
1359 _dirty_revs.clear();
1360 _dirty_revs.push_back(v_in);
1361 while (stem != u_out) {
1362 // Insert the next stem node into the thread list
1363 next_stem = _parent[stem];
1364 _thread[last] = next_stem;
1365 _dirty_revs.push_back(last);
1367 // Remove the subtree of stem from the thread list
1368 before = _rev_thread[stem];
1369 _thread[before] = after;
1370 _rev_thread[after] = before;
1372 // Change the parent node and shift stem nodes
1373 _parent[stem] = par_stem;
1377 // Update last and after
1378 last = _last_succ[stem] == _last_succ[par_stem] ?
1379 _rev_thread[par_stem] : _last_succ[stem];
1380 after = _thread[last];
1382 _parent[u_out] = par_stem;
1383 _thread[last] = thread_continue;
1384 _rev_thread[thread_continue] = last;
1385 _last_succ[u_out] = last;
1387 // Remove the subtree of u_out from the thread list except for
1388 // the case when old_rev_thread equals to v_in
1389 if (old_rev_thread != v_in) {
1390 _thread[old_rev_thread] = after;
1391 _rev_thread[after] = old_rev_thread;
1394 // Update _rev_thread using the new _thread values
1395 for (int i = 0; i != int(_dirty_revs.size()); ++i) {
1396 int u = _dirty_revs[i];
1397 _rev_thread[_thread[u]] = u;
1400 // Update _pred, _pred_dir, _last_succ and _succ_num for the
1401 // stem nodes from u_out to u_in
1402 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1403 for (int u = u_out, p = _parent[u]; u != u_in; u = p, p = _parent[u]) {
1404 _pred[u] = _pred[p];
1405 _pred_dir[u] = -_pred_dir[p];
1406 tmp_sc += _succ_num[u] - _succ_num[p];
1407 _succ_num[u] = tmp_sc;
1408 _last_succ[p] = tmp_ls;
1410 _pred[u_in] = in_arc;
1411 _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1412 _succ_num[u_in] = old_succ_num;
1415 // Update _last_succ from v_in towards the root
1416 int up_limit_out = _last_succ[join] == v_in ? join : -1;
1417 int last_succ_out = _last_succ[u_out];
1418 for (int u = v_in; u != -1 && _last_succ[u] == v_in; u = _parent[u]) {
1419 _last_succ[u] = last_succ_out;
1422 // Update _last_succ from v_out towards the root
1423 if (join != old_rev_thread && v_in != old_rev_thread) {
1424 for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1426 _last_succ[u] = old_rev_thread;
1429 else if (last_succ_out != old_last_succ) {
1430 for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1432 _last_succ[u] = last_succ_out;
1436 // Update _succ_num from v_in to join
1437 for (int u = v_in; u != join; u = _parent[u]) {
1438 _succ_num[u] += old_succ_num;
1440 // Update _succ_num from v_out to join
1441 for (int u = v_out; u != join; u = _parent[u]) {
1442 _succ_num[u] -= old_succ_num;
1446 // Update potentials in the subtree that has been moved
1447 void updatePotential() {
1448 Cost sigma = _pi[v_in] - _pi[u_in] -
1449 _pred_dir[u_in] * _cost[in_arc];
1450 int end = _thread[_last_succ[u_in]];
1451 for (int u = u_in; u != end; u = _thread[u]) {
1456 // Heuristic initial pivots
1457 bool initialPivots() {
1458 Value curr, total = 0;
1459 std::vector<Node> supply_nodes, demand_nodes;
1460 for (NodeIt u(_graph); u != INVALID; ++u) {
1461 curr = _supply[_node_id[u]];
1464 supply_nodes.push_back(u);
1466 else if (curr < 0) {
1467 demand_nodes.push_back(u);
1470 if (_sum_supply > 0) total -= _sum_supply;
1471 if (total <= 0) return true;
1473 IntVector arc_vector;
1474 if (_sum_supply >= 0) {
1475 if (supply_nodes.size() == 1 && demand_nodes.size() == 1) {
1476 // Perform a reverse graph search from the sink to the source
1477 typename GR::template NodeMap<bool> reached(_graph, false);
1478 Node s = supply_nodes[0], t = demand_nodes[0];
1479 std::vector<Node> stack;
1482 while (!stack.empty()) {
1483 Node u, v = stack.back();
1486 for (InArcIt a(_graph, v); a != INVALID; ++a) {
1487 if (reached[u = _graph.source(a)]) continue;
1489 if (_cap[j] >= total) {
1490 arc_vector.push_back(j);
1497 // Find the min. cost incomming arc for each demand node
1498 for (int i = 0; i != int(demand_nodes.size()); ++i) {
1499 Node v = demand_nodes[i];
1500 Cost c, min_cost = std::numeric_limits<Cost>::max();
1501 Arc min_arc = INVALID;
1502 for (InArcIt a(_graph, v); a != INVALID; ++a) {
1503 c = _cost[_arc_id[a]];
1509 if (min_arc != INVALID) {
1510 arc_vector.push_back(_arc_id[min_arc]);
1515 // Find the min. cost outgoing arc for each supply node
1516 for (int i = 0; i != int(supply_nodes.size()); ++i) {
1517 Node u = supply_nodes[i];
1518 Cost c, min_cost = std::numeric_limits<Cost>::max();
1519 Arc min_arc = INVALID;
1520 for (OutArcIt a(_graph, u); a != INVALID; ++a) {
1521 c = _cost[_arc_id[a]];
1527 if (min_arc != INVALID) {
1528 arc_vector.push_back(_arc_id[min_arc]);
1533 // Perform heuristic initial pivots
1534 for (int i = 0; i != int(arc_vector.size()); ++i) {
1535 in_arc = arc_vector[i];
1536 if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -
1537 _pi[_target[in_arc]]) >= 0) continue;
1539 bool change = findLeavingArc();
1540 if (delta >= MAX) return false;
1543 updateTreeStructure();
1550 // Execute the algorithm
1551 ProblemType start(PivotRule pivot_rule) {
1552 // Select the pivot rule implementation
1553 switch (pivot_rule) {
1554 case FIRST_ELIGIBLE:
1555 return start<FirstEligiblePivotRule>();
1557 return start<BestEligiblePivotRule>();
1559 return start<BlockSearchPivotRule>();
1560 case CANDIDATE_LIST:
1561 return start<CandidateListPivotRule>();
1563 return start<AlteringListPivotRule>();
1565 return INFEASIBLE; // avoid warning
1568 template <typename PivotRuleImpl>
1569 ProblemType start() {
1570 PivotRuleImpl pivot(*this);
1572 // Perform heuristic initial pivots
1573 if (!initialPivots()) return UNBOUNDED;
1575 // Execute the Network Simplex algorithm
1576 while (pivot.findEnteringArc()) {
1578 bool change = findLeavingArc();
1579 if (delta >= MAX) return UNBOUNDED;
1582 updateTreeStructure();
1587 // Check feasibility
1588 for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1589 if (_flow[e] != 0) return INFEASIBLE;
1592 // Transform the solution and the supply map to the original form
1594 for (int i = 0; i != _arc_num; ++i) {
1595 Value c = _lower[i];
1598 _supply[_source[i]] += c;
1599 _supply[_target[i]] -= c;
1604 // Shift potentials to meet the requirements of the GEQ/LEQ type
1605 // optimality conditions
1606 if (_sum_supply == 0) {
1607 if (_stype == GEQ) {
1608 Cost max_pot = -std::numeric_limits<Cost>::max();
1609 for (int i = 0; i != _node_num; ++i) {
1610 if (_pi[i] > max_pot) max_pot = _pi[i];
1613 for (int i = 0; i != _node_num; ++i)
1617 Cost min_pot = std::numeric_limits<Cost>::max();
1618 for (int i = 0; i != _node_num; ++i) {
1619 if (_pi[i] < min_pot) min_pot = _pi[i];
1622 for (int i = 0; i != _node_num; ++i)
1631 }; //class NetworkSimplex
1637 #endif //LEMON_NETWORK_SIMPLEX_H