1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_NETWORK_SIMPLEX_H
20 #define LEMON_NETWORK_SIMPLEX_H
22 /// \ingroup min_cost_flow
25 /// \brief Network simplex algorithm for finding a minimum cost flow.
31 #include <lemon/core.h>
32 #include <lemon/math.h>
36 /// \addtogroup min_cost_flow
39 /// \brief Implementation of the primal network simplex algorithm
40 /// for finding a \ref min_cost_flow "minimum cost flow".
42 /// \ref NetworkSimplex implements the primal network simplex algorithm
43 /// for finding a \ref min_cost_flow "minimum cost flow".
45 /// \tparam Digraph The digraph type the algorithm runs on.
46 /// \tparam LowerMap The type of the lower bound map.
47 /// \tparam CapacityMap The type of the capacity (upper bound) map.
48 /// \tparam CostMap The type of the cost (length) map.
49 /// \tparam SupplyMap The type of the supply map.
52 /// - Arc capacities and costs should be \e non-negative \e integers.
53 /// - Supply values should be \e signed \e integers.
54 /// - The value types of the maps should be convertible to each other.
55 /// - \c CostMap::Value must be signed type.
57 /// \note \ref NetworkSimplex provides five different pivot rule
58 /// implementations that significantly affect the efficiency of the
60 /// By default "Block Search" pivot rule is used, which proved to be
61 /// by far the most efficient according to our benchmark tests.
62 /// However another pivot rule can be selected using \ref run()
63 /// function with the proper parameter.
65 template < typename Digraph,
72 template < typename Digraph,
73 typename LowerMap = typename Digraph::template ArcMap<int>,
74 typename CapacityMap = typename Digraph::template ArcMap<int>,
75 typename CostMap = typename Digraph::template ArcMap<int>,
76 typename SupplyMap = typename Digraph::template NodeMap<int> >
80 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
82 typedef typename CapacityMap::Value Capacity;
83 typedef typename CostMap::Value Cost;
84 typedef typename SupplyMap::Value Supply;
86 typedef std::vector<Arc> ArcVector;
87 typedef std::vector<Node> NodeVector;
88 typedef std::vector<int> IntVector;
89 typedef std::vector<bool> BoolVector;
90 typedef std::vector<Capacity> CapacityVector;
91 typedef std::vector<Cost> CostVector;
92 typedef std::vector<Supply> SupplyVector;
96 /// The type of the flow map
97 typedef typename Digraph::template ArcMap<Capacity> FlowMap;
98 /// The type of the potential map
99 typedef typename Digraph::template NodeMap<Cost> PotentialMap;
103 /// Enum type for selecting the pivot rule used by \ref run()
105 FIRST_ELIGIBLE_PIVOT,
108 CANDIDATE_LIST_PIVOT,
114 // State constants for arcs
123 // References for the original data
124 const Digraph &_graph;
125 const LowerMap *_orig_lower;
126 const CapacityMap &_orig_cap;
127 const CostMap &_orig_cost;
128 const SupplyMap *_orig_supply;
131 Capacity _orig_flow_value;
135 PotentialMap *_potential_map;
137 bool _local_potential;
139 // The number of nodes and arcs in the original graph
143 // Data structures for storing the graph
153 CapacityVector _flow;
156 // Data for storing the spanning tree structure
165 // Temporary data used in the current pivot iteration
166 int in_arc, join, u_in, v_in, u_out, v_out;
167 int first, second, right, last;
168 int stem, par_stem, new_stem;
173 /// \brief Implementation of the "First Eligible" pivot rule for the
174 /// \ref NetworkSimplex "network simplex" algorithm.
176 /// This class implements the "First Eligible" pivot rule
177 /// for the \ref NetworkSimplex "network simplex" algorithm.
179 /// For more information see \ref NetworkSimplex::run().
180 class FirstEligiblePivotRule
184 // References to the NetworkSimplex class
185 const IntVector &_source;
186 const IntVector &_target;
187 const CostVector &_cost;
188 const IntVector &_state;
189 const CostVector &_pi;
199 FirstEligiblePivotRule(NetworkSimplex &ns) :
200 _source(ns._source), _target(ns._target),
201 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
202 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
205 /// Find next entering arc
206 bool findEnteringArc() {
208 for (int e = _next_arc; e < _arc_num; ++e) {
209 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
216 for (int e = 0; e < _next_arc; ++e) {
217 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
227 }; //class FirstEligiblePivotRule
230 /// \brief Implementation of the "Best Eligible" pivot rule for the
231 /// \ref NetworkSimplex "network simplex" algorithm.
233 /// This class implements the "Best Eligible" pivot rule
234 /// for the \ref NetworkSimplex "network simplex" algorithm.
236 /// For more information see \ref NetworkSimplex::run().
237 class BestEligiblePivotRule
241 // References to the NetworkSimplex class
242 const IntVector &_source;
243 const IntVector &_target;
244 const CostVector &_cost;
245 const IntVector &_state;
246 const CostVector &_pi;
253 BestEligiblePivotRule(NetworkSimplex &ns) :
254 _source(ns._source), _target(ns._target),
255 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
256 _in_arc(ns.in_arc), _arc_num(ns._arc_num)
259 /// Find next entering arc
260 bool findEnteringArc() {
262 for (int e = 0; e < _arc_num; ++e) {
263 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
272 }; //class BestEligiblePivotRule
275 /// \brief Implementation of the "Block Search" pivot rule for the
276 /// \ref NetworkSimplex "network simplex" algorithm.
278 /// This class implements the "Block Search" pivot rule
279 /// for the \ref NetworkSimplex "network simplex" algorithm.
281 /// For more information see \ref NetworkSimplex::run().
282 class BlockSearchPivotRule
286 // References to the NetworkSimplex class
287 const IntVector &_source;
288 const IntVector &_target;
289 const CostVector &_cost;
290 const IntVector &_state;
291 const CostVector &_pi;
302 BlockSearchPivotRule(NetworkSimplex &ns) :
303 _source(ns._source), _target(ns._target),
304 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
305 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
307 // The main parameters of the pivot rule
308 const double BLOCK_SIZE_FACTOR = 2.0;
309 const int MIN_BLOCK_SIZE = 10;
311 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
315 /// Find next entering arc
316 bool findEnteringArc() {
318 int cnt = _block_size;
319 int e, min_arc = _next_arc;
320 for (e = _next_arc; e < _arc_num; ++e) {
321 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
331 if (min == 0 || cnt > 0) {
332 for (e = 0; e < _next_arc; ++e) {
333 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
344 if (min >= 0) return false;
350 }; //class BlockSearchPivotRule
353 /// \brief Implementation of the "Candidate List" pivot rule for the
354 /// \ref NetworkSimplex "network simplex" algorithm.
356 /// This class implements the "Candidate List" pivot rule
357 /// for the \ref NetworkSimplex "network simplex" algorithm.
359 /// For more information see \ref NetworkSimplex::run().
360 class CandidateListPivotRule
364 // References to the NetworkSimplex class
365 const IntVector &_source;
366 const IntVector &_target;
367 const CostVector &_cost;
368 const IntVector &_state;
369 const CostVector &_pi;
374 IntVector _candidates;
375 int _list_length, _minor_limit;
376 int _curr_length, _minor_count;
382 CandidateListPivotRule(NetworkSimplex &ns) :
383 _source(ns._source), _target(ns._target),
384 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
385 _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
387 // The main parameters of the pivot rule
388 const double LIST_LENGTH_FACTOR = 1.0;
389 const int MIN_LIST_LENGTH = 10;
390 const double MINOR_LIMIT_FACTOR = 0.1;
391 const int MIN_MINOR_LIMIT = 3;
393 _list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_arc_num)),
395 _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
397 _curr_length = _minor_count = 0;
398 _candidates.resize(_list_length);
401 /// Find next entering arc
402 bool findEnteringArc() {
404 int e, min_arc = _next_arc;
405 if (_curr_length > 0 && _minor_count < _minor_limit) {
406 // Minor iteration: select the best eligible arc from the
407 // current candidate list
410 for (int i = 0; i < _curr_length; ++i) {
412 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
418 _candidates[i--] = _candidates[--_curr_length];
427 // Major iteration: build a new candidate list
430 for (e = _next_arc; e < _arc_num; ++e) {
431 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
433 _candidates[_curr_length++] = e;
438 if (_curr_length == _list_length) break;
441 if (_curr_length < _list_length) {
442 for (e = 0; e < _next_arc; ++e) {
443 c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
445 _candidates[_curr_length++] = e;
450 if (_curr_length == _list_length) break;
454 if (_curr_length == 0) return false;
461 }; //class CandidateListPivotRule
464 /// \brief Implementation of the "Altering Candidate List" pivot rule
465 /// for the \ref NetworkSimplex "network simplex" algorithm.
467 /// This class implements the "Altering Candidate List" pivot rule
468 /// for the \ref NetworkSimplex "network simplex" algorithm.
470 /// For more information see \ref NetworkSimplex::run().
471 class AlteringListPivotRule
475 // References to the NetworkSimplex class
476 const IntVector &_source;
477 const IntVector &_target;
478 const CostVector &_cost;
479 const IntVector &_state;
480 const CostVector &_pi;
485 int _block_size, _head_length, _curr_length;
487 IntVector _candidates;
488 CostVector _cand_cost;
490 // Functor class to compare arcs during sort of the candidate list
494 const CostVector &_map;
496 SortFunc(const CostVector &map) : _map(map) {}
497 bool operator()(int left, int right) {
498 return _map[left] > _map[right];
507 AlteringListPivotRule(NetworkSimplex &ns) :
508 _source(ns._source), _target(ns._target),
509 _cost(ns._cost), _state(ns._state), _pi(ns._pi),
510 _in_arc(ns.in_arc), _arc_num(ns._arc_num),
511 _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
513 // The main parameters of the pivot rule
514 const double BLOCK_SIZE_FACTOR = 1.5;
515 const int MIN_BLOCK_SIZE = 10;
516 const double HEAD_LENGTH_FACTOR = 0.1;
517 const int MIN_HEAD_LENGTH = 3;
519 _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
521 _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
523 _candidates.resize(_head_length + _block_size);
527 /// Find next entering arc
528 bool findEnteringArc() {
529 // Check the current candidate list
531 for (int i = 0; i < _curr_length; ++i) {
533 _cand_cost[e] = _state[e] *
534 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
535 if (_cand_cost[e] >= 0) {
536 _candidates[i--] = _candidates[--_curr_length];
541 int cnt = _block_size;
543 int limit = _head_length;
545 for (int e = _next_arc; e < _arc_num; ++e) {
546 _cand_cost[e] = _state[e] *
547 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
548 if (_cand_cost[e] < 0) {
549 _candidates[_curr_length++] = e;
553 if (_curr_length > limit) break;
558 if (_curr_length <= limit) {
559 for (int e = 0; e < _next_arc; ++e) {
560 _cand_cost[e] = _state[e] *
561 (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
562 if (_cand_cost[e] < 0) {
563 _candidates[_curr_length++] = e;
567 if (_curr_length > limit) break;
573 if (_curr_length == 0) return false;
574 _next_arc = last_arc + 1;
576 // Make heap of the candidate list (approximating a partial sort)
577 make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
580 // Pop the first element of the heap
581 _in_arc = _candidates[0];
582 pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
584 _curr_length = std::min(_head_length, _curr_length - 1);
588 }; //class AlteringListPivotRule
592 /// \brief General constructor (with lower bounds).
594 /// General constructor (with lower bounds).
596 /// \param graph The digraph the algorithm runs on.
597 /// \param lower The lower bounds of the arcs.
598 /// \param capacity The capacities (upper bounds) of the arcs.
599 /// \param cost The cost (length) values of the arcs.
600 /// \param supply The supply values of the nodes (signed).
601 NetworkSimplex( const Digraph &graph,
602 const LowerMap &lower,
603 const CapacityMap &capacity,
605 const SupplyMap &supply ) :
606 _graph(graph), _orig_lower(&lower), _orig_cap(capacity),
607 _orig_cost(cost), _orig_supply(&supply),
608 _flow_map(NULL), _potential_map(NULL),
609 _local_flow(false), _local_potential(false),
613 /// \brief General constructor (without lower bounds).
615 /// General constructor (without lower bounds).
617 /// \param graph The digraph the algorithm runs on.
618 /// \param capacity The capacities (upper bounds) of the arcs.
619 /// \param cost The cost (length) values of the arcs.
620 /// \param supply The supply values of the nodes (signed).
621 NetworkSimplex( const Digraph &graph,
622 const CapacityMap &capacity,
624 const SupplyMap &supply ) :
625 _graph(graph), _orig_lower(NULL), _orig_cap(capacity),
626 _orig_cost(cost), _orig_supply(&supply),
627 _flow_map(NULL), _potential_map(NULL),
628 _local_flow(false), _local_potential(false),
632 /// \brief Simple constructor (with lower bounds).
634 /// Simple constructor (with lower bounds).
636 /// \param graph The digraph the algorithm runs on.
637 /// \param lower The lower bounds of the arcs.
638 /// \param capacity The capacities (upper bounds) of the arcs.
639 /// \param cost The cost (length) values of the arcs.
640 /// \param s The source node.
641 /// \param t The target node.
642 /// \param flow_value The required amount of flow from node \c s
643 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
644 NetworkSimplex( const Digraph &graph,
645 const LowerMap &lower,
646 const CapacityMap &capacity,
649 Capacity flow_value ) :
650 _graph(graph), _orig_lower(&lower), _orig_cap(capacity),
651 _orig_cost(cost), _orig_supply(NULL),
652 _orig_source(s), _orig_target(t), _orig_flow_value(flow_value),
653 _flow_map(NULL), _potential_map(NULL),
654 _local_flow(false), _local_potential(false),
658 /// \brief Simple constructor (without lower bounds).
660 /// Simple constructor (without lower bounds).
662 /// \param graph The digraph the algorithm runs on.
663 /// \param capacity The capacities (upper bounds) of the arcs.
664 /// \param cost The cost (length) values of the arcs.
665 /// \param s The source node.
666 /// \param t The target node.
667 /// \param flow_value The required amount of flow from node \c s
668 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
669 NetworkSimplex( const Digraph &graph,
670 const CapacityMap &capacity,
673 Capacity flow_value ) :
674 _graph(graph), _orig_lower(NULL), _orig_cap(capacity),
675 _orig_cost(cost), _orig_supply(NULL),
676 _orig_source(s), _orig_target(t), _orig_flow_value(flow_value),
677 _flow_map(NULL), _potential_map(NULL),
678 _local_flow(false), _local_potential(false),
684 if (_local_flow) delete _flow_map;
685 if (_local_potential) delete _potential_map;
688 /// \brief Set the flow map.
690 /// This function sets the flow map.
692 /// \return <tt>(*this)</tt>
693 NetworkSimplex& flowMap(FlowMap &map) {
702 /// \brief Set the potential map.
704 /// This function sets the potential map.
706 /// \return <tt>(*this)</tt>
707 NetworkSimplex& potentialMap(PotentialMap &map) {
708 if (_local_potential) {
709 delete _potential_map;
710 _local_potential = false;
712 _potential_map = ↦
716 /// \name Execution control
717 /// The algorithm can be executed using the
718 /// \ref lemon::NetworkSimplex::run() "run()" function.
721 /// \brief Run the algorithm.
723 /// This function runs the algorithm.
725 /// \param pivot_rule The pivot rule that is used during the
728 /// The available pivot rules:
730 /// - FIRST_ELIGIBLE_PIVOT The next eligible arc is selected in
731 /// a wraparound fashion in every iteration
732 /// (\ref FirstEligiblePivotRule).
734 /// - BEST_ELIGIBLE_PIVOT The best eligible arc is selected in
735 /// every iteration (\ref BestEligiblePivotRule).
737 /// - BLOCK_SEARCH_PIVOT A specified number of arcs are examined in
738 /// every iteration in a wraparound fashion and the best eligible
739 /// arc is selected from this block (\ref BlockSearchPivotRule).
741 /// - CANDIDATE_LIST_PIVOT In a major iteration a candidate list is
742 /// built from eligible arcs in a wraparound fashion and in the
743 /// following minor iterations the best eligible arc is selected
744 /// from this list (\ref CandidateListPivotRule).
746 /// - ALTERING_LIST_PIVOT It is a modified version of the
747 /// "Candidate List" pivot rule. It keeps only the several best
748 /// eligible arcs from the former candidate list and extends this
749 /// list in every iteration (\ref AlteringListPivotRule).
751 /// According to our comprehensive benchmark tests the "Block Search"
752 /// pivot rule proved to be the fastest and the most robust on
753 /// various test inputs. Thus it is the default option.
755 /// \return \c true if a feasible flow can be found.
756 bool run(PivotRuleEnum pivot_rule = BLOCK_SEARCH_PIVOT) {
757 return init() && start(pivot_rule);
762 /// \name Query Functions
763 /// The results of the algorithm can be obtained using these
765 /// \ref lemon::NetworkSimplex::run() "run()" must be called before
769 /// \brief Return a const reference to the flow map.
771 /// This function returns a const reference to an arc map storing
774 /// \pre \ref run() must be called before using this function.
775 const FlowMap& flowMap() const {
779 /// \brief Return a const reference to the potential map
780 /// (the dual solution).
782 /// This function returns a const reference to a node map storing
783 /// the found potentials (the dual solution).
785 /// \pre \ref run() must be called before using this function.
786 const PotentialMap& potentialMap() const {
787 return *_potential_map;
790 /// \brief Return the flow on the given arc.
792 /// This function returns the flow on the given arc.
794 /// \pre \ref run() must be called before using this function.
795 Capacity flow(const Arc& arc) const {
796 return (*_flow_map)[arc];
799 /// \brief Return the potential of the given node.
801 /// This function returns the potential of the given node.
803 /// \pre \ref run() must be called before using this function.
804 Cost potential(const Node& node) const {
805 return (*_potential_map)[node];
808 /// \brief Return the total cost of the found flow.
810 /// This function returns the total cost of the found flow.
811 /// The complexity of the function is \f$ O(e) \f$.
813 /// \pre \ref run() must be called before using this function.
814 Cost totalCost() const {
816 for (ArcIt e(_graph); e != INVALID; ++e)
817 c += (*_flow_map)[e] * _orig_cost[e];
825 // Initialize internal data structures
827 // Initialize result maps
829 _flow_map = new FlowMap(_graph);
832 if (!_potential_map) {
833 _potential_map = new PotentialMap(_graph);
834 _local_potential = true;
837 // Initialize vectors
838 _node_num = countNodes(_graph);
839 _arc_num = countArcs(_graph);
840 int all_node_num = _node_num + 1;
841 int all_arc_num = _arc_num + _node_num;
843 _arc_ref.resize(_arc_num);
844 _source.resize(all_arc_num);
845 _target.resize(all_arc_num);
847 _cap.resize(all_arc_num);
848 _cost.resize(all_arc_num);
849 _supply.resize(all_node_num);
850 _flow.resize(all_arc_num, 0);
851 _pi.resize(all_node_num, 0);
853 _depth.resize(all_node_num);
854 _parent.resize(all_node_num);
855 _pred.resize(all_node_num);
856 _forward.resize(all_node_num);
857 _thread.resize(all_node_num);
858 _state.resize(all_arc_num, STATE_LOWER);
860 // Initialize node related data
861 bool valid_supply = true;
865 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
867 _supply[i] = (*_orig_supply)[n];
870 valid_supply = (sum == 0);
873 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
877 _supply[_node_id[_orig_source]] = _orig_flow_value;
878 _supply[_node_id[_orig_target]] = -_orig_flow_value;
880 if (!valid_supply) return false;
882 // Set data for the artificial root node
891 // Store the arcs in a mixed order
892 int k = std::max(int(sqrt(_arc_num)), 10);
894 for (ArcIt e(_graph); e != INVALID; ++e) {
896 if ((i += k) >= _arc_num) i = (i % k) + 1;
899 // Initialize arc maps
900 for (int i = 0; i != _arc_num; ++i) {
902 _source[i] = _node_id[_graph.source(e)];
903 _target[i] = _node_id[_graph.target(e)];
904 _cost[i] = _orig_cost[e];
905 _cap[i] = _orig_cap[e];
908 // Remove non-zero lower bounds
910 for (int i = 0; i != _arc_num; ++i) {
911 Capacity c = (*_orig_lower)[_arc_ref[i]];
914 _supply[_source[i]] -= c;
915 _supply[_target[i]] += c;
920 // Add artificial arcs and initialize the spanning tree data structure
921 Cost max_cost = std::numeric_limits<Cost>::max() / 4;
922 Capacity max_cap = std::numeric_limits<Capacity>::max();
923 for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
928 if (_supply[u] >= 0) {
929 _flow[e] = _supply[u];
933 _flow[e] = -_supply[u];
939 _state[e] = STATE_TREE;
945 // Find the join node
946 void findJoinNode() {
947 int u = _source[in_arc];
948 int v = _target[in_arc];
949 while (_depth[u] > _depth[v]) u = _parent[u];
950 while (_depth[v] > _depth[u]) v = _parent[v];
958 // Find the leaving arc of the cycle and returns true if the
959 // leaving arc is not the same as the entering arc
960 bool findLeavingArc() {
961 // Initialize first and second nodes according to the direction
963 if (_state[in_arc] == STATE_LOWER) {
964 first = _source[in_arc];
965 second = _target[in_arc];
967 first = _target[in_arc];
968 second = _source[in_arc];
970 delta = _cap[in_arc];
975 // Search the cycle along the path form the first node to the root
976 for (int u = first; u != join; u = _parent[u]) {
978 d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
985 // Search the cycle along the path form the second node to the root
986 for (int u = second; u != join; u = _parent[u]) {
988 d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
1006 // Change _flow and _state vectors
1007 void changeFlow(bool change) {
1008 // Augment along the cycle
1010 Capacity val = _state[in_arc] * delta;
1011 _flow[in_arc] += val;
1012 for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1013 _flow[_pred[u]] += _forward[u] ? -val : val;
1015 for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1016 _flow[_pred[u]] += _forward[u] ? val : -val;
1019 // Update the state of the entering and leaving arcs
1021 _state[in_arc] = STATE_TREE;
1022 _state[_pred[u_out]] =
1023 (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1025 _state[in_arc] = -_state[in_arc];
1029 // Update _thread and _parent vectors
1030 void updateThreadParent() {
1032 v_out = _parent[u_out];
1034 // Handle the case when join and v_out coincide
1035 bool par_first = false;
1036 if (join == v_out) {
1037 for (u = join; u != u_in && u != v_in; u = _thread[u]) ;
1040 while (_thread[u] != u_out) u = _thread[u];
1045 // Find the last successor of u_in (u) and the node after it (right)
1046 // according to the thread index
1047 for (u = u_in; _depth[_thread[u]] > _depth[u_in]; u = _thread[u]) ;
1049 if (_thread[v_in] == u_out) {
1050 for (last = u; _depth[last] > _depth[u_out]; last = _thread[last]) ;
1051 if (last == u_out) last = _thread[last];
1053 else last = _thread[v_in];
1055 // Update stem nodes
1056 _thread[v_in] = stem = u_in;
1058 while (stem != u_out) {
1059 _thread[u] = new_stem = _parent[stem];
1061 // Find the node just before the stem node (u) according to
1062 // the original thread index
1063 for (u = new_stem; _thread[u] != stem; u = _thread[u]) ;
1066 // Change the parent node of stem and shift stem and par_stem nodes
1067 _parent[stem] = par_stem;
1071 // Find the last successor of stem (u) and the node after it (right)
1072 // according to the thread index
1073 for (u = stem; _depth[_thread[u]] > _depth[stem]; u = _thread[u]) ;
1076 _parent[u_out] = par_stem;
1079 if (join == v_out && par_first) {
1080 if (first != v_in) _thread[first] = right;
1082 for (u = v_out; _thread[u] != u_out; u = _thread[u]) ;
1087 // Update _pred and _forward vectors
1088 void updatePredArc() {
1092 _pred[u] = _pred[v];
1093 _forward[u] = !_forward[v];
1096 _pred[u_in] = in_arc;
1097 _forward[u_in] = (u_in == _source[in_arc]);
1100 // Update _depth and _potential vectors
1101 void updateDepthPotential() {
1102 _depth[u_in] = _depth[v_in] + 1;
1103 Cost sigma = _forward[u_in] ?
1104 _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1105 _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1107 for(int u = _thread[u_in]; _parent[u] != -1; u = _thread[u]) {
1108 _depth[u] = _depth[_parent[u]] + 1;
1109 if (_depth[u] <= _depth[u_in]) break;
1114 // Execute the algorithm
1115 bool start(PivotRuleEnum pivot_rule) {
1116 // Select the pivot rule implementation
1117 switch (pivot_rule) {
1118 case FIRST_ELIGIBLE_PIVOT:
1119 return start<FirstEligiblePivotRule>();
1120 case BEST_ELIGIBLE_PIVOT:
1121 return start<BestEligiblePivotRule>();
1122 case BLOCK_SEARCH_PIVOT:
1123 return start<BlockSearchPivotRule>();
1124 case CANDIDATE_LIST_PIVOT:
1125 return start<CandidateListPivotRule>();
1126 case ALTERING_LIST_PIVOT:
1127 return start<AlteringListPivotRule>();
1132 template<class PivotRuleImplementation>
1134 PivotRuleImplementation pivot(*this);
1136 // Execute the network simplex algorithm
1137 while (pivot.findEnteringArc()) {
1139 bool change = findLeavingArc();
1142 updateThreadParent();
1144 updateDepthPotential();
1148 // Check if the flow amount equals zero on all the artificial arcs
1149 for (int e = _arc_num; e != _arc_num + _node_num; ++e) {
1150 if (_flow[e] > 0) return false;
1153 // Copy flow values to _flow_map
1155 for (int i = 0; i != _arc_num; ++i) {
1156 Arc e = _arc_ref[i];
1157 _flow_map->set(e, (*_orig_lower)[e] + _flow[i]);
1160 for (int i = 0; i != _arc_num; ++i) {
1161 _flow_map->set(_arc_ref[i], _flow[i]);
1164 // Copy potential values to _potential_map
1165 for (NodeIt n(_graph); n != INVALID; ++n) {
1166 _potential_map->set(n, _pi[_node_id[n]]);
1172 }; //class NetworkSimplex
1178 #endif //LEMON_NETWORK_SIMPLEX_H