lemon/network_simplex.h
changeset 593 e8349c6f12ca
child 595 425cc8328c0e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/network_simplex.h	Tue Feb 24 09:46:02 2009 +0100
     1.3 @@ -0,0 +1,1191 @@
     1.4 +/* -*- mode: C++; indent-tabs-mode: nil; -*-
     1.5 + *
     1.6 + * This file is a part of LEMON, a generic C++ optimization library.
     1.7 + *
     1.8 + * Copyright (C) 2003-2009
     1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
    1.11 + *
    1.12 + * Permission to use, modify and distribute this software is granted
    1.13 + * provided that this copyright notice appears in all copies. For
    1.14 + * precise terms see the accompanying LICENSE file.
    1.15 + *
    1.16 + * This software is provided "AS IS" with no warranty of any kind,
    1.17 + * express or implied, and with no claim as to its suitability for any
    1.18 + * purpose.
    1.19 + *
    1.20 + */
    1.21 +
    1.22 +#ifndef LEMON_NETWORK_SIMPLEX_H
    1.23 +#define LEMON_NETWORK_SIMPLEX_H
    1.24 +
    1.25 +/// \ingroup min_cost_flow
    1.26 +///
    1.27 +/// \file
    1.28 +/// \brief Network simplex algorithm for finding a minimum cost flow.
    1.29 +
    1.30 +#include <vector>
    1.31 +#include <limits>
    1.32 +#include <algorithm>
    1.33 +
    1.34 +#include <lemon/math.h>
    1.35 +
    1.36 +namespace lemon {
    1.37 +
    1.38 +  /// \addtogroup min_cost_flow
    1.39 +  /// @{
    1.40 +
    1.41 +  /// \brief Implementation of the primal network simplex algorithm
    1.42 +  /// for finding a \ref min_cost_flow "minimum cost flow".
    1.43 +  ///
    1.44 +  /// \ref NetworkSimplex implements the primal network simplex algorithm
    1.45 +  /// for finding a \ref min_cost_flow "minimum cost flow".
    1.46 +  ///
    1.47 +  /// \tparam Digraph The digraph type the algorithm runs on.
    1.48 +  /// \tparam LowerMap The type of the lower bound map.
    1.49 +  /// \tparam CapacityMap The type of the capacity (upper bound) map.
    1.50 +  /// \tparam CostMap The type of the cost (length) map.
    1.51 +  /// \tparam SupplyMap The type of the supply map.
    1.52 +  ///
    1.53 +  /// \warning
    1.54 +  /// - Arc capacities and costs should be \e non-negative \e integers.
    1.55 +  /// - Supply values should be \e signed \e integers.
    1.56 +  /// - The value types of the maps should be convertible to each other.
    1.57 +  /// - \c CostMap::Value must be signed type.
    1.58 +  ///
    1.59 +  /// \note \ref NetworkSimplex provides five different pivot rule
    1.60 +  /// implementations that significantly affect the efficiency of the
    1.61 +  /// algorithm.
    1.62 +  /// By default "Block Search" pivot rule is used, which proved to be
    1.63 +  /// by far the most efficient according to our benchmark tests.
    1.64 +  /// However another pivot rule can be selected using \ref run()
    1.65 +  /// function with the proper parameter.
    1.66 +#ifdef DOXYGEN
    1.67 +  template < typename Digraph,
    1.68 +             typename LowerMap,
    1.69 +             typename CapacityMap,
    1.70 +             typename CostMap,
    1.71 +             typename SupplyMap >
    1.72 +
    1.73 +#else
    1.74 +  template < typename Digraph,
    1.75 +             typename LowerMap = typename Digraph::template ArcMap<int>,
    1.76 +             typename CapacityMap = typename Digraph::template ArcMap<int>,
    1.77 +             typename CostMap = typename Digraph::template ArcMap<int>,
    1.78 +             typename SupplyMap = typename Digraph::template NodeMap<int> >
    1.79 +#endif
    1.80 +  class NetworkSimplex
    1.81 +  {
    1.82 +    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
    1.83 +
    1.84 +    typedef typename CapacityMap::Value Capacity;
    1.85 +    typedef typename CostMap::Value Cost;
    1.86 +    typedef typename SupplyMap::Value Supply;
    1.87 +
    1.88 +    typedef std::vector<Arc> ArcVector;
    1.89 +    typedef std::vector<Node> NodeVector;
    1.90 +    typedef std::vector<int> IntVector;
    1.91 +    typedef std::vector<bool> BoolVector;
    1.92 +    typedef std::vector<Capacity> CapacityVector;
    1.93 +    typedef std::vector<Cost> CostVector;
    1.94 +    typedef std::vector<Supply> SupplyVector;
    1.95 +
    1.96 +  public:
    1.97 +
    1.98 +    /// The type of the flow map
    1.99 +    typedef typename Digraph::template ArcMap<Capacity> FlowMap;
   1.100 +    /// The type of the potential map
   1.101 +    typedef typename Digraph::template NodeMap<Cost> PotentialMap;
   1.102 +
   1.103 +  public:
   1.104 +
   1.105 +    /// Enum type for selecting the pivot rule used by \ref run()
   1.106 +    enum PivotRuleEnum {
   1.107 +      FIRST_ELIGIBLE_PIVOT,
   1.108 +      BEST_ELIGIBLE_PIVOT,
   1.109 +      BLOCK_SEARCH_PIVOT,
   1.110 +      CANDIDATE_LIST_PIVOT,
   1.111 +      ALTERING_LIST_PIVOT
   1.112 +    };
   1.113 +
   1.114 +  private:
   1.115 +
   1.116 +    // State constants for arcs
   1.117 +    enum ArcStateEnum {
   1.118 +      STATE_UPPER = -1,
   1.119 +      STATE_TREE  =  0,
   1.120 +      STATE_LOWER =  1
   1.121 +    };
   1.122 +
   1.123 +  private:
   1.124 +
   1.125 +    // References for the original data
   1.126 +    const Digraph &_orig_graph;
   1.127 +    const LowerMap *_orig_lower;
   1.128 +    const CapacityMap &_orig_cap;
   1.129 +    const CostMap &_orig_cost;
   1.130 +    const SupplyMap *_orig_supply;
   1.131 +    Node _orig_source;
   1.132 +    Node _orig_target;
   1.133 +    Capacity _orig_flow_value;
   1.134 +
   1.135 +    // Result maps
   1.136 +    FlowMap *_flow_result;
   1.137 +    PotentialMap *_potential_result;
   1.138 +    bool _local_flow;
   1.139 +    bool _local_potential;
   1.140 +
   1.141 +    // Data structures for storing the graph
   1.142 +    ArcVector _arc;
   1.143 +    NodeVector _node;
   1.144 +    IntNodeMap _node_id;
   1.145 +    IntVector _source;
   1.146 +    IntVector _target;
   1.147 +
   1.148 +    // The number of nodes and arcs in the original graph
   1.149 +    int _node_num;
   1.150 +    int _arc_num;
   1.151 +
   1.152 +    // Node and arc maps
   1.153 +    CapacityVector _cap;
   1.154 +    CostVector _cost;
   1.155 +    CostVector _supply;
   1.156 +    CapacityVector _flow;
   1.157 +    CostVector _pi;
   1.158 +
   1.159 +    // Node and arc maps for the spanning tree structure
   1.160 +    IntVector _depth;
   1.161 +    IntVector _parent;
   1.162 +    IntVector _pred;
   1.163 +    IntVector _thread;
   1.164 +    BoolVector _forward;
   1.165 +    IntVector _state;
   1.166 +
   1.167 +    // The root node
   1.168 +    int _root;
   1.169 +
   1.170 +    // The entering arc in the current pivot iteration
   1.171 +    int _in_arc;
   1.172 +
   1.173 +    // Temporary data used in the current pivot iteration
   1.174 +    int join, u_in, v_in, u_out, v_out;
   1.175 +    int right, first, second, last;
   1.176 +    int stem, par_stem, new_stem;
   1.177 +    Capacity delta;
   1.178 +
   1.179 +  private:
   1.180 +
   1.181 +    /// \brief Implementation of the "First Eligible" pivot rule for the
   1.182 +    /// \ref NetworkSimplex "network simplex" algorithm.
   1.183 +    ///
   1.184 +    /// This class implements the "First Eligible" pivot rule
   1.185 +    /// for the \ref NetworkSimplex "network simplex" algorithm.
   1.186 +    ///
   1.187 +    /// For more information see \ref NetworkSimplex::run().
   1.188 +    class FirstEligiblePivotRule
   1.189 +    {
   1.190 +    private:
   1.191 +
   1.192 +      // References to the NetworkSimplex class
   1.193 +      const ArcVector &_arc;
   1.194 +      const IntVector  &_source;
   1.195 +      const IntVector  &_target;
   1.196 +      const CostVector &_cost;
   1.197 +      const IntVector  &_state;
   1.198 +      const CostVector &_pi;
   1.199 +      int &_in_arc;
   1.200 +      int _arc_num;
   1.201 +
   1.202 +      // Pivot rule data
   1.203 +      int _next_arc;
   1.204 +
   1.205 +    public:
   1.206 +
   1.207 +      /// Constructor
   1.208 +      FirstEligiblePivotRule(NetworkSimplex &ns) :
   1.209 +        _arc(ns._arc), _source(ns._source), _target(ns._target),
   1.210 +        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
   1.211 +        _in_arc(ns._in_arc), _arc_num(ns._arc_num), _next_arc(0)
   1.212 +      {}
   1.213 +
   1.214 +      /// Find next entering arc
   1.215 +      bool findEnteringArc() {
   1.216 +        Cost c;
   1.217 +        for (int e = _next_arc; e < _arc_num; ++e) {
   1.218 +          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.219 +          if (c < 0) {
   1.220 +            _in_arc = e;
   1.221 +            _next_arc = e + 1;
   1.222 +            return true;
   1.223 +          }
   1.224 +        }
   1.225 +        for (int e = 0; e < _next_arc; ++e) {
   1.226 +          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.227 +          if (c < 0) {
   1.228 +            _in_arc = e;
   1.229 +            _next_arc = e + 1;
   1.230 +            return true;
   1.231 +          }
   1.232 +        }
   1.233 +        return false;
   1.234 +      }
   1.235 +
   1.236 +    }; //class FirstEligiblePivotRule
   1.237 +
   1.238 +
   1.239 +    /// \brief Implementation of the "Best Eligible" pivot rule for the
   1.240 +    /// \ref NetworkSimplex "network simplex" algorithm.
   1.241 +    ///
   1.242 +    /// This class implements the "Best Eligible" pivot rule
   1.243 +    /// for the \ref NetworkSimplex "network simplex" algorithm.
   1.244 +    ///
   1.245 +    /// For more information see \ref NetworkSimplex::run().
   1.246 +    class BestEligiblePivotRule
   1.247 +    {
   1.248 +    private:
   1.249 +
   1.250 +      // References to the NetworkSimplex class
   1.251 +      const ArcVector &_arc;
   1.252 +      const IntVector  &_source;
   1.253 +      const IntVector  &_target;
   1.254 +      const CostVector &_cost;
   1.255 +      const IntVector  &_state;
   1.256 +      const CostVector &_pi;
   1.257 +      int &_in_arc;
   1.258 +      int _arc_num;
   1.259 +
   1.260 +    public:
   1.261 +
   1.262 +      /// Constructor
   1.263 +      BestEligiblePivotRule(NetworkSimplex &ns) :
   1.264 +        _arc(ns._arc), _source(ns._source), _target(ns._target),
   1.265 +        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
   1.266 +        _in_arc(ns._in_arc), _arc_num(ns._arc_num)
   1.267 +      {}
   1.268 +
   1.269 +      /// Find next entering arc
   1.270 +      bool findEnteringArc() {
   1.271 +        Cost c, min = 0;
   1.272 +        for (int e = 0; e < _arc_num; ++e) {
   1.273 +          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.274 +          if (c < min) {
   1.275 +            min = c;
   1.276 +            _in_arc = e;
   1.277 +          }
   1.278 +        }
   1.279 +        return min < 0;
   1.280 +      }
   1.281 +
   1.282 +    }; //class BestEligiblePivotRule
   1.283 +
   1.284 +
   1.285 +    /// \brief Implementation of the "Block Search" pivot rule for the
   1.286 +    /// \ref NetworkSimplex "network simplex" algorithm.
   1.287 +    ///
   1.288 +    /// This class implements the "Block Search" pivot rule
   1.289 +    /// for the \ref NetworkSimplex "network simplex" algorithm.
   1.290 +    ///
   1.291 +    /// For more information see \ref NetworkSimplex::run().
   1.292 +    class BlockSearchPivotRule
   1.293 +    {
   1.294 +    private:
   1.295 +
   1.296 +      // References to the NetworkSimplex class
   1.297 +      const ArcVector &_arc;
   1.298 +      const IntVector  &_source;
   1.299 +      const IntVector  &_target;
   1.300 +      const CostVector &_cost;
   1.301 +      const IntVector  &_state;
   1.302 +      const CostVector &_pi;
   1.303 +      int &_in_arc;
   1.304 +      int _arc_num;
   1.305 +
   1.306 +      // Pivot rule data
   1.307 +      int _block_size;
   1.308 +      int _next_arc;
   1.309 +
   1.310 +    public:
   1.311 +
   1.312 +      /// Constructor
   1.313 +      BlockSearchPivotRule(NetworkSimplex &ns) :
   1.314 +        _arc(ns._arc), _source(ns._source), _target(ns._target),
   1.315 +        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
   1.316 +        _in_arc(ns._in_arc), _arc_num(ns._arc_num), _next_arc(0)
   1.317 +      {
   1.318 +        // The main parameters of the pivot rule
   1.319 +        const double BLOCK_SIZE_FACTOR = 2.0;
   1.320 +        const int MIN_BLOCK_SIZE = 10;
   1.321 +
   1.322 +        _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
   1.323 +                                MIN_BLOCK_SIZE );
   1.324 +      }
   1.325 +
   1.326 +      /// Find next entering arc
   1.327 +      bool findEnteringArc() {
   1.328 +        Cost c, min = 0;
   1.329 +        int cnt = _block_size;
   1.330 +        int e, min_arc = _next_arc;
   1.331 +        for (e = _next_arc; e < _arc_num; ++e) {
   1.332 +          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.333 +          if (c < min) {
   1.334 +            min = c;
   1.335 +            min_arc = e;
   1.336 +          }
   1.337 +          if (--cnt == 0) {
   1.338 +            if (min < 0) break;
   1.339 +            cnt = _block_size;
   1.340 +          }
   1.341 +        }
   1.342 +        if (min == 0 || cnt > 0) {
   1.343 +          for (e = 0; e < _next_arc; ++e) {
   1.344 +            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.345 +            if (c < min) {
   1.346 +              min = c;
   1.347 +              min_arc = e;
   1.348 +            }
   1.349 +            if (--cnt == 0) {
   1.350 +              if (min < 0) break;
   1.351 +              cnt = _block_size;
   1.352 +            }
   1.353 +          }
   1.354 +        }
   1.355 +        if (min >= 0) return false;
   1.356 +        _in_arc = min_arc;
   1.357 +        _next_arc = e;
   1.358 +        return true;
   1.359 +      }
   1.360 +
   1.361 +    }; //class BlockSearchPivotRule
   1.362 +
   1.363 +
   1.364 +    /// \brief Implementation of the "Candidate List" pivot rule for the
   1.365 +    /// \ref NetworkSimplex "network simplex" algorithm.
   1.366 +    ///
   1.367 +    /// This class implements the "Candidate List" pivot rule
   1.368 +    /// for the \ref NetworkSimplex "network simplex" algorithm.
   1.369 +    ///
   1.370 +    /// For more information see \ref NetworkSimplex::run().
   1.371 +    class CandidateListPivotRule
   1.372 +    {
   1.373 +    private:
   1.374 +
   1.375 +      // References to the NetworkSimplex class
   1.376 +      const ArcVector &_arc;
   1.377 +      const IntVector  &_source;
   1.378 +      const IntVector  &_target;
   1.379 +      const CostVector &_cost;
   1.380 +      const IntVector  &_state;
   1.381 +      const CostVector &_pi;
   1.382 +      int &_in_arc;
   1.383 +      int _arc_num;
   1.384 +
   1.385 +      // Pivot rule data
   1.386 +      IntVector _candidates;
   1.387 +      int _list_length, _minor_limit;
   1.388 +      int _curr_length, _minor_count;
   1.389 +      int _next_arc;
   1.390 +
   1.391 +    public:
   1.392 +
   1.393 +      /// Constructor
   1.394 +      CandidateListPivotRule(NetworkSimplex &ns) :
   1.395 +        _arc(ns._arc), _source(ns._source), _target(ns._target),
   1.396 +        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
   1.397 +        _in_arc(ns._in_arc), _arc_num(ns._arc_num), _next_arc(0)
   1.398 +      {
   1.399 +        // The main parameters of the pivot rule
   1.400 +        const double LIST_LENGTH_FACTOR = 1.0;
   1.401 +        const int MIN_LIST_LENGTH = 10;
   1.402 +        const double MINOR_LIMIT_FACTOR = 0.1;
   1.403 +        const int MIN_MINOR_LIMIT = 3;
   1.404 +
   1.405 +        _list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_arc_num)),
   1.406 +                                 MIN_LIST_LENGTH );
   1.407 +        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
   1.408 +                                 MIN_MINOR_LIMIT );
   1.409 +        _curr_length = _minor_count = 0;
   1.410 +        _candidates.resize(_list_length);
   1.411 +      }
   1.412 +
   1.413 +      /// Find next entering arc
   1.414 +      bool findEnteringArc() {
   1.415 +        Cost min, c;
   1.416 +        int e, min_arc = _next_arc;
   1.417 +        if (_curr_length > 0 && _minor_count < _minor_limit) {
   1.418 +          // Minor iteration: select the best eligible arc from the
   1.419 +          // current candidate list
   1.420 +          ++_minor_count;
   1.421 +          min = 0;
   1.422 +          for (int i = 0; i < _curr_length; ++i) {
   1.423 +            e = _candidates[i];
   1.424 +            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.425 +            if (c < min) {
   1.426 +              min = c;
   1.427 +              min_arc = e;
   1.428 +            }
   1.429 +            if (c >= 0) {
   1.430 +              _candidates[i--] = _candidates[--_curr_length];
   1.431 +            }
   1.432 +          }
   1.433 +          if (min < 0) {
   1.434 +            _in_arc = min_arc;
   1.435 +            return true;
   1.436 +          }
   1.437 +        }
   1.438 +
   1.439 +        // Major iteration: build a new candidate list
   1.440 +        min = 0;
   1.441 +        _curr_length = 0;
   1.442 +        for (e = _next_arc; e < _arc_num; ++e) {
   1.443 +          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.444 +          if (c < 0) {
   1.445 +            _candidates[_curr_length++] = e;
   1.446 +            if (c < min) {
   1.447 +              min = c;
   1.448 +              min_arc = e;
   1.449 +            }
   1.450 +            if (_curr_length == _list_length) break;
   1.451 +          }
   1.452 +        }
   1.453 +        if (_curr_length < _list_length) {
   1.454 +          for (e = 0; e < _next_arc; ++e) {
   1.455 +            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.456 +            if (c < 0) {
   1.457 +              _candidates[_curr_length++] = e;
   1.458 +              if (c < min) {
   1.459 +                min = c;
   1.460 +                min_arc = e;
   1.461 +              }
   1.462 +              if (_curr_length == _list_length) break;
   1.463 +            }
   1.464 +          }
   1.465 +        }
   1.466 +        if (_curr_length == 0) return false;
   1.467 +        _minor_count = 1;
   1.468 +        _in_arc = min_arc;
   1.469 +        _next_arc = e;
   1.470 +        return true;
   1.471 +      }
   1.472 +
   1.473 +    }; //class CandidateListPivotRule
   1.474 +
   1.475 +
   1.476 +    /// \brief Implementation of the "Altering Candidate List" pivot rule
   1.477 +    /// for the \ref NetworkSimplex "network simplex" algorithm.
   1.478 +    ///
   1.479 +    /// This class implements the "Altering Candidate List" pivot rule
   1.480 +    /// for the \ref NetworkSimplex "network simplex" algorithm.
   1.481 +    ///
   1.482 +    /// For more information see \ref NetworkSimplex::run().
   1.483 +    class AlteringListPivotRule
   1.484 +    {
   1.485 +    private:
   1.486 +
   1.487 +      // References to the NetworkSimplex class
   1.488 +      const ArcVector &_arc;
   1.489 +      const IntVector  &_source;
   1.490 +      const IntVector  &_target;
   1.491 +      const CostVector &_cost;
   1.492 +      const IntVector  &_state;
   1.493 +      const CostVector &_pi;
   1.494 +      int &_in_arc;
   1.495 +      int _arc_num;
   1.496 +
   1.497 +      // Pivot rule data
   1.498 +      int _block_size, _head_length, _curr_length;
   1.499 +      int _next_arc;
   1.500 +      IntVector _candidates;
   1.501 +      CostVector _cand_cost;
   1.502 +
   1.503 +      // Functor class to compare arcs during sort of the candidate list
   1.504 +      class SortFunc
   1.505 +      {
   1.506 +      private:
   1.507 +        const CostVector &_map;
   1.508 +      public:
   1.509 +        SortFunc(const CostVector &map) : _map(map) {}
   1.510 +        bool operator()(int left, int right) {
   1.511 +          return _map[left] > _map[right];
   1.512 +        }
   1.513 +      };
   1.514 +
   1.515 +      SortFunc _sort_func;
   1.516 +
   1.517 +    public:
   1.518 +
   1.519 +      /// Constructor
   1.520 +      AlteringListPivotRule(NetworkSimplex &ns) :
   1.521 +        _arc(ns._arc), _source(ns._source), _target(ns._target),
   1.522 +        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
   1.523 +        _in_arc(ns._in_arc), _arc_num(ns._arc_num),
   1.524 +        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
   1.525 +      {
   1.526 +        // The main parameters of the pivot rule
   1.527 +        const double BLOCK_SIZE_FACTOR = 1.5;
   1.528 +        const int MIN_BLOCK_SIZE = 10;
   1.529 +        const double HEAD_LENGTH_FACTOR = 0.1;
   1.530 +        const int MIN_HEAD_LENGTH = 3;
   1.531 +
   1.532 +        _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
   1.533 +                                MIN_BLOCK_SIZE );
   1.534 +        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
   1.535 +                                 MIN_HEAD_LENGTH );
   1.536 +        _candidates.resize(_head_length + _block_size);
   1.537 +        _curr_length = 0;
   1.538 +      }
   1.539 +
   1.540 +      /// Find next entering arc
   1.541 +      bool findEnteringArc() {
   1.542 +        // Check the current candidate list
   1.543 +        int e;
   1.544 +        for (int i = 0; i < _curr_length; ++i) {
   1.545 +          e = _candidates[i];
   1.546 +          _cand_cost[e] = _state[e] *
   1.547 +            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.548 +          if (_cand_cost[e] >= 0) {
   1.549 +            _candidates[i--] = _candidates[--_curr_length];
   1.550 +          }
   1.551 +        }
   1.552 +
   1.553 +        // Extend the list
   1.554 +        int cnt = _block_size;
   1.555 +        int last_edge = 0;
   1.556 +        int limit = _head_length;
   1.557 +
   1.558 +        for (int e = _next_arc; e < _arc_num; ++e) {
   1.559 +          _cand_cost[e] = _state[e] *
   1.560 +            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.561 +          if (_cand_cost[e] < 0) {
   1.562 +            _candidates[_curr_length++] = e;
   1.563 +            last_edge = e;
   1.564 +          }
   1.565 +          if (--cnt == 0) {
   1.566 +            if (_curr_length > limit) break;
   1.567 +            limit = 0;
   1.568 +            cnt = _block_size;
   1.569 +          }
   1.570 +        }
   1.571 +        if (_curr_length <= limit) {
   1.572 +          for (int e = 0; e < _next_arc; ++e) {
   1.573 +            _cand_cost[e] = _state[e] *
   1.574 +              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
   1.575 +            if (_cand_cost[e] < 0) {
   1.576 +              _candidates[_curr_length++] = e;
   1.577 +              last_edge = e;
   1.578 +            }
   1.579 +            if (--cnt == 0) {
   1.580 +              if (_curr_length > limit) break;
   1.581 +              limit = 0;
   1.582 +              cnt = _block_size;
   1.583 +            }
   1.584 +          }
   1.585 +        }
   1.586 +        if (_curr_length == 0) return false;
   1.587 +        _next_arc = last_edge + 1;
   1.588 +
   1.589 +        // Make heap of the candidate list (approximating a partial sort)
   1.590 +        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
   1.591 +                   _sort_func );
   1.592 +
   1.593 +        // Pop the first element of the heap
   1.594 +        _in_arc = _candidates[0];
   1.595 +        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
   1.596 +                  _sort_func );
   1.597 +        _curr_length = std::min(_head_length, _curr_length - 1);
   1.598 +        return true;
   1.599 +      }
   1.600 +
   1.601 +    }; //class AlteringListPivotRule
   1.602 +
   1.603 +  public:
   1.604 +
   1.605 +    /// \brief General constructor (with lower bounds).
   1.606 +    ///
   1.607 +    /// General constructor (with lower bounds).
   1.608 +    ///
   1.609 +    /// \param digraph The digraph the algorithm runs on.
   1.610 +    /// \param lower The lower bounds of the arcs.
   1.611 +    /// \param capacity The capacities (upper bounds) of the arcs.
   1.612 +    /// \param cost The cost (length) values of the arcs.
   1.613 +    /// \param supply The supply values of the nodes (signed).
   1.614 +    NetworkSimplex( const Digraph &digraph,
   1.615 +                    const LowerMap &lower,
   1.616 +                    const CapacityMap &capacity,
   1.617 +                    const CostMap &cost,
   1.618 +                    const SupplyMap &supply ) :
   1.619 +      _orig_graph(digraph), _orig_lower(&lower), _orig_cap(capacity),
   1.620 +      _orig_cost(cost), _orig_supply(&supply),
   1.621 +      _flow_result(NULL), _potential_result(NULL),
   1.622 +      _local_flow(false), _local_potential(false),
   1.623 +      _node_id(digraph)
   1.624 +    {}
   1.625 +
   1.626 +    /// \brief General constructor (without lower bounds).
   1.627 +    ///
   1.628 +    /// General constructor (without lower bounds).
   1.629 +    ///
   1.630 +    /// \param digraph The digraph the algorithm runs on.
   1.631 +    /// \param capacity The capacities (upper bounds) of the arcs.
   1.632 +    /// \param cost The cost (length) values of the arcs.
   1.633 +    /// \param supply The supply values of the nodes (signed).
   1.634 +    NetworkSimplex( const Digraph &digraph,
   1.635 +                    const CapacityMap &capacity,
   1.636 +                    const CostMap &cost,
   1.637 +                    const SupplyMap &supply ) :
   1.638 +      _orig_graph(digraph), _orig_lower(NULL), _orig_cap(capacity),
   1.639 +      _orig_cost(cost), _orig_supply(&supply),
   1.640 +      _flow_result(NULL), _potential_result(NULL),
   1.641 +      _local_flow(false), _local_potential(false),
   1.642 +      _node_id(digraph)
   1.643 +    {}
   1.644 +
   1.645 +    /// \brief Simple constructor (with lower bounds).
   1.646 +    ///
   1.647 +    /// Simple constructor (with lower bounds).
   1.648 +    ///
   1.649 +    /// \param digraph The digraph the algorithm runs on.
   1.650 +    /// \param lower The lower bounds of the arcs.
   1.651 +    /// \param capacity The capacities (upper bounds) of the arcs.
   1.652 +    /// \param cost The cost (length) values of the arcs.
   1.653 +    /// \param s The source node.
   1.654 +    /// \param t The target node.
   1.655 +    /// \param flow_value The required amount of flow from node \c s
   1.656 +    /// to node \c t (i.e. the supply of \c s and the demand of \c t).
   1.657 +    NetworkSimplex( const Digraph &digraph,
   1.658 +                    const LowerMap &lower,
   1.659 +                    const CapacityMap &capacity,
   1.660 +                    const CostMap &cost,
   1.661 +                    Node s, Node t,
   1.662 +                    Capacity flow_value ) :
   1.663 +      _orig_graph(digraph), _orig_lower(&lower), _orig_cap(capacity),
   1.664 +      _orig_cost(cost), _orig_supply(NULL),
   1.665 +      _orig_source(s), _orig_target(t), _orig_flow_value(flow_value),
   1.666 +      _flow_result(NULL), _potential_result(NULL),
   1.667 +      _local_flow(false), _local_potential(false),
   1.668 +      _node_id(digraph)
   1.669 +    {}
   1.670 +
   1.671 +    /// \brief Simple constructor (without lower bounds).
   1.672 +    ///
   1.673 +    /// Simple constructor (without lower bounds).
   1.674 +    ///
   1.675 +    /// \param digraph The digraph the algorithm runs on.
   1.676 +    /// \param capacity The capacities (upper bounds) of the arcs.
   1.677 +    /// \param cost The cost (length) values of the arcs.
   1.678 +    /// \param s The source node.
   1.679 +    /// \param t The target node.
   1.680 +    /// \param flow_value The required amount of flow from node \c s
   1.681 +    /// to node \c t (i.e. the supply of \c s and the demand of \c t).
   1.682 +    NetworkSimplex( const Digraph &digraph,
   1.683 +                    const CapacityMap &capacity,
   1.684 +                    const CostMap &cost,
   1.685 +                    Node s, Node t,
   1.686 +                    Capacity flow_value ) :
   1.687 +      _orig_graph(digraph), _orig_lower(NULL), _orig_cap(capacity),
   1.688 +      _orig_cost(cost), _orig_supply(NULL),
   1.689 +      _orig_source(s), _orig_target(t), _orig_flow_value(flow_value),
   1.690 +      _flow_result(NULL), _potential_result(NULL),
   1.691 +      _local_flow(false), _local_potential(false),
   1.692 +      _node_id(digraph)
   1.693 +    {}
   1.694 +
   1.695 +    /// Destructor.
   1.696 +    ~NetworkSimplex() {
   1.697 +      if (_local_flow) delete _flow_result;
   1.698 +      if (_local_potential) delete _potential_result;
   1.699 +    }
   1.700 +
   1.701 +    /// \brief Set the flow map.
   1.702 +    ///
   1.703 +    /// This function sets the flow map.
   1.704 +    ///
   1.705 +    /// \return <tt>(*this)</tt>
   1.706 +    NetworkSimplex& flowMap(FlowMap &map) {
   1.707 +      if (_local_flow) {
   1.708 +        delete _flow_result;
   1.709 +        _local_flow = false;
   1.710 +      }
   1.711 +      _flow_result = &map;
   1.712 +      return *this;
   1.713 +    }
   1.714 +
   1.715 +    /// \brief Set the potential map.
   1.716 +    ///
   1.717 +    /// This function sets the potential map.
   1.718 +    ///
   1.719 +    /// \return <tt>(*this)</tt>
   1.720 +    NetworkSimplex& potentialMap(PotentialMap &map) {
   1.721 +      if (_local_potential) {
   1.722 +        delete _potential_result;
   1.723 +        _local_potential = false;
   1.724 +      }
   1.725 +      _potential_result = &map;
   1.726 +      return *this;
   1.727 +    }
   1.728 +
   1.729 +    /// \name Execution control
   1.730 +    /// The algorithm can be executed using the
   1.731 +    /// \ref lemon::NetworkSimplex::run() "run()" function.
   1.732 +    /// @{
   1.733 +
   1.734 +    /// \brief Run the algorithm.
   1.735 +    ///
   1.736 +    /// This function runs the algorithm.
   1.737 +    ///
   1.738 +    /// \param pivot_rule The pivot rule that is used during the
   1.739 +    /// algorithm.
   1.740 +    ///
   1.741 +    /// The available pivot rules:
   1.742 +    ///
   1.743 +    /// - FIRST_ELIGIBLE_PIVOT The next eligible arc is selected in
   1.744 +    /// a wraparound fashion in every iteration
   1.745 +    /// (\ref FirstEligiblePivotRule).
   1.746 +    ///
   1.747 +    /// - BEST_ELIGIBLE_PIVOT The best eligible arc is selected in
   1.748 +    /// every iteration (\ref BestEligiblePivotRule).
   1.749 +    ///
   1.750 +    /// - BLOCK_SEARCH_PIVOT A specified number of arcs are examined in
   1.751 +    /// every iteration in a wraparound fashion and the best eligible
   1.752 +    /// arc is selected from this block (\ref BlockSearchPivotRule).
   1.753 +    ///
   1.754 +    /// - CANDIDATE_LIST_PIVOT In a major iteration a candidate list is
   1.755 +    /// built from eligible arcs in a wraparound fashion and in the
   1.756 +    /// following minor iterations the best eligible arc is selected
   1.757 +    /// from this list (\ref CandidateListPivotRule).
   1.758 +    ///
   1.759 +    /// - ALTERING_LIST_PIVOT It is a modified version of the
   1.760 +    /// "Candidate List" pivot rule. It keeps only the several best
   1.761 +    /// eligible arcs from the former candidate list and extends this
   1.762 +    /// list in every iteration (\ref AlteringListPivotRule).
   1.763 +    ///
   1.764 +    /// According to our comprehensive benchmark tests the "Block Search"
   1.765 +    /// pivot rule proved to be the fastest and the most robust on
   1.766 +    /// various test inputs. Thus it is the default option.
   1.767 +    ///
   1.768 +    /// \return \c true if a feasible flow can be found.
   1.769 +    bool run(PivotRuleEnum pivot_rule = BLOCK_SEARCH_PIVOT) {
   1.770 +      return init() && start(pivot_rule);
   1.771 +    }
   1.772 +
   1.773 +    /// @}
   1.774 +
   1.775 +    /// \name Query Functions
   1.776 +    /// The results of the algorithm can be obtained using these
   1.777 +    /// functions.\n
   1.778 +    /// \ref lemon::NetworkSimplex::run() "run()" must be called before
   1.779 +    /// using them.
   1.780 +    /// @{
   1.781 +
   1.782 +    /// \brief Return a const reference to the flow map.
   1.783 +    ///
   1.784 +    /// This function returns a const reference to an arc map storing
   1.785 +    /// the found flow.
   1.786 +    ///
   1.787 +    /// \pre \ref run() must be called before using this function.
   1.788 +    const FlowMap& flowMap() const {
   1.789 +      return *_flow_result;
   1.790 +    }
   1.791 +
   1.792 +    /// \brief Return a const reference to the potential map
   1.793 +    /// (the dual solution).
   1.794 +    ///
   1.795 +    /// This function returns a const reference to a node map storing
   1.796 +    /// the found potentials (the dual solution).
   1.797 +    ///
   1.798 +    /// \pre \ref run() must be called before using this function.
   1.799 +    const PotentialMap& potentialMap() const {
   1.800 +      return *_potential_result;
   1.801 +    }
   1.802 +
   1.803 +    /// \brief Return the flow on the given arc.
   1.804 +    ///
   1.805 +    /// This function returns the flow on the given arc.
   1.806 +    ///
   1.807 +    /// \pre \ref run() must be called before using this function.
   1.808 +    Capacity flow(const Arc& arc) const {
   1.809 +      return (*_flow_result)[arc];
   1.810 +    }
   1.811 +
   1.812 +    /// \brief Return the potential of the given node.
   1.813 +    ///
   1.814 +    /// This function returns the potential of the given node.
   1.815 +    ///
   1.816 +    /// \pre \ref run() must be called before using this function.
   1.817 +    Cost potential(const Node& node) const {
   1.818 +      return (*_potential_result)[node];
   1.819 +    }
   1.820 +
   1.821 +    /// \brief Return the total cost of the found flow.
   1.822 +    ///
   1.823 +    /// This function returns the total cost of the found flow.
   1.824 +    /// The complexity of the function is \f$ O(e) \f$.
   1.825 +    ///
   1.826 +    /// \pre \ref run() must be called before using this function.
   1.827 +    Cost totalCost() const {
   1.828 +      Cost c = 0;
   1.829 +      for (ArcIt e(_orig_graph); e != INVALID; ++e)
   1.830 +        c += (*_flow_result)[e] * _orig_cost[e];
   1.831 +      return c;
   1.832 +    }
   1.833 +
   1.834 +    /// @}
   1.835 +
   1.836 +  private:
   1.837 +
   1.838 +    // Initialize internal data structures
   1.839 +    bool init() {
   1.840 +      // Initialize result maps
   1.841 +      if (!_flow_result) {
   1.842 +        _flow_result = new FlowMap(_orig_graph);
   1.843 +        _local_flow = true;
   1.844 +      }
   1.845 +      if (!_potential_result) {
   1.846 +        _potential_result = new PotentialMap(_orig_graph);
   1.847 +        _local_potential = true;
   1.848 +      }
   1.849 +
   1.850 +      // Initialize vectors
   1.851 +      _node_num = countNodes(_orig_graph);
   1.852 +      _arc_num = countArcs(_orig_graph);
   1.853 +      int all_node_num = _node_num + 1;
   1.854 +      int all_edge_num = _arc_num + _node_num;
   1.855 +
   1.856 +      _arc.resize(_arc_num);
   1.857 +      _node.reserve(_node_num);
   1.858 +      _source.resize(all_edge_num);
   1.859 +      _target.resize(all_edge_num);
   1.860 +
   1.861 +      _cap.resize(all_edge_num);
   1.862 +      _cost.resize(all_edge_num);
   1.863 +      _supply.resize(all_node_num);
   1.864 +      _flow.resize(all_edge_num, 0);
   1.865 +      _pi.resize(all_node_num, 0);
   1.866 +
   1.867 +      _depth.resize(all_node_num);
   1.868 +      _parent.resize(all_node_num);
   1.869 +      _pred.resize(all_node_num);
   1.870 +      _thread.resize(all_node_num);
   1.871 +      _forward.resize(all_node_num);
   1.872 +      _state.resize(all_edge_num, STATE_LOWER);
   1.873 +
   1.874 +      // Initialize node related data
   1.875 +      bool valid_supply = true;
   1.876 +      if (_orig_supply) {
   1.877 +        Supply sum = 0;
   1.878 +        int i = 0;
   1.879 +        for (NodeIt n(_orig_graph); n != INVALID; ++n, ++i) {
   1.880 +          _node.push_back(n);
   1.881 +          _node_id[n] = i;
   1.882 +          _supply[i] = (*_orig_supply)[n];
   1.883 +          sum += _supply[i];
   1.884 +        }
   1.885 +        valid_supply = (sum == 0);
   1.886 +      } else {
   1.887 +        int i = 0;
   1.888 +        for (NodeIt n(_orig_graph); n != INVALID; ++n, ++i) {
   1.889 +          _node.push_back(n);
   1.890 +          _node_id[n] = i;
   1.891 +          _supply[i] = 0;
   1.892 +        }
   1.893 +        _supply[_node_id[_orig_source]] =  _orig_flow_value;
   1.894 +        _supply[_node_id[_orig_target]] = -_orig_flow_value;
   1.895 +      }
   1.896 +      if (!valid_supply) return false;
   1.897 +
   1.898 +      // Set data for the artificial root node
   1.899 +      _root = _node_num;
   1.900 +      _depth[_root] = 0;
   1.901 +      _parent[_root] = -1;
   1.902 +      _pred[_root] = -1;
   1.903 +      _thread[_root] = 0;
   1.904 +      _supply[_root] = 0;
   1.905 +      _pi[_root] = 0;
   1.906 +
   1.907 +      // Store the arcs in a mixed order
   1.908 +      int k = std::max(int(sqrt(_arc_num)), 10);
   1.909 +      int i = 0;
   1.910 +      for (ArcIt e(_orig_graph); e != INVALID; ++e) {
   1.911 +        _arc[i] = e;
   1.912 +        if ((i += k) >= _arc_num) i = (i % k) + 1;
   1.913 +      }
   1.914 +
   1.915 +      // Initialize arc maps
   1.916 +      for (int i = 0; i != _arc_num; ++i) {
   1.917 +        Arc e = _arc[i];
   1.918 +        _source[i] = _node_id[_orig_graph.source(e)];
   1.919 +        _target[i] = _node_id[_orig_graph.target(e)];
   1.920 +        _cost[i] = _orig_cost[e];
   1.921 +        _cap[i] = _orig_cap[e];
   1.922 +      }
   1.923 +
   1.924 +      // Remove non-zero lower bounds
   1.925 +      if (_orig_lower) {
   1.926 +        for (int i = 0; i != _arc_num; ++i) {
   1.927 +          Capacity c = (*_orig_lower)[_arc[i]];
   1.928 +          if (c != 0) {
   1.929 +            _cap[i] -= c;
   1.930 +            _supply[_source[i]] -= c;
   1.931 +            _supply[_target[i]] += c;
   1.932 +          }
   1.933 +        }
   1.934 +      }
   1.935 +
   1.936 +      // Add artificial arcs and initialize the spanning tree data structure
   1.937 +      Cost max_cost = std::numeric_limits<Cost>::max() / 4;
   1.938 +      Capacity max_cap = std::numeric_limits<Capacity>::max();
   1.939 +      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
   1.940 +        _thread[u] = u + 1;
   1.941 +        _depth[u] = 1;
   1.942 +        _parent[u] = _root;
   1.943 +        _pred[u] = e;
   1.944 +        if (_supply[u] >= 0) {
   1.945 +          _flow[e] = _supply[u];
   1.946 +          _forward[u] = true;
   1.947 +          _pi[u] = -max_cost;
   1.948 +        } else {
   1.949 +          _flow[e] = -_supply[u];
   1.950 +          _forward[u] = false;
   1.951 +          _pi[u] = max_cost;
   1.952 +        }
   1.953 +        _cost[e] = max_cost;
   1.954 +        _cap[e] = max_cap;
   1.955 +        _state[e] = STATE_TREE;
   1.956 +      }
   1.957 +
   1.958 +      return true;
   1.959 +    }
   1.960 +
   1.961 +    // Find the join node
   1.962 +    void findJoinNode() {
   1.963 +      int u = _source[_in_arc];
   1.964 +      int v = _target[_in_arc];
   1.965 +      while (_depth[u] > _depth[v]) u = _parent[u];
   1.966 +      while (_depth[v] > _depth[u]) v = _parent[v];
   1.967 +      while (u != v) {
   1.968 +        u = _parent[u];
   1.969 +        v = _parent[v];
   1.970 +      }
   1.971 +      join = u;
   1.972 +    }
   1.973 +
   1.974 +    // Find the leaving arc of the cycle and returns true if the
   1.975 +    // leaving arc is not the same as the entering arc
   1.976 +    bool findLeavingArc() {
   1.977 +      // Initialize first and second nodes according to the direction
   1.978 +      // of the cycle
   1.979 +      if (_state[_in_arc] == STATE_LOWER) {
   1.980 +        first  = _source[_in_arc];
   1.981 +        second = _target[_in_arc];
   1.982 +      } else {
   1.983 +        first  = _target[_in_arc];
   1.984 +        second = _source[_in_arc];
   1.985 +      }
   1.986 +      delta = _cap[_in_arc];
   1.987 +      int result = 0;
   1.988 +      Capacity d;
   1.989 +      int e;
   1.990 +
   1.991 +      // Search the cycle along the path form the first node to the root
   1.992 +      for (int u = first; u != join; u = _parent[u]) {
   1.993 +        e = _pred[u];
   1.994 +        d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
   1.995 +        if (d < delta) {
   1.996 +          delta = d;
   1.997 +          u_out = u;
   1.998 +          result = 1;
   1.999 +        }
  1.1000 +      }
  1.1001 +      // Search the cycle along the path form the second node to the root
  1.1002 +      for (int u = second; u != join; u = _parent[u]) {
  1.1003 +        e = _pred[u];
  1.1004 +        d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
  1.1005 +        if (d <= delta) {
  1.1006 +          delta = d;
  1.1007 +          u_out = u;
  1.1008 +          result = 2;
  1.1009 +        }
  1.1010 +      }
  1.1011 +
  1.1012 +      if (result == 1) {
  1.1013 +        u_in = first;
  1.1014 +        v_in = second;
  1.1015 +      } else {
  1.1016 +        u_in = second;
  1.1017 +        v_in = first;
  1.1018 +      }
  1.1019 +      return result != 0;
  1.1020 +    }
  1.1021 +
  1.1022 +    // Change _flow and _state vectors
  1.1023 +    void changeFlow(bool change) {
  1.1024 +      // Augment along the cycle
  1.1025 +      if (delta > 0) {
  1.1026 +        Capacity val = _state[_in_arc] * delta;
  1.1027 +        _flow[_in_arc] += val;
  1.1028 +        for (int u = _source[_in_arc]; u != join; u = _parent[u]) {
  1.1029 +          _flow[_pred[u]] += _forward[u] ? -val : val;
  1.1030 +        }
  1.1031 +        for (int u = _target[_in_arc]; u != join; u = _parent[u]) {
  1.1032 +          _flow[_pred[u]] += _forward[u] ? val : -val;
  1.1033 +        }
  1.1034 +      }
  1.1035 +      // Update the state of the entering and leaving arcs
  1.1036 +      if (change) {
  1.1037 +        _state[_in_arc] = STATE_TREE;
  1.1038 +        _state[_pred[u_out]] =
  1.1039 +          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
  1.1040 +      } else {
  1.1041 +        _state[_in_arc] = -_state[_in_arc];
  1.1042 +      }
  1.1043 +    }
  1.1044 +
  1.1045 +    // Update _thread and _parent vectors
  1.1046 +    void updateThreadParent() {
  1.1047 +      int u;
  1.1048 +      v_out = _parent[u_out];
  1.1049 +
  1.1050 +      // Handle the case when join and v_out coincide
  1.1051 +      bool par_first = false;
  1.1052 +      if (join == v_out) {
  1.1053 +        for (u = join; u != u_in && u != v_in; u = _thread[u]) ;
  1.1054 +        if (u == v_in) {
  1.1055 +          par_first = true;
  1.1056 +          while (_thread[u] != u_out) u = _thread[u];
  1.1057 +          first = u;
  1.1058 +        }
  1.1059 +      }
  1.1060 +
  1.1061 +      // Find the last successor of u_in (u) and the node after it (right)
  1.1062 +      // according to the thread index
  1.1063 +      for (u = u_in; _depth[_thread[u]] > _depth[u_in]; u = _thread[u]) ;
  1.1064 +      right = _thread[u];
  1.1065 +      if (_thread[v_in] == u_out) {
  1.1066 +        for (last = u; _depth[last] > _depth[u_out]; last = _thread[last]) ;
  1.1067 +        if (last == u_out) last = _thread[last];
  1.1068 +      }
  1.1069 +      else last = _thread[v_in];
  1.1070 +
  1.1071 +      // Update stem nodes
  1.1072 +      _thread[v_in] = stem = u_in;
  1.1073 +      par_stem = v_in;
  1.1074 +      while (stem != u_out) {
  1.1075 +        _thread[u] = new_stem = _parent[stem];
  1.1076 +
  1.1077 +        // Find the node just before the stem node (u) according to
  1.1078 +        // the original thread index
  1.1079 +        for (u = new_stem; _thread[u] != stem; u = _thread[u]) ;
  1.1080 +        _thread[u] = right;
  1.1081 +
  1.1082 +        // Change the parent node of stem and shift stem and par_stem nodes
  1.1083 +        _parent[stem] = par_stem;
  1.1084 +        par_stem = stem;
  1.1085 +        stem = new_stem;
  1.1086 +
  1.1087 +        // Find the last successor of stem (u) and the node after it (right)
  1.1088 +        // according to the thread index
  1.1089 +        for (u = stem; _depth[_thread[u]] > _depth[stem]; u = _thread[u]) ;
  1.1090 +        right = _thread[u];
  1.1091 +      }
  1.1092 +      _parent[u_out] = par_stem;
  1.1093 +      _thread[u] = last;
  1.1094 +
  1.1095 +      if (join == v_out && par_first) {
  1.1096 +        if (first != v_in) _thread[first] = right;
  1.1097 +      } else {
  1.1098 +        for (u = v_out; _thread[u] != u_out; u = _thread[u]) ;
  1.1099 +        _thread[u] = right;
  1.1100 +      }
  1.1101 +    }
  1.1102 +
  1.1103 +    // Update _pred and _forward vectors
  1.1104 +    void updatePredArc() {
  1.1105 +      int u = u_out, v;
  1.1106 +      while (u != u_in) {
  1.1107 +        v = _parent[u];
  1.1108 +        _pred[u] = _pred[v];
  1.1109 +        _forward[u] = !_forward[v];
  1.1110 +        u = v;
  1.1111 +      }
  1.1112 +      _pred[u_in] = _in_arc;
  1.1113 +      _forward[u_in] = (u_in == _source[_in_arc]);
  1.1114 +    }
  1.1115 +
  1.1116 +    // Update _depth and _potential vectors
  1.1117 +    void updateDepthPotential() {
  1.1118 +      _depth[u_in] = _depth[v_in] + 1;
  1.1119 +      Cost sigma = _forward[u_in] ?
  1.1120 +        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
  1.1121 +        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
  1.1122 +      _pi[u_in] += sigma;
  1.1123 +      for(int u = _thread[u_in]; _parent[u] != -1; u = _thread[u]) {
  1.1124 +        _depth[u] = _depth[_parent[u]] + 1;
  1.1125 +        if (_depth[u] <= _depth[u_in]) break;
  1.1126 +        _pi[u] += sigma;
  1.1127 +      }
  1.1128 +    }
  1.1129 +
  1.1130 +    // Execute the algorithm
  1.1131 +    bool start(PivotRuleEnum pivot_rule) {
  1.1132 +      // Select the pivot rule implementation
  1.1133 +      switch (pivot_rule) {
  1.1134 +        case FIRST_ELIGIBLE_PIVOT:
  1.1135 +          return start<FirstEligiblePivotRule>();
  1.1136 +        case BEST_ELIGIBLE_PIVOT:
  1.1137 +          return start<BestEligiblePivotRule>();
  1.1138 +        case BLOCK_SEARCH_PIVOT:
  1.1139 +          return start<BlockSearchPivotRule>();
  1.1140 +        case CANDIDATE_LIST_PIVOT:
  1.1141 +          return start<CandidateListPivotRule>();
  1.1142 +        case ALTERING_LIST_PIVOT:
  1.1143 +          return start<AlteringListPivotRule>();
  1.1144 +      }
  1.1145 +      return false;
  1.1146 +    }
  1.1147 +
  1.1148 +    template<class PivotRuleImplementation>
  1.1149 +    bool start() {
  1.1150 +      PivotRuleImplementation pivot(*this);
  1.1151 +
  1.1152 +      // Execute the network simplex algorithm
  1.1153 +      while (pivot.findEnteringArc()) {
  1.1154 +        findJoinNode();
  1.1155 +        bool change = findLeavingArc();
  1.1156 +        changeFlow(change);
  1.1157 +        if (change) {
  1.1158 +          updateThreadParent();
  1.1159 +          updatePredArc();
  1.1160 +          updateDepthPotential();
  1.1161 +        }
  1.1162 +      }
  1.1163 +
  1.1164 +      // Check if the flow amount equals zero on all the artificial arcs
  1.1165 +      for (int e = _arc_num; e != _arc_num + _node_num; ++e) {
  1.1166 +        if (_flow[e] > 0) return false;
  1.1167 +      }
  1.1168 +
  1.1169 +      // Copy flow values to _flow_result
  1.1170 +      if (_orig_lower) {
  1.1171 +        for (int i = 0; i != _arc_num; ++i) {
  1.1172 +          Arc e = _arc[i];
  1.1173 +          (*_flow_result)[e] = (*_orig_lower)[e] + _flow[i];
  1.1174 +        }
  1.1175 +      } else {
  1.1176 +        for (int i = 0; i != _arc_num; ++i) {
  1.1177 +          (*_flow_result)[_arc[i]] = _flow[i];
  1.1178 +        }
  1.1179 +      }
  1.1180 +      // Copy potential values to _potential_result
  1.1181 +      for (int i = 0; i != _node_num; ++i) {
  1.1182 +        (*_potential_result)[_node[i]] = _pi[i];
  1.1183 +      }
  1.1184 +
  1.1185 +      return true;
  1.1186 +    }
  1.1187 +
  1.1188 +  }; //class NetworkSimplex
  1.1189 +
  1.1190 +  ///@}
  1.1191 +
  1.1192 +} //namespace lemon
  1.1193 +
  1.1194 +#endif //LEMON_NETWORK_SIMPLEX_H