lemon/network_simplex.h
author Alpar Juttner <alpar@cs.elte.hu>
Fri, 12 Feb 2010 21:53:15 +0100
changeset 826 02109e17027f
parent 811 fe80a8145653
child 830 75c97c3786d6
child 839 f3bc4e9b5f3a
permissions -rw-r--r--
Merge
     1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library.
     4  *
     5  * Copyright (C) 2003-2009
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     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.
    12  *
    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
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_NETWORK_SIMPLEX_H
    20 #define LEMON_NETWORK_SIMPLEX_H
    21 
    22 /// \ingroup min_cost_flow_algs
    23 ///
    24 /// \file
    25 /// \brief Network Simplex algorithm for finding a minimum cost flow.
    26 
    27 #include <vector>
    28 #include <limits>
    29 #include <algorithm>
    30 
    31 #include <lemon/core.h>
    32 #include <lemon/math.h>
    33 
    34 namespace lemon {
    35 
    36   /// \addtogroup min_cost_flow_algs
    37   /// @{
    38 
    39   /// \brief Implementation of the primal Network Simplex algorithm
    40   /// for finding a \ref min_cost_flow "minimum cost flow".
    41   ///
    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
    48   /// flow problem.
    49   ///
    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.
    54   ///
    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.
    59   ///
    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.
    65   ///
    66   /// \warning Both number types must be signed and all input data must
    67   /// be integer.
    68   ///
    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>
    73   class NetworkSimplex
    74   {
    75   public:
    76 
    77     /// The type of the flow amounts, capacity bounds and supply values
    78     typedef V Value;
    79     /// The type of the arc costs
    80     typedef C Cost;
    81 
    82   public:
    83 
    84     /// \brief Problem type constants for the \c run() function.
    85     ///
    86     /// Enum type containing the problem type constants that can be
    87     /// returned by the \ref run() function of the algorithm.
    88     enum ProblemType {
    89       /// The problem has no feasible solution (flow).
    90       INFEASIBLE,
    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).
    94       OPTIMAL,
    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.
    98       UNBOUNDED
    99     };
   100     
   101     /// \brief Constants for selecting the type of the supply constraints.
   102     ///
   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".
   106     ///
   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.
   110     enum SupplyType {
   111       /// This option means that there are <em>"greater or equal"</em>
   112       /// supply/demand constraints in the definition of the problem.
   113       GEQ,
   114       /// This option means that there are <em>"less or equal"</em>
   115       /// supply/demand constraints in the definition of the problem.
   116       LEQ
   117     };
   118     
   119     /// \brief Constants for selecting the pivot rule.
   120     ///
   121     /// Enum type containing constants for selecting the pivot rule for
   122     /// the \ref run() function.
   123     ///
   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
   129     /// test inputs.
   130     /// However, another pivot rule can be selected using the \ref run()
   131     /// function with the proper parameter.
   132     enum PivotRule {
   133 
   134       /// The \e First \e Eligible pivot rule.
   135       /// The next eligible arc is selected in a wraparound fashion
   136       /// in every iteration.
   137       FIRST_ELIGIBLE,
   138 
   139       /// The \e Best \e Eligible pivot rule.
   140       /// The best eligible arc is selected in every iteration.
   141       BEST_ELIGIBLE,
   142 
   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
   146       /// from this block.
   147       BLOCK_SEARCH,
   148 
   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.
   153       CANDIDATE_LIST,
   154 
   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.
   159       ALTERING_LIST
   160     };
   161     
   162   private:
   163 
   164     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
   165 
   166     typedef std::vector<int> IntVector;
   167     typedef std::vector<char> CharVector;
   168     typedef std::vector<Value> ValueVector;
   169     typedef std::vector<Cost> CostVector;
   170 
   171     // State constants for arcs
   172     enum ArcStateEnum {
   173       STATE_UPPER = -1,
   174       STATE_TREE  =  0,
   175       STATE_LOWER =  1
   176     };
   177 
   178   private:
   179 
   180     // Data related to the underlying digraph
   181     const GR &_graph;
   182     int _node_num;
   183     int _arc_num;
   184     int _all_arc_num;
   185     int _search_arc_num;
   186 
   187     // Parameters of the problem
   188     bool _have_lower;
   189     SupplyType _stype;
   190     Value _sum_supply;
   191 
   192     // Data structures for storing the digraph
   193     IntNodeMap _node_id;
   194     IntArcMap _arc_id;
   195     IntVector _source;
   196     IntVector _target;
   197 
   198     // Node and arc data
   199     ValueVector _lower;
   200     ValueVector _upper;
   201     ValueVector _cap;
   202     CostVector _cost;
   203     ValueVector _supply;
   204     ValueVector _flow;
   205     CostVector _pi;
   206 
   207     // Data for storing the spanning tree structure
   208     IntVector _parent;
   209     IntVector _pred;
   210     IntVector _thread;
   211     IntVector _rev_thread;
   212     IntVector _succ_num;
   213     IntVector _last_succ;
   214     IntVector _dirty_revs;
   215     CharVector _forward;
   216     CharVector _state;
   217     int _root;
   218 
   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;
   223     Value delta;
   224     
   225     const Value MAX;
   226 
   227   public:
   228   
   229     /// \brief Constant for infinite upper bounds (capacities).
   230     ///
   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.
   234     const Value INF;
   235 
   236   private:
   237 
   238     // Implementation of the First Eligible pivot rule
   239     class FirstEligiblePivotRule
   240     {
   241     private:
   242 
   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;
   249       int &_in_arc;
   250       int _search_arc_num;
   251 
   252       // Pivot rule data
   253       int _next_arc;
   254 
   255     public:
   256 
   257       // Constructor
   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),
   262         _next_arc(0)
   263       {}
   264 
   265       // Find next entering arc
   266       bool findEnteringArc() {
   267         Cost c;
   268         for (int e = _next_arc; e < _search_arc_num; ++e) {
   269           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   270           if (c < 0) {
   271             _in_arc = e;
   272             _next_arc = e + 1;
   273             return true;
   274           }
   275         }
   276         for (int e = 0; e < _next_arc; ++e) {
   277           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   278           if (c < 0) {
   279             _in_arc = e;
   280             _next_arc = e + 1;
   281             return true;
   282           }
   283         }
   284         return false;
   285       }
   286 
   287     }; //class FirstEligiblePivotRule
   288 
   289 
   290     // Implementation of the Best Eligible pivot rule
   291     class BestEligiblePivotRule
   292     {
   293     private:
   294 
   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;
   301       int &_in_arc;
   302       int _search_arc_num;
   303 
   304     public:
   305 
   306       // Constructor
   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)
   311       {}
   312 
   313       // Find next entering arc
   314       bool findEnteringArc() {
   315         Cost c, min = 0;
   316         for (int e = 0; e < _search_arc_num; ++e) {
   317           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   318           if (c < min) {
   319             min = c;
   320             _in_arc = e;
   321           }
   322         }
   323         return min < 0;
   324       }
   325 
   326     }; //class BestEligiblePivotRule
   327 
   328 
   329     // Implementation of the Block Search pivot rule
   330     class BlockSearchPivotRule
   331     {
   332     private:
   333 
   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;
   340       int &_in_arc;
   341       int _search_arc_num;
   342 
   343       // Pivot rule data
   344       int _block_size;
   345       int _next_arc;
   346 
   347     public:
   348 
   349       // Constructor
   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),
   354         _next_arc(0)
   355       {
   356         // The main parameters of the pivot rule
   357         const double BLOCK_SIZE_FACTOR = 0.5;
   358         const int MIN_BLOCK_SIZE = 10;
   359 
   360         _block_size = std::max( int(BLOCK_SIZE_FACTOR *
   361                                     std::sqrt(double(_search_arc_num))),
   362                                 MIN_BLOCK_SIZE );
   363       }
   364 
   365       // Find next entering arc
   366       bool findEnteringArc() {
   367         Cost c, min = 0;
   368         int cnt = _block_size;
   369         int e;
   370         for (e = _next_arc; e < _search_arc_num; ++e) {
   371           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   372           if (c < min) {
   373             min = c;
   374             _in_arc = e;
   375           }
   376           if (--cnt == 0) {
   377             if (min < 0) goto search_end;
   378             cnt = _block_size;
   379           }
   380         }
   381         for (e = 0; e < _next_arc; ++e) {
   382           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   383           if (c < min) {
   384             min = c;
   385             _in_arc = e;
   386           }
   387           if (--cnt == 0) {
   388             if (min < 0) goto search_end;
   389             cnt = _block_size;
   390           }
   391         }
   392         if (min >= 0) return false;
   393 
   394       search_end:
   395         _next_arc = e;
   396         return true;
   397       }
   398 
   399     }; //class BlockSearchPivotRule
   400 
   401 
   402     // Implementation of the Candidate List pivot rule
   403     class CandidateListPivotRule
   404     {
   405     private:
   406 
   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;
   413       int &_in_arc;
   414       int _search_arc_num;
   415 
   416       // Pivot rule data
   417       IntVector _candidates;
   418       int _list_length, _minor_limit;
   419       int _curr_length, _minor_count;
   420       int _next_arc;
   421 
   422     public:
   423 
   424       /// Constructor
   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),
   429         _next_arc(0)
   430       {
   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;
   436 
   437         _list_length = std::max( int(LIST_LENGTH_FACTOR *
   438                                      std::sqrt(double(_search_arc_num))),
   439                                  MIN_LIST_LENGTH );
   440         _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
   441                                  MIN_MINOR_LIMIT );
   442         _curr_length = _minor_count = 0;
   443         _candidates.resize(_list_length);
   444       }
   445 
   446       /// Find next entering arc
   447       bool findEnteringArc() {
   448         Cost min, c;
   449         int e;
   450         if (_curr_length > 0 && _minor_count < _minor_limit) {
   451           // Minor iteration: select the best eligible arc from the
   452           // current candidate list
   453           ++_minor_count;
   454           min = 0;
   455           for (int i = 0; i < _curr_length; ++i) {
   456             e = _candidates[i];
   457             c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   458             if (c < min) {
   459               min = c;
   460               _in_arc = e;
   461             }
   462             else if (c >= 0) {
   463               _candidates[i--] = _candidates[--_curr_length];
   464             }
   465           }
   466           if (min < 0) return true;
   467         }
   468 
   469         // Major iteration: build a new candidate list
   470         min = 0;
   471         _curr_length = 0;
   472         for (e = _next_arc; e < _search_arc_num; ++e) {
   473           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   474           if (c < 0) {
   475             _candidates[_curr_length++] = e;
   476             if (c < min) {
   477               min = c;
   478               _in_arc = e;
   479             }
   480             if (_curr_length == _list_length) goto search_end;
   481           }
   482         }
   483         for (e = 0; e < _next_arc; ++e) {
   484           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   485           if (c < 0) {
   486             _candidates[_curr_length++] = e;
   487             if (c < min) {
   488               min = c;
   489               _in_arc = e;
   490             }
   491             if (_curr_length == _list_length) goto search_end;
   492           }
   493         }
   494         if (_curr_length == 0) return false;
   495       
   496       search_end:        
   497         _minor_count = 1;
   498         _next_arc = e;
   499         return true;
   500       }
   501 
   502     }; //class CandidateListPivotRule
   503 
   504 
   505     // Implementation of the Altering Candidate List pivot rule
   506     class AlteringListPivotRule
   507     {
   508     private:
   509 
   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;
   516       int &_in_arc;
   517       int _search_arc_num;
   518 
   519       // Pivot rule data
   520       int _block_size, _head_length, _curr_length;
   521       int _next_arc;
   522       IntVector _candidates;
   523       CostVector _cand_cost;
   524 
   525       // Functor class to compare arcs during sort of the candidate list
   526       class SortFunc
   527       {
   528       private:
   529         const CostVector &_map;
   530       public:
   531         SortFunc(const CostVector &map) : _map(map) {}
   532         bool operator()(int left, int right) {
   533           return _map[left] > _map[right];
   534         }
   535       };
   536 
   537       SortFunc _sort_func;
   538 
   539     public:
   540 
   541       // Constructor
   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)
   547       {
   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;
   553 
   554         _block_size = std::max( int(BLOCK_SIZE_FACTOR *
   555                                     std::sqrt(double(_search_arc_num))),
   556                                 MIN_BLOCK_SIZE );
   557         _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
   558                                  MIN_HEAD_LENGTH );
   559         _candidates.resize(_head_length + _block_size);
   560         _curr_length = 0;
   561       }
   562 
   563       // Find next entering arc
   564       bool findEnteringArc() {
   565         // Check the current candidate list
   566         int e;
   567         for (int i = 0; i < _curr_length; ++i) {
   568           e = _candidates[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];
   573           }
   574         }
   575 
   576         // Extend the list
   577         int cnt = _block_size;
   578         int limit = _head_length;
   579 
   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;
   585           }
   586           if (--cnt == 0) {
   587             if (_curr_length > limit) goto search_end;
   588             limit = 0;
   589             cnt = _block_size;
   590           }
   591         }
   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;
   597           }
   598           if (--cnt == 0) {
   599             if (_curr_length > limit) goto search_end;
   600             limit = 0;
   601             cnt = _block_size;
   602           }
   603         }
   604         if (_curr_length == 0) return false;
   605         
   606       search_end:
   607 
   608         // Make heap of the candidate list (approximating a partial sort)
   609         make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
   610                    _sort_func );
   611 
   612         // Pop the first element of the heap
   613         _in_arc = _candidates[0];
   614         _next_arc = e;
   615         pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
   616                   _sort_func );
   617         _curr_length = std::min(_head_length, _curr_length - 1);
   618         return true;
   619       }
   620 
   621     }; //class AlteringListPivotRule
   622 
   623   public:
   624 
   625     /// \brief Constructor.
   626     ///
   627     /// The constructor of the class.
   628     ///
   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)
   639     {
   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");
   645         
   646       // Resize vectors
   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;
   651 
   652       _source.resize(max_arc_num);
   653       _target.resize(max_arc_num);
   654 
   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);
   662 
   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);
   671 
   672       // Copy the graph
   673       int i = 0;
   674       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   675         _node_id[n] = i;
   676       }
   677       if (arc_mixing) {
   678         // Store the arcs in a mixed order
   679         int k = std::max(int(std::sqrt(double(_arc_num))), 10);
   680         int i = 0, j = 0;
   681         for (ArcIt a(_graph); a != INVALID; ++a) {
   682           _arc_id[a] = i;
   683           _source[i] = _node_id[_graph.source(a)];
   684           _target[i] = _node_id[_graph.target(a)];
   685           if ((i += k) >= _arc_num) i = ++j;
   686         }
   687       } else {
   688         // Store the arcs in the original order
   689         int i = 0;
   690         for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
   691           _arc_id[a] = i;
   692           _source[i] = _node_id[_graph.source(a)];
   693           _target[i] = _node_id[_graph.target(a)];
   694         }
   695       }
   696       
   697       // Reset parameters
   698       reset();
   699     }
   700 
   701     /// \name Parameters
   702     /// The parameters of the algorithm can be specified using these
   703     /// functions.
   704 
   705     /// @{
   706 
   707     /// \brief Set the lower bounds on the arcs.
   708     ///
   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.
   712     ///
   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.
   716     ///
   717     /// \return <tt>(*this)</tt>
   718     template <typename LowerMap>
   719     NetworkSimplex& lowerMap(const LowerMap& map) {
   720       _have_lower = true;
   721       for (ArcIt a(_graph); a != INVALID; ++a) {
   722         _lower[_arc_id[a]] = map[a];
   723       }
   724       return *this;
   725     }
   726 
   727     /// \brief Set the upper bounds (capacities) on the arcs.
   728     ///
   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).
   733     ///
   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.
   737     ///
   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];
   743       }
   744       return *this;
   745     }
   746 
   747     /// \brief Set the costs of the arcs.
   748     ///
   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.
   752     ///
   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.
   756     ///
   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];
   762       }
   763       return *this;
   764     }
   765 
   766     /// \brief Set the supply values of the nodes.
   767     ///
   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.
   771     ///
   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.
   775     ///
   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];
   781       }
   782       return *this;
   783     }
   784 
   785     /// \brief Set single source and target nodes and a supply value.
   786     ///
   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.
   791     ///
   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.
   795     ///
   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).
   800     ///
   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) {
   804         _supply[i] = 0;
   805       }
   806       _supply[_node_id[s]] =  k;
   807       _supply[_node_id[t]] = -k;
   808       return *this;
   809     }
   810     
   811     /// \brief Set the type of the supply constraints.
   812     ///
   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.
   816     ///
   817     /// For more information, see \ref SupplyType.
   818     ///
   819     /// \return <tt>(*this)</tt>
   820     NetworkSimplex& supplyType(SupplyType supply_type) {
   821       _stype = supply_type;
   822       return *this;
   823     }
   824 
   825     /// @}
   826 
   827     /// \name Execution Control
   828     /// The algorithm can be executed using \ref run().
   829 
   830     /// @{
   831 
   832     /// \brief Run the algorithm.
   833     ///
   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().
   838     /// For example,
   839     /// \code
   840     ///   NetworkSimplex<ListDigraph> ns(graph);
   841     ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
   842     ///     .supplyMap(sup).run();
   843     /// \endcode
   844     ///
   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.
   851     ///
   852     /// \param pivot_rule The pivot rule that will be used during the
   853     /// algorithm. For more information, see \ref PivotRule.
   854     ///
   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.
   862     ///
   863     /// \see ProblemType, PivotRule
   864     ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
   865       if (!init()) return INFEASIBLE;
   866       return start(pivot_rule);
   867     }
   868 
   869     /// \brief Reset all the parameters that have been given before.
   870     ///
   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().
   874     ///
   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
   877     /// \ref run() call.
   878     /// However, the underlying digraph must not be modified after this
   879     /// class have been constructed, since it copies and extends the graph.
   880     ///
   881     /// For example,
   882     /// \code
   883     ///   NetworkSimplex<ListDigraph> ns(graph);
   884     ///
   885     ///   // First run
   886     ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
   887     ///     .supplyMap(sup).run();
   888     ///
   889     ///   // Run again with modified cost map (reset() is not called,
   890     ///   // so only the cost map have to be set again)
   891     ///   cost[e] += 100;
   892     ///   ns.costMap(cost).run();
   893     ///
   894     ///   // Run again from scratch using reset()
   895     ///   // (the lower bounds will be set to zero on all arcs)
   896     ///   ns.reset();
   897     ///   ns.upperMap(capacity).costMap(cost)
   898     ///     .supplyMap(sup).run();
   899     /// \endcode
   900     ///
   901     /// \return <tt>(*this)</tt>
   902     NetworkSimplex& reset() {
   903       for (int i = 0; i != _node_num; ++i) {
   904         _supply[i] = 0;
   905       }
   906       for (int i = 0; i != _arc_num; ++i) {
   907         _lower[i] = 0;
   908         _upper[i] = INF;
   909         _cost[i] = 1;
   910       }
   911       _have_lower = false;
   912       _stype = GEQ;
   913       return *this;
   914     }
   915 
   916     /// @}
   917 
   918     /// \name Query Functions
   919     /// The results of the algorithm can be obtained using these
   920     /// functions.\n
   921     /// The \ref run() function must be called before using them.
   922 
   923     /// @{
   924 
   925     /// \brief Return the total cost of the found flow.
   926     ///
   927     /// This function returns the total cost of the found flow.
   928     /// Its complexity is O(e).
   929     ///
   930     /// \note The return type of the function can be specified as a
   931     /// template parameter. For example,
   932     /// \code
   933     ///   ns.totalCost<double>();
   934     /// \endcode
   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
   937     /// function.
   938     ///
   939     /// \pre \ref run() must be called before using this function.
   940     template <typename Number>
   941     Number totalCost() const {
   942       Number c = 0;
   943       for (ArcIt a(_graph); a != INVALID; ++a) {
   944         int i = _arc_id[a];
   945         c += Number(_flow[i]) * Number(_cost[i]);
   946       }
   947       return c;
   948     }
   949 
   950 #ifndef DOXYGEN
   951     Cost totalCost() const {
   952       return totalCost<Cost>();
   953     }
   954 #endif
   955 
   956     /// \brief Return the flow on the given arc.
   957     ///
   958     /// This function returns the flow on the given arc.
   959     ///
   960     /// \pre \ref run() must be called before using this function.
   961     Value flow(const Arc& a) const {
   962       return _flow[_arc_id[a]];
   963     }
   964 
   965     /// \brief Return the flow map (the primal solution).
   966     ///
   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.
   970     ///
   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]]);
   976       }
   977     }
   978 
   979     /// \brief Return the potential (dual value) of the given node.
   980     ///
   981     /// This function returns the potential (dual value) of the
   982     /// given node.
   983     ///
   984     /// \pre \ref run() must be called before using this function.
   985     Cost potential(const Node& n) const {
   986       return _pi[_node_id[n]];
   987     }
   988 
   989     /// \brief Return the potential map (the dual solution).
   990     ///
   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.
   995     ///
   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]]);
  1001       }
  1002     }
  1003 
  1004     /// @}
  1005 
  1006   private:
  1007 
  1008     // Initialize internal data structures
  1009     bool init() {
  1010       if (_node_num == 0) return false;
  1011 
  1012       // Check the sum of supply values
  1013       _sum_supply = 0;
  1014       for (int i = 0; i != _node_num; ++i) {
  1015         _sum_supply += _supply[i];
  1016       }
  1017       if ( !((_stype == GEQ && _sum_supply <= 0) ||
  1018              (_stype == LEQ && _sum_supply >= 0)) ) return false;
  1019 
  1020       // Remove non-zero lower bounds
  1021       if (_have_lower) {
  1022         for (int i = 0; i != _arc_num; ++i) {
  1023           Value c = _lower[i];
  1024           if (c >= 0) {
  1025             _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
  1026           } else {
  1027             _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
  1028           }
  1029           _supply[_source[i]] -= c;
  1030           _supply[_target[i]] += c;
  1031         }
  1032       } else {
  1033         for (int i = 0; i != _arc_num; ++i) {
  1034           _cap[i] = _upper[i];
  1035         }
  1036       }
  1037 
  1038       // Initialize artifical cost
  1039       Cost ART_COST;
  1040       if (std::numeric_limits<Cost>::is_exact) {
  1041         ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
  1042       } else {
  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];
  1046         }
  1047         ART_COST = (ART_COST + 1) * _node_num;
  1048       }
  1049 
  1050       // Initialize arc maps
  1051       for (int i = 0; i != _arc_num; ++i) {
  1052         _flow[i] = 0;
  1053         _state[i] = STATE_LOWER;
  1054       }
  1055       
  1056       // Set data for the artificial root node
  1057       _root = _node_num;
  1058       _parent[_root] = -1;
  1059       _pred[_root] = -1;
  1060       _thread[_root] = 0;
  1061       _rev_thread[0] = _root;
  1062       _succ_num[_root] = _node_num + 1;
  1063       _last_succ[_root] = _root - 1;
  1064       _supply[_root] = -_sum_supply;
  1065       _pi[_root] = 0;
  1066 
  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) {
  1073           _parent[u] = _root;
  1074           _pred[u] = e;
  1075           _thread[u] = u + 1;
  1076           _rev_thread[u + 1] = u;
  1077           _succ_num[u] = 1;
  1078           _last_succ[u] = u;
  1079           _cap[e] = INF;
  1080           _state[e] = STATE_TREE;
  1081           if (_supply[u] >= 0) {
  1082             _forward[u] = true;
  1083             _pi[u] = 0;
  1084             _source[e] = u;
  1085             _target[e] = _root;
  1086             _flow[e] = _supply[u];
  1087             _cost[e] = 0;
  1088           } else {
  1089             _forward[u] = false;
  1090             _pi[u] = ART_COST;
  1091             _source[e] = _root;
  1092             _target[e] = u;
  1093             _flow[e] = -_supply[u];
  1094             _cost[e] = ART_COST;
  1095           }
  1096         }
  1097       }
  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) {
  1103           _parent[u] = _root;
  1104           _thread[u] = u + 1;
  1105           _rev_thread[u + 1] = u;
  1106           _succ_num[u] = 1;
  1107           _last_succ[u] = u;
  1108           if (_supply[u] >= 0) {
  1109             _forward[u] = true;
  1110             _pi[u] = 0;
  1111             _pred[u] = e;
  1112             _source[e] = u;
  1113             _target[e] = _root;
  1114             _cap[e] = INF;
  1115             _flow[e] = _supply[u];
  1116             _cost[e] = 0;
  1117             _state[e] = STATE_TREE;
  1118           } else {
  1119             _forward[u] = false;
  1120             _pi[u] = ART_COST;
  1121             _pred[u] = f;
  1122             _source[f] = _root;
  1123             _target[f] = u;
  1124             _cap[f] = INF;
  1125             _flow[f] = -_supply[u];
  1126             _cost[f] = ART_COST;
  1127             _state[f] = STATE_TREE;
  1128             _source[e] = u;
  1129             _target[e] = _root;
  1130             _cap[e] = INF;
  1131             _flow[e] = 0;
  1132             _cost[e] = 0;
  1133             _state[e] = STATE_LOWER;
  1134             ++f;
  1135           }
  1136         }
  1137         _all_arc_num = f;
  1138       }
  1139       else {
  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) {
  1144           _parent[u] = _root;
  1145           _thread[u] = u + 1;
  1146           _rev_thread[u + 1] = u;
  1147           _succ_num[u] = 1;
  1148           _last_succ[u] = u;
  1149           if (_supply[u] <= 0) {
  1150             _forward[u] = false;
  1151             _pi[u] = 0;
  1152             _pred[u] = e;
  1153             _source[e] = _root;
  1154             _target[e] = u;
  1155             _cap[e] = INF;
  1156             _flow[e] = -_supply[u];
  1157             _cost[e] = 0;
  1158             _state[e] = STATE_TREE;
  1159           } else {
  1160             _forward[u] = true;
  1161             _pi[u] = -ART_COST;
  1162             _pred[u] = f;
  1163             _source[f] = u;
  1164             _target[f] = _root;
  1165             _cap[f] = INF;
  1166             _flow[f] = _supply[u];
  1167             _state[f] = STATE_TREE;
  1168             _cost[f] = ART_COST;
  1169             _source[e] = _root;
  1170             _target[e] = u;
  1171             _cap[e] = INF;
  1172             _flow[e] = 0;
  1173             _cost[e] = 0;
  1174             _state[e] = STATE_LOWER;
  1175             ++f;
  1176           }
  1177         }
  1178         _all_arc_num = f;
  1179       }
  1180 
  1181       return true;
  1182     }
  1183 
  1184     // Find the join node
  1185     void findJoinNode() {
  1186       int u = _source[in_arc];
  1187       int v = _target[in_arc];
  1188       while (u != v) {
  1189         if (_succ_num[u] < _succ_num[v]) {
  1190           u = _parent[u];
  1191         } else {
  1192           v = _parent[v];
  1193         }
  1194       }
  1195       join = u;
  1196     }
  1197 
  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
  1202       // of the cycle
  1203       if (_state[in_arc] == STATE_LOWER) {
  1204         first  = _source[in_arc];
  1205         second = _target[in_arc];
  1206       } else {
  1207         first  = _target[in_arc];
  1208         second = _source[in_arc];
  1209       }
  1210       delta = _cap[in_arc];
  1211       int result = 0;
  1212       Value d;
  1213       int e;
  1214 
  1215       // Search the cycle along the path form the first node to the root
  1216       for (int u = first; u != join; u = _parent[u]) {
  1217         e = _pred[u];
  1218         d = _forward[u] ?
  1219           _flow[e] : (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]);
  1220         if (d < delta) {
  1221           delta = d;
  1222           u_out = u;
  1223           result = 1;
  1224         }
  1225       }
  1226       // Search the cycle along the path form the second node to the root
  1227       for (int u = second; u != join; u = _parent[u]) {
  1228         e = _pred[u];
  1229         d = _forward[u] ? 
  1230           (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]) : _flow[e];
  1231         if (d <= delta) {
  1232           delta = d;
  1233           u_out = u;
  1234           result = 2;
  1235         }
  1236       }
  1237 
  1238       if (result == 1) {
  1239         u_in = first;
  1240         v_in = second;
  1241       } else {
  1242         u_in = second;
  1243         v_in = first;
  1244       }
  1245       return result != 0;
  1246     }
  1247 
  1248     // Change _flow and _state vectors
  1249     void changeFlow(bool change) {
  1250       // Augment along the cycle
  1251       if (delta > 0) {
  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;
  1256         }
  1257         for (int u = _target[in_arc]; u != join; u = _parent[u]) {
  1258           _flow[_pred[u]] += _forward[u] ? val : -val;
  1259         }
  1260       }
  1261       // Update the state of the entering and leaving arcs
  1262       if (change) {
  1263         _state[in_arc] = STATE_TREE;
  1264         _state[_pred[u_out]] =
  1265           (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
  1266       } else {
  1267         _state[in_arc] = -_state[in_arc];
  1268       }
  1269     }
  1270 
  1271     // Update the tree structure
  1272     void updateTreeStructure() {
  1273       int u, w;
  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];
  1278 
  1279       u = _last_succ[u_in];  // the last successor of u_in
  1280       right = _thread[u];    // the node after it
  1281 
  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]];
  1286       } else {
  1287         last = _thread[v_in];
  1288       }
  1289 
  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);
  1295       par_stem = 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);
  1301 
  1302         // Remove the subtree of stem from the thread list
  1303         w = _rev_thread[stem];
  1304         _thread[w] = right;
  1305         _rev_thread[right] = w;
  1306 
  1307         // Change the parent node and shift stem nodes
  1308         _parent[stem] = par_stem;
  1309         par_stem = stem;
  1310         stem = new_stem;
  1311 
  1312         // Update u and right
  1313         u = _last_succ[stem] == _last_succ[par_stem] ?
  1314           _rev_thread[par_stem] : _last_succ[stem];
  1315         right = _thread[u];
  1316       }
  1317       _parent[u_out] = par_stem;
  1318       _thread[u] = last;
  1319       _rev_thread[last] = u;
  1320       _last_succ[u_out] = u;
  1321 
  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;
  1328       }
  1329 
  1330       // Update _rev_thread using the new _thread values
  1331       for (int i = 0; i < int(_dirty_revs.size()); ++i) {
  1332         u = _dirty_revs[i];
  1333         _rev_thread[_thread[u]] = u;
  1334       }
  1335 
  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];
  1339       u = u_out;
  1340       while (u != u_in) {
  1341         w = _parent[u];
  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;
  1347         u = w;
  1348       }
  1349       _pred[u_in] = in_arc;
  1350       _forward[u_in] = (u_in == _source[in_arc]);
  1351       _succ_num[u_in] = old_succ_num;
  1352 
  1353       // Set limits for updating _last_succ form v_in and v_out
  1354       // towards the root
  1355       int up_limit_in = -1;
  1356       int up_limit_out = -1;
  1357       if (_last_succ[join] == v_in) {
  1358         up_limit_out = join;
  1359       } else {
  1360         up_limit_in = join;
  1361       }
  1362 
  1363       // Update _last_succ from v_in towards the root
  1364       for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
  1365            u = _parent[u]) {
  1366         _last_succ[u] = _last_succ[u_out];
  1367       }
  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;
  1371              u = _parent[u]) {
  1372           _last_succ[u] = old_rev_thread;
  1373         }
  1374       } else {
  1375         for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
  1376              u = _parent[u]) {
  1377           _last_succ[u] = _last_succ[u_out];
  1378         }
  1379       }
  1380 
  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;
  1384       }
  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;
  1388       }
  1389     }
  1390 
  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]) {
  1399         _pi[u] += sigma;
  1400       }
  1401     }
  1402 
  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>();
  1409         case BEST_ELIGIBLE:
  1410           return start<BestEligiblePivotRule>();
  1411         case BLOCK_SEARCH:
  1412           return start<BlockSearchPivotRule>();
  1413         case CANDIDATE_LIST:
  1414           return start<CandidateListPivotRule>();
  1415         case ALTERING_LIST:
  1416           return start<AlteringListPivotRule>();
  1417       }
  1418       return INFEASIBLE; // avoid warning
  1419     }
  1420 
  1421     template <typename PivotRuleImpl>
  1422     ProblemType start() {
  1423       PivotRuleImpl pivot(*this);
  1424 
  1425       // Execute the Network Simplex algorithm
  1426       while (pivot.findEnteringArc()) {
  1427         findJoinNode();
  1428         bool change = findLeavingArc();
  1429         if (delta >= MAX) return UNBOUNDED;
  1430         changeFlow(change);
  1431         if (change) {
  1432           updateTreeStructure();
  1433           updatePotential();
  1434         }
  1435       }
  1436       
  1437       // Check feasibility
  1438       for (int e = _search_arc_num; e != _all_arc_num; ++e) {
  1439         if (_flow[e] != 0) return INFEASIBLE;
  1440       }
  1441 
  1442       // Transform the solution and the supply map to the original form
  1443       if (_have_lower) {
  1444         for (int i = 0; i != _arc_num; ++i) {
  1445           Value c = _lower[i];
  1446           if (c != 0) {
  1447             _flow[i] += c;
  1448             _supply[_source[i]] += c;
  1449             _supply[_target[i]] -= c;
  1450           }
  1451         }
  1452       }
  1453       
  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];
  1461           }
  1462           if (max_pot > 0) {
  1463             for (int i = 0; i != _node_num; ++i)
  1464               _pi[i] -= max_pot;
  1465           }
  1466         } else {
  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];
  1470           }
  1471           if (min_pot < 0) {
  1472             for (int i = 0; i != _node_num; ++i)
  1473               _pi[i] -= min_pot;
  1474           }
  1475         }
  1476       }
  1477 
  1478       return OPTIMAL;
  1479     }
  1480 
  1481   }; //class NetworkSimplex
  1482 
  1483   ///@}
  1484 
  1485 } //namespace lemon
  1486 
  1487 #endif //LEMON_NETWORK_SIMPLEX_H