kpeter@601: /* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@601:  *
kpeter@601:  * This file is a part of LEMON, a generic C++ optimization library.
kpeter@601:  *
kpeter@601:  * Copyright (C) 2003-2009
kpeter@601:  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@601:  * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@601:  *
kpeter@601:  * Permission to use, modify and distribute this software is granted
kpeter@601:  * provided that this copyright notice appears in all copies. For
kpeter@601:  * precise terms see the accompanying LICENSE file.
kpeter@601:  *
kpeter@601:  * This software is provided "AS IS" with no warranty of any kind,
kpeter@601:  * express or implied, and with no claim as to its suitability for any
kpeter@601:  * purpose.
kpeter@601:  *
kpeter@601:  */
kpeter@601: 
kpeter@601: #ifndef LEMON_NETWORK_SIMPLEX_H
kpeter@601: #define LEMON_NETWORK_SIMPLEX_H
kpeter@601: 
kpeter@601: /// \ingroup min_cost_flow
kpeter@601: ///
kpeter@601: /// \file
kpeter@605: /// \brief Network Simplex algorithm for finding a minimum cost flow.
kpeter@601: 
kpeter@601: #include <vector>
kpeter@601: #include <limits>
kpeter@601: #include <algorithm>
kpeter@601: 
kpeter@603: #include <lemon/core.h>
kpeter@601: #include <lemon/math.h>
kpeter@601: 
kpeter@601: namespace lemon {
kpeter@601: 
kpeter@601:   /// \addtogroup min_cost_flow
kpeter@601:   /// @{
kpeter@601: 
kpeter@605:   /// \brief Implementation of the primal Network Simplex algorithm
kpeter@601:   /// for finding a \ref min_cost_flow "minimum cost flow".
kpeter@601:   ///
kpeter@605:   /// \ref NetworkSimplex implements the primal Network Simplex algorithm
kpeter@601:   /// for finding a \ref min_cost_flow "minimum cost flow".
kpeter@606:   /// This algorithm is a specialized version of the linear programming
kpeter@606:   /// simplex method directly for the minimum cost flow problem.
kpeter@606:   /// It is one of the most efficient solution methods.
kpeter@606:   ///
kpeter@606:   /// In general this class is the fastest implementation available
kpeter@606:   /// in LEMON for the minimum cost flow problem.
kpeter@640:   /// Moreover it supports both directions of the supply/demand inequality
kpeter@640:   /// constraints. For more information see \ref SupplyType.
kpeter@640:   ///
kpeter@640:   /// Most of the parameters of the problem (except for the digraph)
kpeter@640:   /// can be given using separate functions, and the algorithm can be
kpeter@640:   /// executed using the \ref run() function. If some parameters are not
kpeter@640:   /// specified, then default values will be used.
kpeter@601:   ///
kpeter@605:   /// \tparam GR The digraph type the algorithm runs on.
kpeter@641:   /// \tparam V The value type used for flow amounts, capacity bounds
kpeter@607:   /// and supply values in the algorithm. By default it is \c int.
kpeter@607:   /// \tparam C The value type used for costs and potentials in the
kpeter@641:   /// algorithm. By default it is the same as \c V.
kpeter@601:   ///
kpeter@608:   /// \warning Both value types must be signed and all input data must
kpeter@608:   /// be integer.
kpeter@601:   ///
kpeter@605:   /// \note %NetworkSimplex provides five different pivot rule
kpeter@609:   /// implementations, from which the most efficient one is used
kpeter@609:   /// by default. For more information see \ref PivotRule.
kpeter@641:   template <typename GR, typename V = int, typename C = V>
kpeter@601:   class NetworkSimplex
kpeter@601:   {
kpeter@605:   public:
kpeter@601: 
kpeter@642:     /// The type of the flow amounts, capacity bounds and supply values
kpeter@641:     typedef V Value;
kpeter@642:     /// The type of the arc costs
kpeter@607:     typedef C Cost;
kpeter@605: 
kpeter@605:   public:
kpeter@605: 
kpeter@640:     /// \brief Problem type constants for the \c run() function.
kpeter@605:     ///
kpeter@640:     /// Enum type containing the problem type constants that can be
kpeter@640:     /// returned by the \ref run() function of the algorithm.
kpeter@640:     enum ProblemType {
kpeter@640:       /// The problem has no feasible solution (flow).
kpeter@640:       INFEASIBLE,
kpeter@640:       /// The problem has optimal solution (i.e. it is feasible and
kpeter@640:       /// bounded), and the algorithm has found optimal flow and node
kpeter@640:       /// potentials (primal and dual solutions).
kpeter@640:       OPTIMAL,
kpeter@640:       /// The objective function of the problem is unbounded, i.e.
kpeter@640:       /// there is a directed cycle having negative total cost and
kpeter@640:       /// infinite upper bound.
kpeter@640:       UNBOUNDED
kpeter@640:     };
kpeter@640:     
kpeter@640:     /// \brief Constants for selecting the type of the supply constraints.
kpeter@640:     ///
kpeter@640:     /// Enum type containing constants for selecting the supply type,
kpeter@640:     /// i.e. the direction of the inequalities in the supply/demand
kpeter@640:     /// constraints of the \ref min_cost_flow "minimum cost flow problem".
kpeter@640:     ///
kpeter@640:     /// The default supply type is \c GEQ, since this form is supported
kpeter@640:     /// by other minimum cost flow algorithms and the \ref Circulation
kpeter@640:     /// algorithm, as well.
kpeter@640:     /// The \c LEQ problem type can be selected using the \ref supplyType()
kpeter@605:     /// function.
kpeter@605:     ///
kpeter@640:     /// Note that the equality form is a special case of both supply types.
kpeter@640:     enum SupplyType {
kpeter@640: 
kpeter@640:       /// This option means that there are <em>"greater or equal"</em>
kpeter@640:       /// supply/demand constraints in the definition, i.e. the exact
kpeter@640:       /// formulation of the problem is the following.
kpeter@640:       /**
kpeter@640:           \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
kpeter@640:           \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
kpeter@640:               sup(u) \quad \forall u\in V \f]
kpeter@640:           \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
kpeter@640:       */
kpeter@640:       /// It means that the total demand must be greater or equal to the 
kpeter@640:       /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
kpeter@640:       /// negative) and all the supplies have to be carried out from 
kpeter@640:       /// the supply nodes, but there could be demands that are not 
kpeter@640:       /// satisfied.
kpeter@640:       GEQ,
kpeter@640:       /// It is just an alias for the \c GEQ option.
kpeter@640:       CARRY_SUPPLIES = GEQ,
kpeter@640: 
kpeter@640:       /// This option means that there are <em>"less or equal"</em>
kpeter@640:       /// supply/demand constraints in the definition, i.e. the exact
kpeter@640:       /// formulation of the problem is the following.
kpeter@640:       /**
kpeter@640:           \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
kpeter@640:           \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
kpeter@640:               sup(u) \quad \forall u\in V \f]
kpeter@640:           \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
kpeter@640:       */
kpeter@640:       /// It means that the total demand must be less or equal to the 
kpeter@640:       /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
kpeter@640:       /// positive) and all the demands have to be satisfied, but there
kpeter@640:       /// could be supplies that are not carried out from the supply
kpeter@640:       /// nodes.
kpeter@640:       LEQ,
kpeter@640:       /// It is just an alias for the \c LEQ option.
kpeter@640:       SATISFY_DEMANDS = LEQ
kpeter@640:     };
kpeter@640:     
kpeter@640:     /// \brief Constants for selecting the pivot rule.
kpeter@640:     ///
kpeter@640:     /// Enum type containing constants for selecting the pivot rule for
kpeter@640:     /// the \ref run() function.
kpeter@640:     ///
kpeter@605:     /// \ref NetworkSimplex provides five different pivot rule
kpeter@605:     /// implementations that significantly affect the running time
kpeter@605:     /// of the algorithm.
kpeter@605:     /// By default \ref BLOCK_SEARCH "Block Search" is used, which
kpeter@605:     /// proved to be the most efficient and the most robust on various
kpeter@605:     /// test inputs according to our benchmark tests.
kpeter@605:     /// However another pivot rule can be selected using the \ref run()
kpeter@605:     /// function with the proper parameter.
kpeter@605:     enum PivotRule {
kpeter@605: 
kpeter@605:       /// The First Eligible pivot rule.
kpeter@605:       /// The next eligible arc is selected in a wraparound fashion
kpeter@605:       /// in every iteration.
kpeter@605:       FIRST_ELIGIBLE,
kpeter@605: 
kpeter@605:       /// The Best Eligible pivot rule.
kpeter@605:       /// The best eligible arc is selected in every iteration.
kpeter@605:       BEST_ELIGIBLE,
kpeter@605: 
kpeter@605:       /// The Block Search pivot rule.
kpeter@605:       /// A specified number of arcs are examined in every iteration
kpeter@605:       /// in a wraparound fashion and the best eligible arc is selected
kpeter@605:       /// from this block.
kpeter@605:       BLOCK_SEARCH,
kpeter@605: 
kpeter@605:       /// The Candidate List pivot rule.
kpeter@605:       /// In a major iteration a candidate list is built from eligible arcs
kpeter@605:       /// in a wraparound fashion and in the following minor iterations
kpeter@605:       /// the best eligible arc is selected from this list.
kpeter@605:       CANDIDATE_LIST,
kpeter@605: 
kpeter@605:       /// The Altering Candidate List pivot rule.
kpeter@605:       /// It is a modified version of the Candidate List method.
kpeter@605:       /// It keeps only the several best eligible arcs from the former
kpeter@605:       /// candidate list and extends this list in every iteration.
kpeter@605:       ALTERING_LIST
kpeter@605:     };
kpeter@609:     
kpeter@605:   private:
kpeter@605: 
kpeter@605:     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
kpeter@605: 
kpeter@601:     typedef std::vector<Arc> ArcVector;
kpeter@601:     typedef std::vector<Node> NodeVector;
kpeter@601:     typedef std::vector<int> IntVector;
kpeter@601:     typedef std::vector<bool> BoolVector;
kpeter@642:     typedef std::vector<Value> ValueVector;
kpeter@607:     typedef std::vector<Cost> CostVector;
kpeter@601: 
kpeter@601:     // State constants for arcs
kpeter@601:     enum ArcStateEnum {
kpeter@601:       STATE_UPPER = -1,
kpeter@601:       STATE_TREE  =  0,
kpeter@601:       STATE_LOWER =  1
kpeter@601:     };
kpeter@601: 
kpeter@601:   private:
kpeter@601: 
kpeter@605:     // Data related to the underlying digraph
kpeter@605:     const GR &_graph;
kpeter@605:     int _node_num;
kpeter@605:     int _arc_num;
kpeter@605: 
kpeter@605:     // Parameters of the problem
kpeter@642:     bool _have_lower;
kpeter@640:     SupplyType _stype;
kpeter@641:     Value _sum_supply;
kpeter@601: 
kpeter@605:     // Data structures for storing the digraph
kpeter@603:     IntNodeMap _node_id;
kpeter@642:     IntArcMap _arc_id;
kpeter@603:     IntVector _source;
kpeter@603:     IntVector _target;
kpeter@603: 
kpeter@605:     // Node and arc data
kpeter@642:     ValueVector _lower;
kpeter@642:     ValueVector _upper;
kpeter@642:     ValueVector _cap;
kpeter@607:     CostVector _cost;
kpeter@642:     ValueVector _supply;
kpeter@642:     ValueVector _flow;
kpeter@607:     CostVector _pi;
kpeter@601: 
kpeter@603:     // Data for storing the spanning tree structure
kpeter@601:     IntVector _parent;
kpeter@601:     IntVector _pred;
kpeter@601:     IntVector _thread;
kpeter@604:     IntVector _rev_thread;
kpeter@604:     IntVector _succ_num;
kpeter@604:     IntVector _last_succ;
kpeter@604:     IntVector _dirty_revs;
kpeter@601:     BoolVector _forward;
kpeter@601:     IntVector _state;
kpeter@601:     int _root;
kpeter@601: 
kpeter@601:     // Temporary data used in the current pivot iteration
kpeter@603:     int in_arc, join, u_in, v_in, u_out, v_out;
kpeter@603:     int first, second, right, last;
kpeter@601:     int stem, par_stem, new_stem;
kpeter@641:     Value delta;
kpeter@601: 
kpeter@640:   public:
kpeter@640:   
kpeter@640:     /// \brief Constant for infinite upper bounds (capacities).
kpeter@640:     ///
kpeter@640:     /// Constant for infinite upper bounds (capacities).
kpeter@641:     /// It is \c std::numeric_limits<Value>::infinity() if available,
kpeter@641:     /// \c std::numeric_limits<Value>::max() otherwise.
kpeter@641:     const Value INF;
kpeter@640: 
kpeter@601:   private:
kpeter@601: 
kpeter@605:     // Implementation of the First Eligible pivot rule
kpeter@601:     class FirstEligiblePivotRule
kpeter@601:     {
kpeter@601:     private:
kpeter@601: 
kpeter@601:       // References to the NetworkSimplex class
kpeter@601:       const IntVector  &_source;
kpeter@601:       const IntVector  &_target;
kpeter@607:       const CostVector &_cost;
kpeter@601:       const IntVector  &_state;
kpeter@607:       const CostVector &_pi;
kpeter@601:       int &_in_arc;
kpeter@601:       int _arc_num;
kpeter@601: 
kpeter@601:       // Pivot rule data
kpeter@601:       int _next_arc;
kpeter@601: 
kpeter@601:     public:
kpeter@601: 
kpeter@605:       // Constructor
kpeter@601:       FirstEligiblePivotRule(NetworkSimplex &ns) :
kpeter@603:         _source(ns._source), _target(ns._target),
kpeter@601:         _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603:         _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
kpeter@601:       {}
kpeter@601: 
kpeter@605:       // Find next entering arc
kpeter@601:       bool findEnteringArc() {
kpeter@607:         Cost c;
kpeter@601:         for (int e = _next_arc; e < _arc_num; ++e) {
kpeter@601:           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (c < 0) {
kpeter@601:             _in_arc = e;
kpeter@601:             _next_arc = e + 1;
kpeter@601:             return true;
kpeter@601:           }
kpeter@601:         }
kpeter@601:         for (int e = 0; e < _next_arc; ++e) {
kpeter@601:           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (c < 0) {
kpeter@601:             _in_arc = e;
kpeter@601:             _next_arc = e + 1;
kpeter@601:             return true;
kpeter@601:           }
kpeter@601:         }
kpeter@601:         return false;
kpeter@601:       }
kpeter@601: 
kpeter@601:     }; //class FirstEligiblePivotRule
kpeter@601: 
kpeter@601: 
kpeter@605:     // Implementation of the Best Eligible pivot rule
kpeter@601:     class BestEligiblePivotRule
kpeter@601:     {
kpeter@601:     private:
kpeter@601: 
kpeter@601:       // References to the NetworkSimplex class
kpeter@601:       const IntVector  &_source;
kpeter@601:       const IntVector  &_target;
kpeter@607:       const CostVector &_cost;
kpeter@601:       const IntVector  &_state;
kpeter@607:       const CostVector &_pi;
kpeter@601:       int &_in_arc;
kpeter@601:       int _arc_num;
kpeter@601: 
kpeter@601:     public:
kpeter@601: 
kpeter@605:       // Constructor
kpeter@601:       BestEligiblePivotRule(NetworkSimplex &ns) :
kpeter@603:         _source(ns._source), _target(ns._target),
kpeter@601:         _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603:         _in_arc(ns.in_arc), _arc_num(ns._arc_num)
kpeter@601:       {}
kpeter@601: 
kpeter@605:       // Find next entering arc
kpeter@601:       bool findEnteringArc() {
kpeter@607:         Cost c, min = 0;
kpeter@601:         for (int e = 0; e < _arc_num; ++e) {
kpeter@601:           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (c < min) {
kpeter@601:             min = c;
kpeter@601:             _in_arc = e;
kpeter@601:           }
kpeter@601:         }
kpeter@601:         return min < 0;
kpeter@601:       }
kpeter@601: 
kpeter@601:     }; //class BestEligiblePivotRule
kpeter@601: 
kpeter@601: 
kpeter@605:     // Implementation of the Block Search pivot rule
kpeter@601:     class BlockSearchPivotRule
kpeter@601:     {
kpeter@601:     private:
kpeter@601: 
kpeter@601:       // References to the NetworkSimplex class
kpeter@601:       const IntVector  &_source;
kpeter@601:       const IntVector  &_target;
kpeter@607:       const CostVector &_cost;
kpeter@601:       const IntVector  &_state;
kpeter@607:       const CostVector &_pi;
kpeter@601:       int &_in_arc;
kpeter@601:       int _arc_num;
kpeter@601: 
kpeter@601:       // Pivot rule data
kpeter@601:       int _block_size;
kpeter@601:       int _next_arc;
kpeter@601: 
kpeter@601:     public:
kpeter@601: 
kpeter@605:       // Constructor
kpeter@601:       BlockSearchPivotRule(NetworkSimplex &ns) :
kpeter@603:         _source(ns._source), _target(ns._target),
kpeter@601:         _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603:         _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
kpeter@601:       {
kpeter@601:         // The main parameters of the pivot rule
kpeter@601:         const double BLOCK_SIZE_FACTOR = 2.0;
kpeter@601:         const int MIN_BLOCK_SIZE = 10;
kpeter@601: 
alpar@612:         _block_size = std::max( int(BLOCK_SIZE_FACTOR *
alpar@612:                                     std::sqrt(double(_arc_num))),
kpeter@601:                                 MIN_BLOCK_SIZE );
kpeter@601:       }
kpeter@601: 
kpeter@605:       // Find next entering arc
kpeter@601:       bool findEnteringArc() {
kpeter@607:         Cost c, min = 0;
kpeter@601:         int cnt = _block_size;
kpeter@601:         int e, min_arc = _next_arc;
kpeter@601:         for (e = _next_arc; e < _arc_num; ++e) {
kpeter@601:           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (c < min) {
kpeter@601:             min = c;
kpeter@601:             min_arc = e;
kpeter@601:           }
kpeter@601:           if (--cnt == 0) {
kpeter@601:             if (min < 0) break;
kpeter@601:             cnt = _block_size;
kpeter@601:           }
kpeter@601:         }
kpeter@601:         if (min == 0 || cnt > 0) {
kpeter@601:           for (e = 0; e < _next_arc; ++e) {
kpeter@601:             c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:             if (c < min) {
kpeter@601:               min = c;
kpeter@601:               min_arc = e;
kpeter@601:             }
kpeter@601:             if (--cnt == 0) {
kpeter@601:               if (min < 0) break;
kpeter@601:               cnt = _block_size;
kpeter@601:             }
kpeter@601:           }
kpeter@601:         }
kpeter@601:         if (min >= 0) return false;
kpeter@601:         _in_arc = min_arc;
kpeter@601:         _next_arc = e;
kpeter@601:         return true;
kpeter@601:       }
kpeter@601: 
kpeter@601:     }; //class BlockSearchPivotRule
kpeter@601: 
kpeter@601: 
kpeter@605:     // Implementation of the Candidate List pivot rule
kpeter@601:     class CandidateListPivotRule
kpeter@601:     {
kpeter@601:     private:
kpeter@601: 
kpeter@601:       // References to the NetworkSimplex class
kpeter@601:       const IntVector  &_source;
kpeter@601:       const IntVector  &_target;
kpeter@607:       const CostVector &_cost;
kpeter@601:       const IntVector  &_state;
kpeter@607:       const CostVector &_pi;
kpeter@601:       int &_in_arc;
kpeter@601:       int _arc_num;
kpeter@601: 
kpeter@601:       // Pivot rule data
kpeter@601:       IntVector _candidates;
kpeter@601:       int _list_length, _minor_limit;
kpeter@601:       int _curr_length, _minor_count;
kpeter@601:       int _next_arc;
kpeter@601: 
kpeter@601:     public:
kpeter@601: 
kpeter@601:       /// Constructor
kpeter@601:       CandidateListPivotRule(NetworkSimplex &ns) :
kpeter@603:         _source(ns._source), _target(ns._target),
kpeter@601:         _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603:         _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
kpeter@601:       {
kpeter@601:         // The main parameters of the pivot rule
kpeter@601:         const double LIST_LENGTH_FACTOR = 1.0;
kpeter@601:         const int MIN_LIST_LENGTH = 10;
kpeter@601:         const double MINOR_LIMIT_FACTOR = 0.1;
kpeter@601:         const int MIN_MINOR_LIMIT = 3;
kpeter@601: 
alpar@612:         _list_length = std::max( int(LIST_LENGTH_FACTOR *
alpar@612:                                      std::sqrt(double(_arc_num))),
kpeter@601:                                  MIN_LIST_LENGTH );
kpeter@601:         _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
kpeter@601:                                  MIN_MINOR_LIMIT );
kpeter@601:         _curr_length = _minor_count = 0;
kpeter@601:         _candidates.resize(_list_length);
kpeter@601:       }
kpeter@601: 
kpeter@601:       /// Find next entering arc
kpeter@601:       bool findEnteringArc() {
kpeter@607:         Cost min, c;
kpeter@601:         int e, min_arc = _next_arc;
kpeter@601:         if (_curr_length > 0 && _minor_count < _minor_limit) {
kpeter@601:           // Minor iteration: select the best eligible arc from the
kpeter@601:           // current candidate list
kpeter@601:           ++_minor_count;
kpeter@601:           min = 0;
kpeter@601:           for (int i = 0; i < _curr_length; ++i) {
kpeter@601:             e = _candidates[i];
kpeter@601:             c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:             if (c < min) {
kpeter@601:               min = c;
kpeter@601:               min_arc = e;
kpeter@601:             }
kpeter@601:             if (c >= 0) {
kpeter@601:               _candidates[i--] = _candidates[--_curr_length];
kpeter@601:             }
kpeter@601:           }
kpeter@601:           if (min < 0) {
kpeter@601:             _in_arc = min_arc;
kpeter@601:             return true;
kpeter@601:           }
kpeter@601:         }
kpeter@601: 
kpeter@601:         // Major iteration: build a new candidate list
kpeter@601:         min = 0;
kpeter@601:         _curr_length = 0;
kpeter@601:         for (e = _next_arc; e < _arc_num; ++e) {
kpeter@601:           c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (c < 0) {
kpeter@601:             _candidates[_curr_length++] = e;
kpeter@601:             if (c < min) {
kpeter@601:               min = c;
kpeter@601:               min_arc = e;
kpeter@601:             }
kpeter@601:             if (_curr_length == _list_length) break;
kpeter@601:           }
kpeter@601:         }
kpeter@601:         if (_curr_length < _list_length) {
kpeter@601:           for (e = 0; e < _next_arc; ++e) {
kpeter@601:             c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:             if (c < 0) {
kpeter@601:               _candidates[_curr_length++] = e;
kpeter@601:               if (c < min) {
kpeter@601:                 min = c;
kpeter@601:                 min_arc = e;
kpeter@601:               }
kpeter@601:               if (_curr_length == _list_length) break;
kpeter@601:             }
kpeter@601:           }
kpeter@601:         }
kpeter@601:         if (_curr_length == 0) return false;
kpeter@601:         _minor_count = 1;
kpeter@601:         _in_arc = min_arc;
kpeter@601:         _next_arc = e;
kpeter@601:         return true;
kpeter@601:       }
kpeter@601: 
kpeter@601:     }; //class CandidateListPivotRule
kpeter@601: 
kpeter@601: 
kpeter@605:     // Implementation of the Altering Candidate List pivot rule
kpeter@601:     class AlteringListPivotRule
kpeter@601:     {
kpeter@601:     private:
kpeter@601: 
kpeter@601:       // References to the NetworkSimplex class
kpeter@601:       const IntVector  &_source;
kpeter@601:       const IntVector  &_target;
kpeter@607:       const CostVector &_cost;
kpeter@601:       const IntVector  &_state;
kpeter@607:       const CostVector &_pi;
kpeter@601:       int &_in_arc;
kpeter@601:       int _arc_num;
kpeter@601: 
kpeter@601:       // Pivot rule data
kpeter@601:       int _block_size, _head_length, _curr_length;
kpeter@601:       int _next_arc;
kpeter@601:       IntVector _candidates;
kpeter@607:       CostVector _cand_cost;
kpeter@601: 
kpeter@601:       // Functor class to compare arcs during sort of the candidate list
kpeter@601:       class SortFunc
kpeter@601:       {
kpeter@601:       private:
kpeter@607:         const CostVector &_map;
kpeter@601:       public:
kpeter@607:         SortFunc(const CostVector &map) : _map(map) {}
kpeter@601:         bool operator()(int left, int right) {
kpeter@601:           return _map[left] > _map[right];
kpeter@601:         }
kpeter@601:       };
kpeter@601: 
kpeter@601:       SortFunc _sort_func;
kpeter@601: 
kpeter@601:     public:
kpeter@601: 
kpeter@605:       // Constructor
kpeter@601:       AlteringListPivotRule(NetworkSimplex &ns) :
kpeter@603:         _source(ns._source), _target(ns._target),
kpeter@601:         _cost(ns._cost), _state(ns._state), _pi(ns._pi),
kpeter@603:         _in_arc(ns.in_arc), _arc_num(ns._arc_num),
kpeter@601:         _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
kpeter@601:       {
kpeter@601:         // The main parameters of the pivot rule
kpeter@601:         const double BLOCK_SIZE_FACTOR = 1.5;
kpeter@601:         const int MIN_BLOCK_SIZE = 10;
kpeter@601:         const double HEAD_LENGTH_FACTOR = 0.1;
kpeter@601:         const int MIN_HEAD_LENGTH = 3;
kpeter@601: 
alpar@612:         _block_size = std::max( int(BLOCK_SIZE_FACTOR *
alpar@612:                                     std::sqrt(double(_arc_num))),
kpeter@601:                                 MIN_BLOCK_SIZE );
kpeter@601:         _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
kpeter@601:                                  MIN_HEAD_LENGTH );
kpeter@601:         _candidates.resize(_head_length + _block_size);
kpeter@601:         _curr_length = 0;
kpeter@601:       }
kpeter@601: 
kpeter@605:       // Find next entering arc
kpeter@601:       bool findEnteringArc() {
kpeter@601:         // Check the current candidate list
kpeter@601:         int e;
kpeter@601:         for (int i = 0; i < _curr_length; ++i) {
kpeter@601:           e = _candidates[i];
kpeter@601:           _cand_cost[e] = _state[e] *
kpeter@601:             (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (_cand_cost[e] >= 0) {
kpeter@601:             _candidates[i--] = _candidates[--_curr_length];
kpeter@601:           }
kpeter@601:         }
kpeter@601: 
kpeter@601:         // Extend the list
kpeter@601:         int cnt = _block_size;
kpeter@603:         int last_arc = 0;
kpeter@601:         int limit = _head_length;
kpeter@601: 
kpeter@601:         for (int e = _next_arc; e < _arc_num; ++e) {
kpeter@601:           _cand_cost[e] = _state[e] *
kpeter@601:             (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:           if (_cand_cost[e] < 0) {
kpeter@601:             _candidates[_curr_length++] = e;
kpeter@603:             last_arc = e;
kpeter@601:           }
kpeter@601:           if (--cnt == 0) {
kpeter@601:             if (_curr_length > limit) break;
kpeter@601:             limit = 0;
kpeter@601:             cnt = _block_size;
kpeter@601:           }
kpeter@601:         }
kpeter@601:         if (_curr_length <= limit) {
kpeter@601:           for (int e = 0; e < _next_arc; ++e) {
kpeter@601:             _cand_cost[e] = _state[e] *
kpeter@601:               (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
kpeter@601:             if (_cand_cost[e] < 0) {
kpeter@601:               _candidates[_curr_length++] = e;
kpeter@603:               last_arc = e;
kpeter@601:             }
kpeter@601:             if (--cnt == 0) {
kpeter@601:               if (_curr_length > limit) break;
kpeter@601:               limit = 0;
kpeter@601:               cnt = _block_size;
kpeter@601:             }
kpeter@601:           }
kpeter@601:         }
kpeter@601:         if (_curr_length == 0) return false;
kpeter@603:         _next_arc = last_arc + 1;
kpeter@601: 
kpeter@601:         // Make heap of the candidate list (approximating a partial sort)
kpeter@601:         make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
kpeter@601:                    _sort_func );
kpeter@601: 
kpeter@601:         // Pop the first element of the heap
kpeter@601:         _in_arc = _candidates[0];
kpeter@601:         pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
kpeter@601:                   _sort_func );
kpeter@601:         _curr_length = std::min(_head_length, _curr_length - 1);
kpeter@601:         return true;
kpeter@601:       }
kpeter@601: 
kpeter@601:     }; //class AlteringListPivotRule
kpeter@601: 
kpeter@601:   public:
kpeter@601: 
kpeter@605:     /// \brief Constructor.
kpeter@601:     ///
kpeter@609:     /// The constructor of the class.
kpeter@601:     ///
kpeter@603:     /// \param graph The digraph the algorithm runs on.
kpeter@605:     NetworkSimplex(const GR& graph) :
kpeter@642:       _graph(graph), _node_id(graph), _arc_id(graph),
kpeter@641:       INF(std::numeric_limits<Value>::has_infinity ?
kpeter@641:           std::numeric_limits<Value>::infinity() :
kpeter@641:           std::numeric_limits<Value>::max())
kpeter@605:     {
kpeter@640:       // Check the value types
kpeter@641:       LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
kpeter@640:         "The flow type of NetworkSimplex must be signed");
kpeter@640:       LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
kpeter@640:         "The cost type of NetworkSimplex must be signed");
kpeter@642:         
kpeter@642:       // Resize vectors
kpeter@642:       _node_num = countNodes(_graph);
kpeter@642:       _arc_num = countArcs(_graph);
kpeter@642:       int all_node_num = _node_num + 1;
kpeter@642:       int all_arc_num = _arc_num + _node_num;
kpeter@601: 
kpeter@642:       _source.resize(all_arc_num);
kpeter@642:       _target.resize(all_arc_num);
kpeter@642: 
kpeter@642:       _lower.resize(all_arc_num);
kpeter@642:       _upper.resize(all_arc_num);
kpeter@642:       _cap.resize(all_arc_num);
kpeter@642:       _cost.resize(all_arc_num);
kpeter@642:       _supply.resize(all_node_num);
kpeter@642:       _flow.resize(all_arc_num);
kpeter@642:       _pi.resize(all_node_num);
kpeter@642: 
kpeter@642:       _parent.resize(all_node_num);
kpeter@642:       _pred.resize(all_node_num);
kpeter@642:       _forward.resize(all_node_num);
kpeter@642:       _thread.resize(all_node_num);
kpeter@642:       _rev_thread.resize(all_node_num);
kpeter@642:       _succ_num.resize(all_node_num);
kpeter@642:       _last_succ.resize(all_node_num);
kpeter@642:       _state.resize(all_arc_num);
kpeter@642: 
kpeter@642:       // Copy the graph (store the arcs in a mixed order)
kpeter@642:       int i = 0;
kpeter@642:       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@642:         _node_id[n] = i;
kpeter@642:       }
kpeter@642:       int k = std::max(int(std::sqrt(double(_arc_num))), 10);
kpeter@642:       i = 0;
kpeter@642:       for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@642:         _arc_id[a] = i;
kpeter@642:         _source[i] = _node_id[_graph.source(a)];
kpeter@642:         _target[i] = _node_id[_graph.target(a)];
kpeter@642:         if ((i += k) >= _arc_num) i = (i % k) + 1;
kpeter@642:       }
kpeter@642:       
kpeter@642:       // Initialize maps
kpeter@642:       for (int i = 0; i != _node_num; ++i) {
kpeter@642:         _supply[i] = 0;
kpeter@642:       }
kpeter@642:       for (int i = 0; i != _arc_num; ++i) {
kpeter@642:         _lower[i] = 0;
kpeter@642:         _upper[i] = INF;
kpeter@642:         _cost[i] = 1;
kpeter@642:       }
kpeter@642:       _have_lower = false;
kpeter@642:       _stype = GEQ;
kpeter@601:     }
kpeter@601: 
kpeter@609:     /// \name Parameters
kpeter@609:     /// The parameters of the algorithm can be specified using these
kpeter@609:     /// functions.
kpeter@609: 
kpeter@609:     /// @{
kpeter@609: 
kpeter@605:     /// \brief Set the lower bounds on the arcs.
kpeter@605:     ///
kpeter@605:     /// This function sets the lower bounds on the arcs.
kpeter@640:     /// If it is not used before calling \ref run(), the lower bounds
kpeter@640:     /// will be set to zero on all arcs.
kpeter@605:     ///
kpeter@605:     /// \param map An arc map storing the lower bounds.
kpeter@641:     /// Its \c Value type must be convertible to the \c Value type
kpeter@605:     /// of the algorithm.
kpeter@605:     ///
kpeter@605:     /// \return <tt>(*this)</tt>
kpeter@640:     template <typename LowerMap>
kpeter@640:     NetworkSimplex& lowerMap(const LowerMap& map) {
kpeter@642:       _have_lower = true;
kpeter@605:       for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@642:         _lower[_arc_id[a]] = map[a];
kpeter@605:       }
kpeter@605:       return *this;
kpeter@605:     }
kpeter@605: 
kpeter@605:     /// \brief Set the upper bounds (capacities) on the arcs.
kpeter@605:     ///
kpeter@605:     /// This function sets the upper bounds (capacities) on the arcs.
kpeter@640:     /// If it is not used before calling \ref run(), the upper bounds
kpeter@640:     /// will be set to \ref INF on all arcs (i.e. the flow value will be
kpeter@640:     /// unbounded from above on each arc).
kpeter@605:     ///
kpeter@605:     /// \param map An arc map storing the upper bounds.
kpeter@641:     /// Its \c Value type must be convertible to the \c Value type
kpeter@605:     /// of the algorithm.
kpeter@605:     ///
kpeter@605:     /// \return <tt>(*this)</tt>
kpeter@640:     template<typename UpperMap>
kpeter@640:     NetworkSimplex& upperMap(const UpperMap& map) {
kpeter@605:       for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@642:         _upper[_arc_id[a]] = map[a];
kpeter@605:       }
kpeter@605:       return *this;
kpeter@605:     }
kpeter@605: 
kpeter@605:     /// \brief Set the costs of the arcs.
kpeter@605:     ///
kpeter@605:     /// This function sets the costs of the arcs.
kpeter@605:     /// If it is not used before calling \ref run(), the costs
kpeter@605:     /// will be set to \c 1 on all arcs.
kpeter@605:     ///
kpeter@605:     /// \param map An arc map storing the costs.
kpeter@607:     /// Its \c Value type must be convertible to the \c Cost type
kpeter@605:     /// of the algorithm.
kpeter@605:     ///
kpeter@605:     /// \return <tt>(*this)</tt>
kpeter@640:     template<typename CostMap>
kpeter@640:     NetworkSimplex& costMap(const CostMap& map) {
kpeter@605:       for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@642:         _cost[_arc_id[a]] = map[a];
kpeter@605:       }
kpeter@605:       return *this;
kpeter@605:     }
kpeter@605: 
kpeter@605:     /// \brief Set the supply values of the nodes.
kpeter@605:     ///
kpeter@605:     /// This function sets the supply values of the nodes.
kpeter@605:     /// If neither this function nor \ref stSupply() is used before
kpeter@605:     /// calling \ref run(), the supply of each node will be set to zero.
kpeter@605:     /// (It makes sense only if non-zero lower bounds are given.)
kpeter@605:     ///
kpeter@605:     /// \param map A node map storing the supply values.
kpeter@641:     /// Its \c Value type must be convertible to the \c Value type
kpeter@605:     /// of the algorithm.
kpeter@605:     ///
kpeter@605:     /// \return <tt>(*this)</tt>
kpeter@640:     template<typename SupplyMap>
kpeter@640:     NetworkSimplex& supplyMap(const SupplyMap& map) {
kpeter@605:       for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@642:         _supply[_node_id[n]] = map[n];
kpeter@605:       }
kpeter@605:       return *this;
kpeter@605:     }
kpeter@605: 
kpeter@605:     /// \brief Set single source and target nodes and a supply value.
kpeter@605:     ///
kpeter@605:     /// This function sets a single source node and a single target node
kpeter@605:     /// and the required flow value.
kpeter@605:     /// If neither this function nor \ref supplyMap() is used before
kpeter@605:     /// calling \ref run(), the supply of each node will be set to zero.
kpeter@605:     /// (It makes sense only if non-zero lower bounds are given.)
kpeter@605:     ///
kpeter@640:     /// Using this function has the same effect as using \ref supplyMap()
kpeter@640:     /// with such a map in which \c k is assigned to \c s, \c -k is
kpeter@640:     /// assigned to \c t and all other nodes have zero supply value.
kpeter@640:     ///
kpeter@605:     /// \param s The source node.
kpeter@605:     /// \param t The target node.
kpeter@605:     /// \param k The required amount of flow from node \c s to node \c t
kpeter@605:     /// (i.e. the supply of \c s and the demand of \c t).
kpeter@605:     ///
kpeter@605:     /// \return <tt>(*this)</tt>
kpeter@641:     NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
kpeter@642:       for (int i = 0; i != _node_num; ++i) {
kpeter@642:         _supply[i] = 0;
kpeter@642:       }
kpeter@642:       _supply[_node_id[s]] =  k;
kpeter@642:       _supply[_node_id[t]] = -k;
kpeter@605:       return *this;
kpeter@605:     }
kpeter@609:     
kpeter@640:     /// \brief Set the type of the supply constraints.
kpeter@609:     ///
kpeter@640:     /// This function sets the type of the supply/demand constraints.
kpeter@640:     /// If it is not used before calling \ref run(), the \ref GEQ supply
kpeter@609:     /// type will be used.
kpeter@609:     ///
kpeter@640:     /// For more information see \ref SupplyType.
kpeter@609:     ///
kpeter@609:     /// \return <tt>(*this)</tt>
kpeter@640:     NetworkSimplex& supplyType(SupplyType supply_type) {
kpeter@640:       _stype = supply_type;
kpeter@609:       return *this;
kpeter@609:     }
kpeter@605: 
kpeter@609:     /// @}
kpeter@601: 
kpeter@605:     /// \name Execution Control
kpeter@605:     /// The algorithm can be executed using \ref run().
kpeter@605: 
kpeter@601:     /// @{
kpeter@601: 
kpeter@601:     /// \brief Run the algorithm.
kpeter@601:     ///
kpeter@601:     /// This function runs the algorithm.
kpeter@609:     /// The paramters can be specified using functions \ref lowerMap(),
kpeter@640:     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), 
kpeter@642:     /// \ref supplyType().
kpeter@609:     /// For example,
kpeter@605:     /// \code
kpeter@605:     ///   NetworkSimplex<ListDigraph> ns(graph);
kpeter@640:     ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
kpeter@605:     ///     .supplyMap(sup).run();
kpeter@605:     /// \endcode
kpeter@601:     ///
kpeter@606:     /// This function can be called more than once. All the parameters
kpeter@606:     /// that have been given are kept for the next call, unless
kpeter@606:     /// \ref reset() is called, thus only the modified parameters
kpeter@606:     /// have to be set again. See \ref reset() for examples.
kpeter@642:     /// However the underlying digraph must not be modified after this
kpeter@642:     /// class have been constructed, since it copies and extends the graph.
kpeter@606:     ///
kpeter@605:     /// \param pivot_rule The pivot rule that will be used during the
kpeter@605:     /// algorithm. For more information see \ref PivotRule.
kpeter@601:     ///
kpeter@640:     /// \return \c INFEASIBLE if no feasible flow exists,
kpeter@640:     /// \n \c OPTIMAL if the problem has optimal solution
kpeter@640:     /// (i.e. it is feasible and bounded), and the algorithm has found
kpeter@640:     /// optimal flow and node potentials (primal and dual solutions),
kpeter@640:     /// \n \c UNBOUNDED if the objective function of the problem is
kpeter@640:     /// unbounded, i.e. there is a directed cycle having negative total
kpeter@640:     /// cost and infinite upper bound.
kpeter@640:     ///
kpeter@640:     /// \see ProblemType, PivotRule
kpeter@640:     ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
kpeter@640:       if (!init()) return INFEASIBLE;
kpeter@640:       return start(pivot_rule);
kpeter@601:     }
kpeter@601: 
kpeter@606:     /// \brief Reset all the parameters that have been given before.
kpeter@606:     ///
kpeter@606:     /// This function resets all the paramaters that have been given
kpeter@609:     /// before using functions \ref lowerMap(), \ref upperMap(),
kpeter@642:     /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
kpeter@606:     ///
kpeter@606:     /// It is useful for multiple run() calls. If this function is not
kpeter@606:     /// used, all the parameters given before are kept for the next
kpeter@606:     /// \ref run() call.
kpeter@642:     /// However the underlying digraph must not be modified after this
kpeter@642:     /// class have been constructed, since it copies and extends the graph.
kpeter@606:     ///
kpeter@606:     /// For example,
kpeter@606:     /// \code
kpeter@606:     ///   NetworkSimplex<ListDigraph> ns(graph);
kpeter@606:     ///
kpeter@606:     ///   // First run
kpeter@640:     ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
kpeter@606:     ///     .supplyMap(sup).run();
kpeter@606:     ///
kpeter@606:     ///   // Run again with modified cost map (reset() is not called,
kpeter@606:     ///   // so only the cost map have to be set again)
kpeter@606:     ///   cost[e] += 100;
kpeter@606:     ///   ns.costMap(cost).run();
kpeter@606:     ///
kpeter@606:     ///   // Run again from scratch using reset()
kpeter@606:     ///   // (the lower bounds will be set to zero on all arcs)
kpeter@606:     ///   ns.reset();
kpeter@640:     ///   ns.upperMap(capacity).costMap(cost)
kpeter@606:     ///     .supplyMap(sup).run();
kpeter@606:     /// \endcode
kpeter@606:     ///
kpeter@606:     /// \return <tt>(*this)</tt>
kpeter@606:     NetworkSimplex& reset() {
kpeter@642:       for (int i = 0; i != _node_num; ++i) {
kpeter@642:         _supply[i] = 0;
kpeter@642:       }
kpeter@642:       for (int i = 0; i != _arc_num; ++i) {
kpeter@642:         _lower[i] = 0;
kpeter@642:         _upper[i] = INF;
kpeter@642:         _cost[i] = 1;
kpeter@642:       }
kpeter@642:       _have_lower = false;
kpeter@640:       _stype = GEQ;
kpeter@606:       return *this;
kpeter@606:     }
kpeter@606: 
kpeter@601:     /// @}
kpeter@601: 
kpeter@601:     /// \name Query Functions
kpeter@601:     /// The results of the algorithm can be obtained using these
kpeter@601:     /// functions.\n
kpeter@605:     /// The \ref run() function must be called before using them.
kpeter@605: 
kpeter@601:     /// @{
kpeter@601: 
kpeter@605:     /// \brief Return the total cost of the found flow.
kpeter@605:     ///
kpeter@605:     /// This function returns the total cost of the found flow.
kpeter@640:     /// Its complexity is O(e).
kpeter@605:     ///
kpeter@605:     /// \note The return type of the function can be specified as a
kpeter@605:     /// template parameter. For example,
kpeter@605:     /// \code
kpeter@605:     ///   ns.totalCost<double>();
kpeter@605:     /// \endcode
kpeter@607:     /// It is useful if the total cost cannot be stored in the \c Cost
kpeter@605:     /// type of the algorithm, which is the default return type of the
kpeter@605:     /// function.
kpeter@605:     ///
kpeter@605:     /// \pre \ref run() must be called before using this function.
kpeter@642:     template <typename Number>
kpeter@642:     Number totalCost() const {
kpeter@642:       Number c = 0;
kpeter@642:       for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@642:         int i = _arc_id[a];
kpeter@642:         c += Number(_flow[i]) * Number(_cost[i]);
kpeter@605:       }
kpeter@605:       return c;
kpeter@605:     }
kpeter@605: 
kpeter@605: #ifndef DOXYGEN
kpeter@607:     Cost totalCost() const {
kpeter@607:       return totalCost<Cost>();
kpeter@605:     }
kpeter@605: #endif
kpeter@605: 
kpeter@605:     /// \brief Return the flow on the given arc.
kpeter@605:     ///
kpeter@605:     /// This function returns the flow on the given arc.
kpeter@605:     ///
kpeter@605:     /// \pre \ref run() must be called before using this function.
kpeter@641:     Value flow(const Arc& a) const {
kpeter@642:       return _flow[_arc_id[a]];
kpeter@605:     }
kpeter@605: 
kpeter@642:     /// \brief Return the flow map (the primal solution).
kpeter@601:     ///
kpeter@642:     /// This function copies the flow value on each arc into the given
kpeter@642:     /// map. The \c Value type of the algorithm must be convertible to
kpeter@642:     /// the \c Value type of the map.
kpeter@601:     ///
kpeter@601:     /// \pre \ref run() must be called before using this function.
kpeter@642:     template <typename FlowMap>
kpeter@642:     void flowMap(FlowMap &map) const {
kpeter@642:       for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@642:         map.set(a, _flow[_arc_id[a]]);
kpeter@642:       }
kpeter@601:     }
kpeter@601: 
kpeter@605:     /// \brief Return the potential (dual value) of the given node.
kpeter@605:     ///
kpeter@605:     /// This function returns the potential (dual value) of the
kpeter@605:     /// given node.
kpeter@605:     ///
kpeter@605:     /// \pre \ref run() must be called before using this function.
kpeter@607:     Cost potential(const Node& n) const {
kpeter@642:       return _pi[_node_id[n]];
kpeter@605:     }
kpeter@605: 
kpeter@642:     /// \brief Return the potential map (the dual solution).
kpeter@601:     ///
kpeter@642:     /// This function copies the potential (dual value) of each node
kpeter@642:     /// into the given map.
kpeter@642:     /// The \c Cost type of the algorithm must be convertible to the
kpeter@642:     /// \c Value type of the map.
kpeter@601:     ///
kpeter@601:     /// \pre \ref run() must be called before using this function.
kpeter@642:     template <typename PotentialMap>
kpeter@642:     void potentialMap(PotentialMap &map) const {
kpeter@642:       for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@642:         map.set(n, _pi[_node_id[n]]);
kpeter@642:       }
kpeter@601:     }
kpeter@601: 
kpeter@601:     /// @}
kpeter@601: 
kpeter@601:   private:
kpeter@601: 
kpeter@601:     // Initialize internal data structures
kpeter@601:     bool init() {
kpeter@605:       if (_node_num == 0) return false;
kpeter@601: 
kpeter@642:       // Check the sum of supply values
kpeter@642:       _sum_supply = 0;
kpeter@642:       for (int i = 0; i != _node_num; ++i) {
kpeter@642:         _sum_supply += _supply[i];
kpeter@642:       }
alpar@643:       if ( !((_stype == GEQ && _sum_supply <= 0) ||
alpar@643:              (_stype == LEQ && _sum_supply >= 0)) ) return false;
kpeter@601: 
kpeter@642:       // Remove non-zero lower bounds
kpeter@642:       if (_have_lower) {
kpeter@642:         for (int i = 0; i != _arc_num; ++i) {
kpeter@642:           Value c = _lower[i];
kpeter@642:           if (c >= 0) {
kpeter@642:             _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
kpeter@642:           } else {
kpeter@642:             _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
kpeter@642:           }
kpeter@642:           _supply[_source[i]] -= c;
kpeter@642:           _supply[_target[i]] += c;
kpeter@642:         }
kpeter@642:       } else {
kpeter@642:         for (int i = 0; i != _arc_num; ++i) {
kpeter@642:           _cap[i] = _upper[i];
kpeter@642:         }
kpeter@605:       }
kpeter@601: 
kpeter@609:       // Initialize artifical cost
kpeter@640:       Cost ART_COST;
kpeter@609:       if (std::numeric_limits<Cost>::is_exact) {
kpeter@640:         ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
kpeter@609:       } else {
kpeter@640:         ART_COST = std::numeric_limits<Cost>::min();
kpeter@609:         for (int i = 0; i != _arc_num; ++i) {
kpeter@640:           if (_cost[i] > ART_COST) ART_COST = _cost[i];
kpeter@609:         }
kpeter@640:         ART_COST = (ART_COST + 1) * _node_num;
kpeter@609:       }
kpeter@609: 
kpeter@642:       // Initialize arc maps
kpeter@642:       for (int i = 0; i != _arc_num; ++i) {
kpeter@642:         _flow[i] = 0;
kpeter@642:         _state[i] = STATE_LOWER;
kpeter@642:       }
kpeter@642:       
kpeter@601:       // Set data for the artificial root node
kpeter@601:       _root = _node_num;
kpeter@601:       _parent[_root] = -1;
kpeter@601:       _pred[_root] = -1;
kpeter@601:       _thread[_root] = 0;
kpeter@604:       _rev_thread[0] = _root;
kpeter@642:       _succ_num[_root] = _node_num + 1;
kpeter@604:       _last_succ[_root] = _root - 1;
kpeter@640:       _supply[_root] = -_sum_supply;
kpeter@642:       _pi[_root] = _sum_supply < 0 ? -ART_COST : ART_COST;
kpeter@601: 
kpeter@601:       // Add artificial arcs and initialize the spanning tree data structure
kpeter@601:       for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
kpeter@642:         _parent[u] = _root;
kpeter@642:         _pred[u] = e;
kpeter@601:         _thread[u] = u + 1;
kpeter@604:         _rev_thread[u + 1] = u;
kpeter@604:         _succ_num[u] = 1;
kpeter@604:         _last_succ[u] = u;
kpeter@640:         _cost[e] = ART_COST;
kpeter@640:         _cap[e] = INF;
kpeter@606:         _state[e] = STATE_TREE;
kpeter@640:         if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
kpeter@601:           _flow[e] = _supply[u];
kpeter@601:           _forward[u] = true;
kpeter@640:           _pi[u] = -ART_COST + _pi[_root];
kpeter@601:         } else {
kpeter@601:           _flow[e] = -_supply[u];
kpeter@601:           _forward[u] = false;
kpeter@640:           _pi[u] = ART_COST + _pi[_root];
kpeter@601:         }
kpeter@601:       }
kpeter@601: 
kpeter@601:       return true;
kpeter@601:     }
kpeter@601: 
kpeter@601:     // Find the join node
kpeter@601:     void findJoinNode() {
kpeter@603:       int u = _source[in_arc];
kpeter@603:       int v = _target[in_arc];
kpeter@601:       while (u != v) {
kpeter@604:         if (_succ_num[u] < _succ_num[v]) {
kpeter@604:           u = _parent[u];
kpeter@604:         } else {
kpeter@604:           v = _parent[v];
kpeter@604:         }
kpeter@601:       }
kpeter@601:       join = u;
kpeter@601:     }
kpeter@601: 
kpeter@601:     // Find the leaving arc of the cycle and returns true if the
kpeter@601:     // leaving arc is not the same as the entering arc
kpeter@601:     bool findLeavingArc() {
kpeter@601:       // Initialize first and second nodes according to the direction
kpeter@601:       // of the cycle
kpeter@603:       if (_state[in_arc] == STATE_LOWER) {
kpeter@603:         first  = _source[in_arc];
kpeter@603:         second = _target[in_arc];
kpeter@601:       } else {
kpeter@603:         first  = _target[in_arc];
kpeter@603:         second = _source[in_arc];
kpeter@601:       }
kpeter@603:       delta = _cap[in_arc];
kpeter@601:       int result = 0;
kpeter@641:       Value d;
kpeter@601:       int e;
kpeter@601: 
kpeter@601:       // Search the cycle along the path form the first node to the root
kpeter@601:       for (int u = first; u != join; u = _parent[u]) {
kpeter@601:         e = _pred[u];
kpeter@640:         d = _forward[u] ?
kpeter@640:           _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
kpeter@601:         if (d < delta) {
kpeter@601:           delta = d;
kpeter@601:           u_out = u;
kpeter@601:           result = 1;
kpeter@601:         }
kpeter@601:       }
kpeter@601:       // Search the cycle along the path form the second node to the root
kpeter@601:       for (int u = second; u != join; u = _parent[u]) {
kpeter@601:         e = _pred[u];
kpeter@640:         d = _forward[u] ? 
kpeter@640:           (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
kpeter@601:         if (d <= delta) {
kpeter@601:           delta = d;
kpeter@601:           u_out = u;
kpeter@601:           result = 2;
kpeter@601:         }
kpeter@601:       }
kpeter@601: 
kpeter@601:       if (result == 1) {
kpeter@601:         u_in = first;
kpeter@601:         v_in = second;
kpeter@601:       } else {
kpeter@601:         u_in = second;
kpeter@601:         v_in = first;
kpeter@601:       }
kpeter@601:       return result != 0;
kpeter@601:     }
kpeter@601: 
kpeter@601:     // Change _flow and _state vectors
kpeter@601:     void changeFlow(bool change) {
kpeter@601:       // Augment along the cycle
kpeter@601:       if (delta > 0) {
kpeter@641:         Value val = _state[in_arc] * delta;
kpeter@603:         _flow[in_arc] += val;
kpeter@603:         for (int u = _source[in_arc]; u != join; u = _parent[u]) {
kpeter@601:           _flow[_pred[u]] += _forward[u] ? -val : val;
kpeter@601:         }
kpeter@603:         for (int u = _target[in_arc]; u != join; u = _parent[u]) {
kpeter@601:           _flow[_pred[u]] += _forward[u] ? val : -val;
kpeter@601:         }
kpeter@601:       }
kpeter@601:       // Update the state of the entering and leaving arcs
kpeter@601:       if (change) {
kpeter@603:         _state[in_arc] = STATE_TREE;
kpeter@601:         _state[_pred[u_out]] =
kpeter@601:           (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
kpeter@601:       } else {
kpeter@603:         _state[in_arc] = -_state[in_arc];
kpeter@601:       }
kpeter@601:     }
kpeter@601: 
kpeter@604:     // Update the tree structure
kpeter@604:     void updateTreeStructure() {
kpeter@604:       int u, w;
kpeter@604:       int old_rev_thread = _rev_thread[u_out];
kpeter@604:       int old_succ_num = _succ_num[u_out];
kpeter@604:       int old_last_succ = _last_succ[u_out];
kpeter@601:       v_out = _parent[u_out];
kpeter@601: 
kpeter@604:       u = _last_succ[u_in];  // the last successor of u_in
kpeter@604:       right = _thread[u];    // the node after it
kpeter@604: 
kpeter@604:       // Handle the case when old_rev_thread equals to v_in
kpeter@604:       // (it also means that join and v_out coincide)
kpeter@604:       if (old_rev_thread == v_in) {
kpeter@604:         last = _thread[_last_succ[u_out]];
kpeter@604:       } else {
kpeter@604:         last = _thread[v_in];
kpeter@601:       }
kpeter@601: 
kpeter@604:       // Update _thread and _parent along the stem nodes (i.e. the nodes
kpeter@604:       // between u_in and u_out, whose parent have to be changed)
kpeter@601:       _thread[v_in] = stem = u_in;
kpeter@604:       _dirty_revs.clear();
kpeter@604:       _dirty_revs.push_back(v_in);
kpeter@601:       par_stem = v_in;
kpeter@601:       while (stem != u_out) {
kpeter@604:         // Insert the next stem node into the thread list
kpeter@604:         new_stem = _parent[stem];
kpeter@604:         _thread[u] = new_stem;
kpeter@604:         _dirty_revs.push_back(u);
kpeter@601: 
kpeter@604:         // Remove the subtree of stem from the thread list
kpeter@604:         w = _rev_thread[stem];
kpeter@604:         _thread[w] = right;
kpeter@604:         _rev_thread[right] = w;
kpeter@601: 
kpeter@604:         // Change the parent node and shift stem nodes
kpeter@601:         _parent[stem] = par_stem;
kpeter@601:         par_stem = stem;
kpeter@601:         stem = new_stem;
kpeter@601: 
kpeter@604:         // Update u and right
kpeter@604:         u = _last_succ[stem] == _last_succ[par_stem] ?
kpeter@604:           _rev_thread[par_stem] : _last_succ[stem];
kpeter@601:         right = _thread[u];
kpeter@601:       }
kpeter@601:       _parent[u_out] = par_stem;
kpeter@601:       _thread[u] = last;
kpeter@604:       _rev_thread[last] = u;
kpeter@604:       _last_succ[u_out] = u;
kpeter@601: 
kpeter@604:       // Remove the subtree of u_out from the thread list except for
kpeter@604:       // the case when old_rev_thread equals to v_in
kpeter@604:       // (it also means that join and v_out coincide)
kpeter@604:       if (old_rev_thread != v_in) {
kpeter@604:         _thread[old_rev_thread] = right;
kpeter@604:         _rev_thread[right] = old_rev_thread;
kpeter@604:       }
kpeter@604: 
kpeter@604:       // Update _rev_thread using the new _thread values
kpeter@604:       for (int i = 0; i < int(_dirty_revs.size()); ++i) {
kpeter@604:         u = _dirty_revs[i];
kpeter@604:         _rev_thread[_thread[u]] = u;
kpeter@604:       }
kpeter@604: 
kpeter@604:       // Update _pred, _forward, _last_succ and _succ_num for the
kpeter@604:       // stem nodes from u_out to u_in
kpeter@604:       int tmp_sc = 0, tmp_ls = _last_succ[u_out];
kpeter@604:       u = u_out;
kpeter@604:       while (u != u_in) {
kpeter@604:         w = _parent[u];
kpeter@604:         _pred[u] = _pred[w];
kpeter@604:         _forward[u] = !_forward[w];
kpeter@604:         tmp_sc += _succ_num[u] - _succ_num[w];
kpeter@604:         _succ_num[u] = tmp_sc;
kpeter@604:         _last_succ[w] = tmp_ls;
kpeter@604:         u = w;
kpeter@604:       }
kpeter@604:       _pred[u_in] = in_arc;
kpeter@604:       _forward[u_in] = (u_in == _source[in_arc]);
kpeter@604:       _succ_num[u_in] = old_succ_num;
kpeter@604: 
kpeter@604:       // Set limits for updating _last_succ form v_in and v_out
kpeter@604:       // towards the root
kpeter@604:       int up_limit_in = -1;
kpeter@604:       int up_limit_out = -1;
kpeter@604:       if (_last_succ[join] == v_in) {
kpeter@604:         up_limit_out = join;
kpeter@601:       } else {
kpeter@604:         up_limit_in = join;
kpeter@604:       }
kpeter@604: 
kpeter@604:       // Update _last_succ from v_in towards the root
kpeter@604:       for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
kpeter@604:            u = _parent[u]) {
kpeter@604:         _last_succ[u] = _last_succ[u_out];
kpeter@604:       }
kpeter@604:       // Update _last_succ from v_out towards the root
kpeter@604:       if (join != old_rev_thread && v_in != old_rev_thread) {
kpeter@604:         for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
kpeter@604:              u = _parent[u]) {
kpeter@604:           _last_succ[u] = old_rev_thread;
kpeter@604:         }
kpeter@604:       } else {
kpeter@604:         for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
kpeter@604:              u = _parent[u]) {
kpeter@604:           _last_succ[u] = _last_succ[u_out];
kpeter@604:         }
kpeter@604:       }
kpeter@604: 
kpeter@604:       // Update _succ_num from v_in to join
kpeter@604:       for (u = v_in; u != join; u = _parent[u]) {
kpeter@604:         _succ_num[u] += old_succ_num;
kpeter@604:       }
kpeter@604:       // Update _succ_num from v_out to join
kpeter@604:       for (u = v_out; u != join; u = _parent[u]) {
kpeter@604:         _succ_num[u] -= old_succ_num;
kpeter@601:       }
kpeter@601:     }
kpeter@601: 
kpeter@604:     // Update potentials
kpeter@604:     void updatePotential() {
kpeter@607:       Cost sigma = _forward[u_in] ?
kpeter@601:         _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
kpeter@601:         _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
kpeter@608:       // Update potentials in the subtree, which has been moved
kpeter@608:       int end = _thread[_last_succ[u_in]];
kpeter@608:       for (int u = u_in; u != end; u = _thread[u]) {
kpeter@608:         _pi[u] += sigma;
kpeter@601:       }
kpeter@601:     }
kpeter@601: 
kpeter@601:     // Execute the algorithm
kpeter@640:     ProblemType start(PivotRule pivot_rule) {
kpeter@601:       // Select the pivot rule implementation
kpeter@601:       switch (pivot_rule) {
kpeter@605:         case FIRST_ELIGIBLE:
kpeter@601:           return start<FirstEligiblePivotRule>();
kpeter@605:         case BEST_ELIGIBLE:
kpeter@601:           return start<BestEligiblePivotRule>();
kpeter@605:         case BLOCK_SEARCH:
kpeter@601:           return start<BlockSearchPivotRule>();
kpeter@605:         case CANDIDATE_LIST:
kpeter@601:           return start<CandidateListPivotRule>();
kpeter@605:         case ALTERING_LIST:
kpeter@601:           return start<AlteringListPivotRule>();
kpeter@601:       }
kpeter@640:       return INFEASIBLE; // avoid warning
kpeter@601:     }
kpeter@601: 
kpeter@605:     template <typename PivotRuleImpl>
kpeter@640:     ProblemType start() {
kpeter@605:       PivotRuleImpl pivot(*this);
kpeter@601: 
kpeter@605:       // Execute the Network Simplex algorithm
kpeter@601:       while (pivot.findEnteringArc()) {
kpeter@601:         findJoinNode();
kpeter@601:         bool change = findLeavingArc();
kpeter@640:         if (delta >= INF) return UNBOUNDED;
kpeter@601:         changeFlow(change);
kpeter@601:         if (change) {
kpeter@604:           updateTreeStructure();
kpeter@604:           updatePotential();
kpeter@601:         }
kpeter@601:       }
kpeter@640:       
kpeter@640:       // Check feasibility
kpeter@640:       if (_sum_supply < 0) {
kpeter@640:         for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
kpeter@640:           if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
kpeter@640:         }
kpeter@640:       }
kpeter@640:       else if (_sum_supply > 0) {
kpeter@640:         for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
kpeter@640:           if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
kpeter@640:         }
kpeter@640:       }
kpeter@640:       else {
kpeter@640:         for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
kpeter@640:           if (_flow[e] != 0) return INFEASIBLE;
kpeter@640:         }
kpeter@640:       }
kpeter@601: 
kpeter@642:       // Transform the solution and the supply map to the original form
kpeter@642:       if (_have_lower) {
kpeter@601:         for (int i = 0; i != _arc_num; ++i) {
kpeter@642:           Value c = _lower[i];
kpeter@642:           if (c != 0) {
kpeter@642:             _flow[i] += c;
kpeter@642:             _supply[_source[i]] += c;
kpeter@642:             _supply[_target[i]] -= c;
kpeter@642:           }
kpeter@601:         }
kpeter@601:       }
kpeter@601: 
kpeter@640:       return OPTIMAL;
kpeter@601:     }
kpeter@601: 
kpeter@601:   }; //class NetworkSimplex
kpeter@601: 
kpeter@601:   ///@}
kpeter@601: 
kpeter@601: } //namespace lemon
kpeter@601: 
kpeter@601: #endif //LEMON_NETWORK_SIMPLEX_H