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<char> CharVector;
168 typedef std::vector<Value> ValueVector;
169 typedef std::vector<Cost> CostVector;
171 // State constants for arcs
180 // Data related to the underlying digraph
187 // Parameters of the problem
192 // Data structures for storing the digraph
207 // Data for storing the spanning tree structure
211 IntVector _rev_thread;
213 IntVector _last_succ;
214 IntVector _dirty_revs;
219 // Temporary data used in the current pivot iteration
220 int in_arc, join, u_in, v_in, u_out, v_out;
221 int first, second, right, last;
222 int stem, par_stem, new_stem;
229 /// \brief Constant for infinite upper bounds (capacities).
231 /// Constant for infinite upper bounds (capacities).
232 /// It is \c std::numeric_limits<Value>::infinity() if available,
233 /// \c std::numeric_limits<Value>::max() otherwise.
238 // Implementation of the First Eligible pivot rule
239 class FirstEligiblePivotRule
243 // References to the NetworkSimplex class
244 const IntVector &_source;
245 const IntVector &_target;
246 const CostVector &_cost;
247 const CharVector &_state;
248 const CostVector &_pi;
258 FirstEligiblePivotRule(NetworkSimplex &ns) :
259 _source(ns._source), _target(ns._target),
260 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
261 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
265 // Find next entering arc
266 bool findEnteringArc() {
268 for (int e = _next_arc; e < _search_arc_num; ++e) {
269 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
276 for (int e = 0; e < _next_arc; ++e) {
277 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
287 }; //class FirstEligiblePivotRule
290 // Implementation of the Best Eligible pivot rule
291 class BestEligiblePivotRule
295 // References to the NetworkSimplex class
296 const IntVector &_source;
297 const IntVector &_target;
298 const CostVector &_cost;
299 const CharVector &_state;
300 const CostVector &_pi;
307 BestEligiblePivotRule(NetworkSimplex &ns) :
308 _source(ns._source), _target(ns._target),
309 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
310 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
313 // Find next entering arc
314 bool findEnteringArc() {
316 for (int e = 0; e < _search_arc_num; ++e) {
317 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
326 }; //class BestEligiblePivotRule
329 // Implementation of the Block Search pivot rule
330 class BlockSearchPivotRule
334 // References to the NetworkSimplex class
335 const IntVector &_source;
336 const IntVector &_target;
337 const CostVector &_cost;
338 const CharVector &_state;
339 const CostVector &_pi;
350 BlockSearchPivotRule(NetworkSimplex &ns) :
351 _source(ns._source), _target(ns._target),
352 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
353 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
356 // The main parameters of the pivot rule
357 const double BLOCK_SIZE_FACTOR = 0.5;
358 const int MIN_BLOCK_SIZE = 10;
360 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
361 std::sqrt(double(_search_arc_num))),
365 // Find next entering arc
366 bool findEnteringArc() {
368 int cnt = _block_size;
370 for (e = _next_arc; e < _search_arc_num; ++e) {
371 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
377 if (min < 0) goto search_end;
381 for (e = 0; e < _next_arc; ++e) {
382 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
388 if (min < 0) goto search_end;
392 if (min >= 0) return false;
399 }; //class BlockSearchPivotRule
402 // Implementation of the Candidate List pivot rule
403 class CandidateListPivotRule
407 // References to the NetworkSimplex class
408 const IntVector &_source;
409 const IntVector &_target;
410 const CostVector &_cost;
411 const CharVector &_state;
412 const CostVector &_pi;
417 IntVector _candidates;
418 int _list_length, _minor_limit;
419 int _curr_length, _minor_count;
425 CandidateListPivotRule(NetworkSimplex &ns) :
426 _source(ns._source), _target(ns._target),
427 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
428 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
431 // The main parameters of the pivot rule
432 const double LIST_LENGTH_FACTOR = 0.25;
433 const int MIN_LIST_LENGTH = 10;
434 const double MINOR_LIMIT_FACTOR = 0.1;
435 const int MIN_MINOR_LIMIT = 3;
437 _list_length = std::max( int(LIST_LENGTH_FACTOR *
438 std::sqrt(double(_search_arc_num))),
440 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
442 _curr_length = _minor_count = 0;
443 _candidates.resize(_list_length);
446 /// Find next entering arc
447 bool findEnteringArc() {
450 if (_curr_length > 0 && _minor_count < _minor_limit) {
451 // Minor iteration: select the best eligible arc from the
452 // current candidate list
455 for (int i = 0; i < _curr_length; ++i) {
457 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
463 _candidates[i--] = _candidates[--_curr_length];
466 if (min < 0) return true;
469 // Major iteration: build a new candidate list
472 for (e = _next_arc; e < _search_arc_num; ++e) {
473 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
475 _candidates[_curr_length++] = e;
480 if (_curr_length == _list_length) goto search_end;
483 for (e = 0; e < _next_arc; ++e) {
484 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
486 _candidates[_curr_length++] = e;
491 if (_curr_length == _list_length) goto search_end;
494 if (_curr_length == 0) return false;
502 }; //class CandidateListPivotRule
505 // Implementation of the Altering Candidate List pivot rule
506 class AlteringListPivotRule
510 // References to the NetworkSimplex class
511 const IntVector &_source;
512 const IntVector &_target;
513 const CostVector &_cost;
514 const CharVector &_state;
515 const CostVector &_pi;
520 int _block_size, _head_length, _curr_length;
522 IntVector _candidates;
523 CostVector _cand_cost;
525 // Functor class to compare arcs during sort of the candidate list
529 const CostVector &_map;
531 SortFunc(const CostVector &map) : _map(map) {}
532 bool operator()(int left, int right) {
533 return _map[left] > _map[right];
542 AlteringListPivotRule(NetworkSimplex &ns) :
543 _source(ns._source), _target(ns._target),
544 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
545 _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
546 _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
548 // The main parameters of the pivot rule
549 const double BLOCK_SIZE_FACTOR = 1.0;
550 const int MIN_BLOCK_SIZE = 10;
551 const double HEAD_LENGTH_FACTOR = 0.1;
552 const int MIN_HEAD_LENGTH = 3;
554 _block_size = std::max( int(BLOCK_SIZE_FACTOR *
555 std::sqrt(double(_search_arc_num))),
557 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
559 _candidates.resize(_head_length + _block_size);
563 // Find next entering arc
564 bool findEnteringArc() {
565 // Check the current candidate list
567 for (int i = 0; i < _curr_length; ++i) {
569 _cand_cost[e] = _state[e] *
570 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
571 if (_cand_cost[e] >= 0) {
572 _candidates[i--] = _candidates[--_curr_length];
577 int cnt = _block_size;
578 int limit = _head_length;
580 for (e = _next_arc; e < _search_arc_num; ++e) {
581 _cand_cost[e] = _state[e] *
582 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
583 if (_cand_cost[e] < 0) {
584 _candidates[_curr_length++] = e;
587 if (_curr_length > limit) goto search_end;
592 for (e = 0; e < _next_arc; ++e) {
593 _cand_cost[e] = _state[e] *
594 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
595 if (_cand_cost[e] < 0) {
596 _candidates[_curr_length++] = e;
599 if (_curr_length > limit) goto search_end;
604 if (_curr_length == 0) return false;
608 // Make heap of the candidate list (approximating a partial sort)
609 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
612 // Pop the first element of the heap
613 _in_arc = _candidates[0];
615 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
617 _curr_length = std::min(_head_length, _curr_length - 1);
621 }; //class AlteringListPivotRule
625 /// \brief Constructor.
627 /// The constructor of the class.
629 /// \param graph The digraph the algorithm runs on.
630 /// \param arc_mixing Indicate if the arcs have to be stored in a
631 /// mixed order in the internal data structure.
632 /// In special cases, it could lead to better overall performance,
633 /// but it is usually slower. Therefore it is disabled by default.
634 NetworkSimplex(const GR& graph, bool arc_mixing = false) :
635 _graph(graph), _node_id(graph), _arc_id(graph),
636 MAX(std::numeric_limits<Value>::max()),
637 INF(std::numeric_limits<Value>::has_infinity ?
638 std::numeric_limits<Value>::infinity() : MAX)
640 // Check the number types
641 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
642 "The flow type of NetworkSimplex must be signed");
643 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
644 "The cost type of NetworkSimplex must be signed");
647 _node_num = countNodes(_graph);
648 _arc_num = countArcs(_graph);
649 int all_node_num = _node_num + 1;
650 int max_arc_num = _arc_num + 2 * _node_num;
652 _source.resize(max_arc_num);
653 _target.resize(max_arc_num);
655 _lower.resize(_arc_num);
656 _upper.resize(_arc_num);
657 _cap.resize(max_arc_num);
658 _cost.resize(max_arc_num);
659 _supply.resize(all_node_num);
660 _flow.resize(max_arc_num);
661 _pi.resize(all_node_num);
663 _parent.resize(all_node_num);
664 _pred.resize(all_node_num);
665 _forward.resize(all_node_num);
666 _thread.resize(all_node_num);
667 _rev_thread.resize(all_node_num);
668 _succ_num.resize(all_node_num);
669 _last_succ.resize(all_node_num);
670 _state.resize(max_arc_num);
674 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
678 // Store the arcs in a mixed order
679 int k = std::max(int(std::sqrt(double(_arc_num))), 10);
681 for (ArcIt a(_graph); a != INVALID; ++a) {
683 _source[i] = _node_id[_graph.source(a)];
684 _target[i] = _node_id[_graph.target(a)];
685 if ((i += k) >= _arc_num) i = ++j;
688 // Store the arcs in the original order
690 for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
692 _source[i] = _node_id[_graph.source(a)];
693 _target[i] = _node_id[_graph.target(a)];
702 /// The parameters of the algorithm can be specified using these
707 /// \brief Set the lower bounds on the arcs.
709 /// This function sets the lower bounds on the arcs.
710 /// If it is not used before calling \ref run(), the lower bounds
711 /// will be set to zero on all arcs.
713 /// \param map An arc map storing the lower bounds.
714 /// Its \c Value type must be convertible to the \c Value type
715 /// of the algorithm.
717 /// \return <tt>(*this)</tt>
718 template <typename LowerMap>
719 NetworkSimplex& lowerMap(const LowerMap& map) {
721 for (ArcIt a(_graph); a != INVALID; ++a) {
722 _lower[_arc_id[a]] = map[a];
727 /// \brief Set the upper bounds (capacities) on the arcs.
729 /// This function sets the upper bounds (capacities) on the arcs.
730 /// If it is not used before calling \ref run(), the upper bounds
731 /// will be set to \ref INF on all arcs (i.e. the flow value will be
732 /// unbounded from above).
734 /// \param map An arc map storing the upper bounds.
735 /// Its \c Value type must be convertible to the \c Value type
736 /// of the algorithm.
738 /// \return <tt>(*this)</tt>
739 template<typename UpperMap>
740 NetworkSimplex& upperMap(const UpperMap& map) {
741 for (ArcIt a(_graph); a != INVALID; ++a) {
742 _upper[_arc_id[a]] = map[a];
747 /// \brief Set the costs of the arcs.
749 /// This function sets the costs of the arcs.
750 /// If it is not used before calling \ref run(), the costs
751 /// will be set to \c 1 on all arcs.
753 /// \param map An arc map storing the costs.
754 /// Its \c Value type must be convertible to the \c Cost type
755 /// of the algorithm.
757 /// \return <tt>(*this)</tt>
758 template<typename CostMap>
759 NetworkSimplex& costMap(const CostMap& map) {
760 for (ArcIt a(_graph); a != INVALID; ++a) {
761 _cost[_arc_id[a]] = map[a];
766 /// \brief Set the supply values of the nodes.
768 /// This function sets the supply values of the nodes.
769 /// If neither this function nor \ref stSupply() is used before
770 /// calling \ref run(), the supply of each node will be set to zero.
772 /// \param map A node map storing the supply values.
773 /// Its \c Value type must be convertible to the \c Value type
774 /// of the algorithm.
776 /// \return <tt>(*this)</tt>
777 template<typename SupplyMap>
778 NetworkSimplex& supplyMap(const SupplyMap& map) {
779 for (NodeIt n(_graph); n != INVALID; ++n) {
780 _supply[_node_id[n]] = map[n];
785 /// \brief Set single source and target nodes and a supply value.
787 /// This function sets a single source node and a single target node
788 /// and the required flow value.
789 /// If neither this function nor \ref supplyMap() is used before
790 /// calling \ref run(), the supply of each node will be set to zero.
792 /// Using this function has the same effect as using \ref supplyMap()
793 /// with such a map in which \c k is assigned to \c s, \c -k is
794 /// assigned to \c t and all other nodes have zero supply value.
796 /// \param s The source node.
797 /// \param t The target node.
798 /// \param k The required amount of flow from node \c s to node \c t
799 /// (i.e. the supply of \c s and the demand of \c t).
801 /// \return <tt>(*this)</tt>
802 NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
803 for (int i = 0; i != _node_num; ++i) {
806 _supply[_node_id[s]] = k;
807 _supply[_node_id[t]] = -k;
811 /// \brief Set the type of the supply constraints.
813 /// This function sets the type of the supply/demand constraints.
814 /// If it is not used before calling \ref run(), the \ref GEQ supply
815 /// type will be used.
817 /// For more information, see \ref SupplyType.
819 /// \return <tt>(*this)</tt>
820 NetworkSimplex& supplyType(SupplyType supply_type) {
821 _stype = supply_type;
827 /// \name Execution Control
828 /// The algorithm can be executed using \ref run().
832 /// \brief Run the algorithm.
834 /// This function runs the algorithm.
835 /// The paramters can be specified using functions \ref lowerMap(),
836 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
837 /// \ref supplyType().
840 /// NetworkSimplex<ListDigraph> ns(graph);
841 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
842 /// .supplyMap(sup).run();
845 /// This function can be called more than once. All the parameters
846 /// that have been given are kept for the next call, unless
847 /// \ref reset() is called, thus only the modified parameters
848 /// have to be set again. See \ref reset() for examples.
849 /// However, the underlying digraph must not be modified after this
850 /// class have been constructed, since it copies and extends the graph.
852 /// \param pivot_rule The pivot rule that will be used during the
853 /// algorithm. For more information, see \ref PivotRule.
855 /// \return \c INFEASIBLE if no feasible flow exists,
856 /// \n \c OPTIMAL if the problem has optimal solution
857 /// (i.e. it is feasible and bounded), and the algorithm has found
858 /// optimal flow and node potentials (primal and dual solutions),
859 /// \n \c UNBOUNDED if the objective function of the problem is
860 /// unbounded, i.e. there is a directed cycle having negative total
861 /// cost and infinite upper bound.
863 /// \see ProblemType, PivotRule
864 ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
865 if (!init()) return INFEASIBLE;
866 return start(pivot_rule);
869 /// \brief Reset all the parameters that have been given before.
871 /// This function resets all the paramaters that have been given
872 /// before using functions \ref lowerMap(), \ref upperMap(),
873 /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
875 /// It is useful for multiple run() calls. If this function is not
876 /// used, all the parameters given before are kept for the next
878 /// However, the underlying digraph must not be modified after this
879 /// class have been constructed, since it copies and extends the graph.
883 /// NetworkSimplex<ListDigraph> ns(graph);
886 /// ns.lowerMap(lower).upperMap(upper).costMap(cost)
887 /// .supplyMap(sup).run();
889 /// // Run again with modified cost map (reset() is not called,
890 /// // so only the cost map have to be set again)
892 /// ns.costMap(cost).run();
894 /// // Run again from scratch using reset()
895 /// // (the lower bounds will be set to zero on all arcs)
897 /// ns.upperMap(capacity).costMap(cost)
898 /// .supplyMap(sup).run();
901 /// \return <tt>(*this)</tt>
902 NetworkSimplex& reset() {
903 for (int i = 0; i != _node_num; ++i) {
906 for (int i = 0; i != _arc_num; ++i) {
918 /// \name Query Functions
919 /// The results of the algorithm can be obtained using these
921 /// The \ref run() function must be called before using them.
925 /// \brief Return the total cost of the found flow.
927 /// This function returns the total cost of the found flow.
928 /// Its complexity is O(e).
930 /// \note The return type of the function can be specified as a
931 /// template parameter. For example,
933 /// ns.totalCost<double>();
935 /// It is useful if the total cost cannot be stored in the \c Cost
936 /// type of the algorithm, which is the default return type of the
939 /// \pre \ref run() must be called before using this function.
940 template <typename Number>
941 Number totalCost() const {
943 for (ArcIt a(_graph); a != INVALID; ++a) {
945 c += Number(_flow[i]) * Number(_cost[i]);
951 Cost totalCost() const {
952 return totalCost<Cost>();
956 /// \brief Return the flow on the given arc.
958 /// This function returns the flow on the given arc.
960 /// \pre \ref run() must be called before using this function.
961 Value flow(const Arc& a) const {
962 return _flow[_arc_id[a]];
965 /// \brief Return the flow map (the primal solution).
967 /// This function copies the flow value on each arc into the given
968 /// map. The \c Value type of the algorithm must be convertible to
969 /// the \c Value type of the map.
971 /// \pre \ref run() must be called before using this function.
972 template <typename FlowMap>
973 void flowMap(FlowMap &map) const {
974 for (ArcIt a(_graph); a != INVALID; ++a) {
975 map.set(a, _flow[_arc_id[a]]);
979 /// \brief Return the potential (dual value) of the given node.
981 /// This function returns the potential (dual value) of the
984 /// \pre \ref run() must be called before using this function.
985 Cost potential(const Node& n) const {
986 return _pi[_node_id[n]];
989 /// \brief Return the potential map (the dual solution).
991 /// This function copies the potential (dual value) of each node
992 /// into the given map.
993 /// The \c Cost type of the algorithm must be convertible to the
994 /// \c Value type of the map.
996 /// \pre \ref run() must be called before using this function.
997 template <typename PotentialMap>
998 void potentialMap(PotentialMap &map) const {
999 for (NodeIt n(_graph); n != INVALID; ++n) {
1000 map.set(n, _pi[_node_id[n]]);
1008 // Initialize internal data structures
1010 if (_node_num == 0) return false;
1012 // Check the sum of supply values
1014 for (int i = 0; i != _node_num; ++i) {
1015 _sum_supply += _supply[i];
1017 if ( !((_stype == GEQ && _sum_supply <= 0) ||
1018 (_stype == LEQ && _sum_supply >= 0)) ) return false;
1020 // Remove non-zero lower bounds
1022 for (int i = 0; i != _arc_num; ++i) {
1023 Value c = _lower[i];
1025 _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1027 _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1029 _supply[_source[i]] -= c;
1030 _supply[_target[i]] += c;
1033 for (int i = 0; i != _arc_num; ++i) {
1034 _cap[i] = _upper[i];
1038 // Initialize artifical cost
1040 if (std::numeric_limits<Cost>::is_exact) {
1041 ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1043 ART_COST = std::numeric_limits<Cost>::min();
1044 for (int i = 0; i != _arc_num; ++i) {
1045 if (_cost[i] > ART_COST) ART_COST = _cost[i];
1047 ART_COST = (ART_COST + 1) * _node_num;
1050 // Initialize arc maps
1051 for (int i = 0; i != _arc_num; ++i) {
1053 _state[i] = STATE_LOWER;
1056 // Set data for the artificial root node
1058 _parent[_root] = -1;
1061 _rev_thread[0] = _root;
1062 _succ_num[_root] = _node_num + 1;
1063 _last_succ[_root] = _root - 1;
1064 _supply[_root] = -_sum_supply;
1067 // Add artificial arcs and initialize the spanning tree data structure
1068 if (_sum_supply == 0) {
1069 // EQ supply constraints
1070 _search_arc_num = _arc_num;
1071 _all_arc_num = _arc_num + _node_num;
1072 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1076 _rev_thread[u + 1] = u;
1080 _state[e] = STATE_TREE;
1081 if (_supply[u] >= 0) {
1086 _flow[e] = _supply[u];
1089 _forward[u] = false;
1093 _flow[e] = -_supply[u];
1094 _cost[e] = ART_COST;
1098 else if (_sum_supply > 0) {
1099 // LEQ supply constraints
1100 _search_arc_num = _arc_num + _node_num;
1101 int f = _arc_num + _node_num;
1102 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1105 _rev_thread[u + 1] = u;
1108 if (_supply[u] >= 0) {
1115 _flow[e] = _supply[u];
1117 _state[e] = STATE_TREE;
1119 _forward[u] = false;
1125 _flow[f] = -_supply[u];
1126 _cost[f] = ART_COST;
1127 _state[f] = STATE_TREE;
1133 _state[e] = STATE_LOWER;
1140 // GEQ 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 _forward[u] = false;
1156 _flow[e] = -_supply[u];
1158 _state[e] = STATE_TREE;
1166 _flow[f] = _supply[u];
1167 _state[f] = STATE_TREE;
1168 _cost[f] = ART_COST;
1174 _state[e] = STATE_LOWER;
1184 // Find the join node
1185 void findJoinNode() {
1186 int u = _source[in_arc];
1187 int v = _target[in_arc];
1189 if (_succ_num[u] < _succ_num[v]) {
1198 // Find the leaving arc of the cycle and returns true if the
1199 // leaving arc is not the same as the entering arc
1200 bool findLeavingArc() {
1201 // Initialize first and second nodes according to the direction
1203 if (_state[in_arc] == STATE_LOWER) {
1204 first = _source[in_arc];
1205 second = _target[in_arc];
1207 first = _target[in_arc];
1208 second = _source[in_arc];
1210 delta = _cap[in_arc];
1215 // Search the cycle along the path form the first node to the root
1216 for (int u = first; u != join; u = _parent[u]) {
1219 _flow[e] : (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]);
1226 // Search the cycle along the path form the second node to the root
1227 for (int u = second; u != join; u = _parent[u]) {
1230 (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]) : _flow[e];
1248 // Change _flow and _state vectors
1249 void changeFlow(bool change) {
1250 // Augment along the cycle
1252 Value val = _state[in_arc] * delta;
1253 _flow[in_arc] += val;
1254 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1255 _flow[_pred[u]] += _forward[u] ? -val : val;
1257 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1258 _flow[_pred[u]] += _forward[u] ? val : -val;
1261 // Update the state of the entering and leaving arcs
1263 _state[in_arc] = STATE_TREE;
1264 _state[_pred[u_out]] =
1265 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1267 _state[in_arc] = -_state[in_arc];
1271 // Update the tree structure
1272 void updateTreeStructure() {
1274 int old_rev_thread = _rev_thread[u_out];
1275 int old_succ_num = _succ_num[u_out];
1276 int old_last_succ = _last_succ[u_out];
1277 v_out = _parent[u_out];
1279 u = _last_succ[u_in]; // the last successor of u_in
1280 right = _thread[u]; // the node after it
1282 // Handle the case when old_rev_thread equals to v_in
1283 // (it also means that join and v_out coincide)
1284 if (old_rev_thread == v_in) {
1285 last = _thread[_last_succ[u_out]];
1287 last = _thread[v_in];
1290 // Update _thread and _parent along the stem nodes (i.e. the nodes
1291 // between u_in and u_out, whose parent have to be changed)
1292 _thread[v_in] = stem = u_in;
1293 _dirty_revs.clear();
1294 _dirty_revs.push_back(v_in);
1296 while (stem != u_out) {
1297 // Insert the next stem node into the thread list
1298 new_stem = _parent[stem];
1299 _thread[u] = new_stem;
1300 _dirty_revs.push_back(u);
1302 // Remove the subtree of stem from the thread list
1303 w = _rev_thread[stem];
1305 _rev_thread[right] = w;
1307 // Change the parent node and shift stem nodes
1308 _parent[stem] = par_stem;
1312 // Update u and right
1313 u = _last_succ[stem] == _last_succ[par_stem] ?
1314 _rev_thread[par_stem] : _last_succ[stem];
1317 _parent[u_out] = par_stem;
1319 _rev_thread[last] = u;
1320 _last_succ[u_out] = u;
1322 // Remove the subtree of u_out from the thread list except for
1323 // the case when old_rev_thread equals to v_in
1324 // (it also means that join and v_out coincide)
1325 if (old_rev_thread != v_in) {
1326 _thread[old_rev_thread] = right;
1327 _rev_thread[right] = old_rev_thread;
1330 // Update _rev_thread using the new _thread values
1331 for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1333 _rev_thread[_thread[u]] = u;
1336 // Update _pred, _forward, _last_succ and _succ_num for the
1337 // stem nodes from u_out to u_in
1338 int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1342 _pred[u] = _pred[w];
1343 _forward[u] = !_forward[w];
1344 tmp_sc += _succ_num[u] - _succ_num[w];
1345 _succ_num[u] = tmp_sc;
1346 _last_succ[w] = tmp_ls;
1349 _pred[u_in] = in_arc;
1350 _forward[u_in] = (u_in == _source[in_arc]);
1351 _succ_num[u_in] = old_succ_num;
1353 // Set limits for updating _last_succ form v_in and v_out
1355 int up_limit_in = -1;
1356 int up_limit_out = -1;
1357 if (_last_succ[join] == v_in) {
1358 up_limit_out = join;
1363 // Update _last_succ from v_in towards the root
1364 for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1366 _last_succ[u] = _last_succ[u_out];
1368 // Update _last_succ from v_out towards the root
1369 if (join != old_rev_thread && v_in != old_rev_thread) {
1370 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1372 _last_succ[u] = old_rev_thread;
1375 for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1377 _last_succ[u] = _last_succ[u_out];
1381 // Update _succ_num from v_in to join
1382 for (u = v_in; u != join; u = _parent[u]) {
1383 _succ_num[u] += old_succ_num;
1385 // Update _succ_num from v_out to join
1386 for (u = v_out; u != join; u = _parent[u]) {
1387 _succ_num[u] -= old_succ_num;
1391 // Update potentials
1392 void updatePotential() {
1393 Cost sigma = _forward[u_in] ?
1394 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1395 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1396 // Update potentials in the subtree, which has been moved
1397 int end = _thread[_last_succ[u_in]];
1398 for (int u = u_in; u != end; u = _thread[u]) {
1403 // Execute the algorithm
1404 ProblemType start(PivotRule pivot_rule) {
1405 // Select the pivot rule implementation
1406 switch (pivot_rule) {
1407 case FIRST_ELIGIBLE:
1408 return start<FirstEligiblePivotRule>();
1410 return start<BestEligiblePivotRule>();
1412 return start<BlockSearchPivotRule>();
1413 case CANDIDATE_LIST:
1414 return start<CandidateListPivotRule>();
1416 return start<AlteringListPivotRule>();
1418 return INFEASIBLE; // avoid warning
1421 template <typename PivotRuleImpl>
1422 ProblemType start() {
1423 PivotRuleImpl pivot(*this);
1425 // Execute the Network Simplex algorithm
1426 while (pivot.findEnteringArc()) {
1428 bool change = findLeavingArc();
1429 if (delta >= MAX) return UNBOUNDED;
1432 updateTreeStructure();
1437 // Check feasibility
1438 for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1439 if (_flow[e] != 0) return INFEASIBLE;
1442 // Transform the solution and the supply map to the original form
1444 for (int i = 0; i != _arc_num; ++i) {
1445 Value c = _lower[i];
1448 _supply[_source[i]] += c;
1449 _supply[_target[i]] -= c;
1454 // Shift potentials to meet the requirements of the GEQ/LEQ type
1455 // optimality conditions
1456 if (_sum_supply == 0) {
1457 if (_stype == GEQ) {
1458 Cost max_pot = std::numeric_limits<Cost>::min();
1459 for (int i = 0; i != _node_num; ++i) {
1460 if (_pi[i] > max_pot) max_pot = _pi[i];
1463 for (int i = 0; i != _node_num; ++i)
1467 Cost min_pot = std::numeric_limits<Cost>::max();
1468 for (int i = 0; i != _node_num; ++i) {
1469 if (_pi[i] < min_pot) min_pot = _pi[i];
1472 for (int i = 0; i != _node_num; ++i)
1481 }; //class NetworkSimplex
1487 #endif //LEMON_NETWORK_SIMPLEX_H