kpeter@648: /* -*- mode: C++; indent-tabs-mode: nil; -*- kpeter@648: * kpeter@648: * This file is a part of LEMON, a generic C++ optimization library. kpeter@648: * alpar@956: * Copyright (C) 2003-2010 kpeter@648: * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport kpeter@648: * (Egervary Research Group on Combinatorial Optimization, EGRES). kpeter@648: * kpeter@648: * Permission to use, modify and distribute this software is granted kpeter@648: * provided that this copyright notice appears in all copies. For kpeter@648: * precise terms see the accompanying LICENSE file. kpeter@648: * kpeter@648: * This software is provided "AS IS" with no warranty of any kind, kpeter@648: * express or implied, and with no claim as to its suitability for any kpeter@648: * purpose. kpeter@648: * kpeter@648: */ kpeter@648: kpeter@648: #ifndef LEMON_NETWORK_SIMPLEX_H kpeter@648: #define LEMON_NETWORK_SIMPLEX_H kpeter@648: kpeter@710: /// \ingroup min_cost_flow_algs kpeter@648: /// kpeter@648: /// \file kpeter@652: /// \brief Network Simplex algorithm for finding a minimum cost flow. kpeter@648: kpeter@648: #include kpeter@648: #include kpeter@648: #include kpeter@648: kpeter@650: #include kpeter@648: #include kpeter@648: kpeter@648: namespace lemon { kpeter@648: kpeter@710: /// \addtogroup min_cost_flow_algs kpeter@648: /// @{ kpeter@648: kpeter@652: /// \brief Implementation of the primal Network Simplex algorithm kpeter@648: /// for finding a \ref min_cost_flow "minimum cost flow". kpeter@648: /// kpeter@652: /// \ref NetworkSimplex implements the primal Network Simplex algorithm kpeter@802: /// for finding a \ref min_cost_flow "minimum cost flow" kpeter@802: /// \ref amo93networkflows, \ref dantzig63linearprog, kpeter@802: /// \ref kellyoneill91netsimplex. kpeter@878: /// This algorithm is a highly efficient specialized version of the kpeter@878: /// linear programming simplex method directly for the minimum cost kpeter@878: /// flow problem. kpeter@653: /// kpeter@1023: /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest kpeter@1165: /// implementations available in LEMON for solving this problem. kpeter@1165: /// (For more information, see \ref min_cost_flow_algs "the module page".) kpeter@1023: /// Furthermore, this class supports both directions of the supply/demand kpeter@1023: /// inequality constraints. For more information, see \ref SupplyType. kpeter@687: /// kpeter@687: /// Most of the parameters of the problem (except for the digraph) kpeter@687: /// can be given using separate functions, and the algorithm can be kpeter@687: /// executed using the \ref run() function. If some parameters are not kpeter@687: /// specified, then default values will be used. kpeter@648: /// kpeter@652: /// \tparam GR The digraph type the algorithm runs on. kpeter@878: /// \tparam V The number type used for flow amounts, capacity bounds kpeter@833: /// and supply values in the algorithm. By default, it is \c int. kpeter@878: /// \tparam C The number type used for costs and potentials in the kpeter@833: /// algorithm. By default, it is the same as \c V. kpeter@648: /// kpeter@1025: /// \warning Both \c V and \c C must be signed number types. kpeter@1025: /// \warning All input data (capacities, supply values, and costs) must kpeter@655: /// be integer. kpeter@648: /// kpeter@652: /// \note %NetworkSimplex provides five different pivot rule kpeter@656: /// implementations, from which the most efficient one is used kpeter@833: /// by default. For more information, see \ref PivotRule. kpeter@688: template kpeter@648: class NetworkSimplex kpeter@648: { kpeter@652: public: kpeter@648: kpeter@689: /// The type of the flow amounts, capacity bounds and supply values kpeter@688: typedef V Value; kpeter@689: /// The type of the arc costs kpeter@654: typedef C Cost; kpeter@652: kpeter@652: public: kpeter@652: kpeter@687: /// \brief Problem type constants for the \c run() function. kpeter@652: /// kpeter@687: /// Enum type containing the problem type constants that can be kpeter@687: /// returned by the \ref run() function of the algorithm. kpeter@687: enum ProblemType { kpeter@687: /// The problem has no feasible solution (flow). kpeter@687: INFEASIBLE, kpeter@687: /// The problem has optimal solution (i.e. it is feasible and kpeter@687: /// bounded), and the algorithm has found optimal flow and node kpeter@687: /// potentials (primal and dual solutions). kpeter@687: OPTIMAL, kpeter@687: /// The objective function of the problem is unbounded, i.e. kpeter@687: /// there is a directed cycle having negative total cost and kpeter@687: /// infinite upper bound. kpeter@687: UNBOUNDED kpeter@687: }; alpar@956: kpeter@687: /// \brief Constants for selecting the type of the supply constraints. kpeter@687: /// kpeter@687: /// Enum type containing constants for selecting the supply type, kpeter@687: /// i.e. the direction of the inequalities in the supply/demand kpeter@687: /// constraints of the \ref min_cost_flow "minimum cost flow problem". kpeter@687: /// kpeter@710: /// The default supply type is \c GEQ, the \c LEQ type can be kpeter@710: /// selected using \ref supplyType(). kpeter@710: /// The equality form is a special case of both supply types. kpeter@687: enum SupplyType { kpeter@687: /// This option means that there are "greater or equal" kpeter@710: /// supply/demand constraints in the definition of the problem. kpeter@687: GEQ, kpeter@687: /// This option means that there are "less or equal" kpeter@710: /// supply/demand constraints in the definition of the problem. kpeter@710: LEQ kpeter@687: }; alpar@956: kpeter@687: /// \brief Constants for selecting the pivot rule. kpeter@687: /// kpeter@687: /// Enum type containing constants for selecting the pivot rule for kpeter@687: /// the \ref run() function. kpeter@687: /// kpeter@1136: /// \ref NetworkSimplex provides five different implementations for kpeter@1136: /// the pivot strategy that significantly affects the running time kpeter@652: /// of the algorithm. kpeter@1136: /// According to experimental tests conducted on various problem kpeter@1136: /// instances, \ref BLOCK_SEARCH "Block Search" and kpeter@1136: /// \ref ALTERING_LIST "Altering Candidate List" rules turned out kpeter@1136: /// to be the most efficient. kpeter@1136: /// Since \ref BLOCK_SEARCH "Block Search" is a simpler strategy that kpeter@1136: /// seemed to be slightly more robust, it is used by default. kpeter@1136: /// However, another pivot rule can easily be selected using the kpeter@1136: /// \ref run() function with the proper parameter. kpeter@652: enum PivotRule { kpeter@652: kpeter@833: /// The \e First \e Eligible pivot rule. kpeter@652: /// The next eligible arc is selected in a wraparound fashion kpeter@652: /// in every iteration. kpeter@652: FIRST_ELIGIBLE, kpeter@652: kpeter@833: /// The \e Best \e Eligible pivot rule. kpeter@652: /// The best eligible arc is selected in every iteration. kpeter@652: BEST_ELIGIBLE, kpeter@652: kpeter@833: /// The \e Block \e Search pivot rule. kpeter@652: /// A specified number of arcs are examined in every iteration kpeter@652: /// in a wraparound fashion and the best eligible arc is selected kpeter@652: /// from this block. kpeter@652: BLOCK_SEARCH, kpeter@652: kpeter@833: /// The \e Candidate \e List pivot rule. kpeter@652: /// In a major iteration a candidate list is built from eligible arcs kpeter@652: /// in a wraparound fashion and in the following minor iterations kpeter@652: /// the best eligible arc is selected from this list. kpeter@652: CANDIDATE_LIST, kpeter@652: kpeter@833: /// The \e Altering \e Candidate \e List pivot rule. kpeter@652: /// It is a modified version of the Candidate List method. kpeter@1136: /// It keeps only a few of the best eligible arcs from the former kpeter@652: /// candidate list and extends this list in every iteration. kpeter@652: ALTERING_LIST kpeter@652: }; alpar@956: kpeter@652: private: kpeter@652: kpeter@652: TEMPLATE_DIGRAPH_TYPEDEFS(GR); kpeter@652: kpeter@648: typedef std::vector IntVector; kpeter@689: typedef std::vector ValueVector; kpeter@654: typedef std::vector CostVector; kpeter@990: typedef std::vector CharVector; kpeter@1023: // Note: vector is used instead of vector and kpeter@990: // vector for efficiency reasons kpeter@648: kpeter@648: // State constants for arcs kpeter@936: enum ArcState { kpeter@648: STATE_UPPER = -1, kpeter@648: STATE_TREE = 0, kpeter@648: STATE_LOWER = 1 kpeter@648: }; kpeter@648: kpeter@990: // Direction constants for tree arcs kpeter@990: enum ArcDirection { kpeter@990: DIR_DOWN = -1, kpeter@990: DIR_UP = 1 kpeter@990: }; kpeter@936: kpeter@648: private: kpeter@648: kpeter@652: // Data related to the underlying digraph kpeter@652: const GR &_graph; kpeter@652: int _node_num; kpeter@652: int _arc_num; kpeter@710: int _all_arc_num; kpeter@710: int _search_arc_num; kpeter@652: kpeter@652: // Parameters of the problem kpeter@689: bool _have_lower; kpeter@687: SupplyType _stype; kpeter@688: Value _sum_supply; kpeter@648: kpeter@652: // Data structures for storing the digraph kpeter@650: IntNodeMap _node_id; kpeter@689: IntArcMap _arc_id; kpeter@650: IntVector _source; kpeter@650: IntVector _target; kpeter@898: bool _arc_mixing; kpeter@650: kpeter@652: // Node and arc data kpeter@689: ValueVector _lower; kpeter@689: ValueVector _upper; kpeter@689: ValueVector _cap; kpeter@654: CostVector _cost; kpeter@689: ValueVector _supply; kpeter@689: ValueVector _flow; kpeter@654: CostVector _pi; kpeter@648: kpeter@650: // Data for storing the spanning tree structure kpeter@648: IntVector _parent; kpeter@648: IntVector _pred; kpeter@648: IntVector _thread; kpeter@651: IntVector _rev_thread; kpeter@651: IntVector _succ_num; kpeter@651: IntVector _last_succ; kpeter@990: CharVector _pred_dir; kpeter@990: CharVector _state; kpeter@651: IntVector _dirty_revs; kpeter@648: int _root; kpeter@648: kpeter@648: // Temporary data used in the current pivot iteration kpeter@650: int in_arc, join, u_in, v_in, u_out, v_out; kpeter@688: Value delta; kpeter@648: kpeter@877: const Value MAX; kpeter@710: kpeter@687: public: alpar@956: kpeter@687: /// \brief Constant for infinite upper bounds (capacities). kpeter@687: /// kpeter@687: /// Constant for infinite upper bounds (capacities). kpeter@688: /// It is \c std::numeric_limits::infinity() if available, kpeter@688: /// \c std::numeric_limits::max() otherwise. kpeter@688: const Value INF; kpeter@687: kpeter@648: private: kpeter@648: kpeter@652: // Implementation of the First Eligible pivot rule kpeter@648: class FirstEligiblePivotRule kpeter@648: { kpeter@648: private: kpeter@648: kpeter@648: // References to the NetworkSimplex class kpeter@648: const IntVector &_source; kpeter@648: const IntVector &_target; kpeter@654: const CostVector &_cost; kpeter@990: const CharVector &_state; kpeter@654: const CostVector &_pi; kpeter@648: int &_in_arc; kpeter@710: int _search_arc_num; kpeter@648: kpeter@648: // Pivot rule data kpeter@648: int _next_arc; kpeter@648: kpeter@648: public: kpeter@648: kpeter@652: // Constructor kpeter@648: FirstEligiblePivotRule(NetworkSimplex &ns) : kpeter@650: _source(ns._source), _target(ns._target), kpeter@648: _cost(ns._cost), _state(ns._state), _pi(ns._pi), kpeter@710: _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num), kpeter@710: _next_arc(0) kpeter@648: {} kpeter@648: kpeter@652: // Find next entering arc kpeter@648: bool findEnteringArc() { kpeter@654: Cost c; kpeter@910: for (int e = _next_arc; e != _search_arc_num; ++e) { kpeter@648: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@648: if (c < 0) { kpeter@648: _in_arc = e; kpeter@648: _next_arc = e + 1; kpeter@648: return true; kpeter@648: } kpeter@648: } kpeter@910: for (int e = 0; e != _next_arc; ++e) { kpeter@648: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@648: if (c < 0) { kpeter@648: _in_arc = e; kpeter@648: _next_arc = e + 1; kpeter@648: return true; kpeter@648: } kpeter@648: } kpeter@648: return false; kpeter@648: } kpeter@648: kpeter@648: }; //class FirstEligiblePivotRule kpeter@648: kpeter@648: kpeter@652: // Implementation of the Best Eligible pivot rule kpeter@648: class BestEligiblePivotRule kpeter@648: { kpeter@648: private: kpeter@648: kpeter@648: // References to the NetworkSimplex class kpeter@648: const IntVector &_source; kpeter@648: const IntVector &_target; kpeter@654: const CostVector &_cost; kpeter@990: const CharVector &_state; kpeter@654: const CostVector &_pi; kpeter@648: int &_in_arc; kpeter@710: int _search_arc_num; kpeter@648: kpeter@648: public: kpeter@648: kpeter@652: // Constructor kpeter@648: BestEligiblePivotRule(NetworkSimplex &ns) : kpeter@650: _source(ns._source), _target(ns._target), kpeter@648: _cost(ns._cost), _state(ns._state), _pi(ns._pi), kpeter@710: _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num) kpeter@648: {} kpeter@648: kpeter@652: // Find next entering arc kpeter@648: bool findEnteringArc() { kpeter@654: Cost c, min = 0; kpeter@910: for (int e = 0; e != _search_arc_num; ++e) { kpeter@648: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@648: if (c < min) { kpeter@648: min = c; kpeter@648: _in_arc = e; kpeter@648: } kpeter@648: } kpeter@648: return min < 0; kpeter@648: } kpeter@648: kpeter@648: }; //class BestEligiblePivotRule kpeter@648: kpeter@648: kpeter@652: // Implementation of the Block Search pivot rule kpeter@648: class BlockSearchPivotRule kpeter@648: { kpeter@648: private: kpeter@648: kpeter@648: // References to the NetworkSimplex class kpeter@648: const IntVector &_source; kpeter@648: const IntVector &_target; kpeter@654: const CostVector &_cost; kpeter@990: const CharVector &_state; kpeter@654: const CostVector &_pi; kpeter@648: int &_in_arc; kpeter@710: int _search_arc_num; kpeter@648: kpeter@648: // Pivot rule data kpeter@648: int _block_size; kpeter@648: int _next_arc; kpeter@648: kpeter@648: public: kpeter@648: kpeter@652: // Constructor kpeter@648: BlockSearchPivotRule(NetworkSimplex &ns) : kpeter@650: _source(ns._source), _target(ns._target), kpeter@648: _cost(ns._cost), _state(ns._state), _pi(ns._pi), kpeter@710: _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num), kpeter@710: _next_arc(0) kpeter@648: { kpeter@648: // The main parameters of the pivot rule kpeter@910: const double BLOCK_SIZE_FACTOR = 1.0; kpeter@648: const int MIN_BLOCK_SIZE = 10; kpeter@648: alpar@659: _block_size = std::max( int(BLOCK_SIZE_FACTOR * kpeter@710: std::sqrt(double(_search_arc_num))), kpeter@648: MIN_BLOCK_SIZE ); kpeter@648: } kpeter@648: kpeter@652: // Find next entering arc kpeter@648: bool findEnteringArc() { kpeter@654: Cost c, min = 0; kpeter@648: int cnt = _block_size; kpeter@774: int e; kpeter@910: for (e = _next_arc; e != _search_arc_num; ++e) { kpeter@648: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@648: if (c < min) { kpeter@648: min = c; kpeter@774: _in_arc = e; kpeter@648: } kpeter@648: if (--cnt == 0) { kpeter@774: if (min < 0) goto search_end; kpeter@648: cnt = _block_size; kpeter@648: } kpeter@648: } kpeter@910: for (e = 0; e != _next_arc; ++e) { kpeter@774: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@774: if (c < min) { kpeter@774: min = c; kpeter@774: _in_arc = e; kpeter@774: } kpeter@774: if (--cnt == 0) { kpeter@774: if (min < 0) goto search_end; kpeter@774: cnt = _block_size; kpeter@648: } kpeter@648: } kpeter@648: if (min >= 0) return false; kpeter@774: kpeter@774: search_end: kpeter@648: _next_arc = e; kpeter@648: return true; kpeter@648: } kpeter@648: kpeter@648: }; //class BlockSearchPivotRule kpeter@648: kpeter@648: kpeter@652: // Implementation of the Candidate List pivot rule kpeter@648: class CandidateListPivotRule kpeter@648: { kpeter@648: private: kpeter@648: kpeter@648: // References to the NetworkSimplex class kpeter@648: const IntVector &_source; kpeter@648: const IntVector &_target; kpeter@654: const CostVector &_cost; kpeter@990: const CharVector &_state; kpeter@654: const CostVector &_pi; kpeter@648: int &_in_arc; kpeter@710: int _search_arc_num; kpeter@648: kpeter@648: // Pivot rule data kpeter@648: IntVector _candidates; kpeter@648: int _list_length, _minor_limit; kpeter@648: int _curr_length, _minor_count; kpeter@648: int _next_arc; kpeter@648: kpeter@648: public: kpeter@648: kpeter@648: /// Constructor kpeter@648: CandidateListPivotRule(NetworkSimplex &ns) : kpeter@650: _source(ns._source), _target(ns._target), kpeter@648: _cost(ns._cost), _state(ns._state), _pi(ns._pi), kpeter@710: _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num), kpeter@710: _next_arc(0) kpeter@648: { kpeter@648: // The main parameters of the pivot rule kpeter@774: const double LIST_LENGTH_FACTOR = 0.25; kpeter@648: const int MIN_LIST_LENGTH = 10; kpeter@648: const double MINOR_LIMIT_FACTOR = 0.1; kpeter@648: const int MIN_MINOR_LIMIT = 3; kpeter@648: alpar@659: _list_length = std::max( int(LIST_LENGTH_FACTOR * kpeter@710: std::sqrt(double(_search_arc_num))), kpeter@648: MIN_LIST_LENGTH ); kpeter@648: _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length), kpeter@648: MIN_MINOR_LIMIT ); kpeter@648: _curr_length = _minor_count = 0; kpeter@648: _candidates.resize(_list_length); kpeter@648: } kpeter@648: kpeter@648: /// Find next entering arc kpeter@648: bool findEnteringArc() { kpeter@654: Cost min, c; kpeter@774: int e; kpeter@648: if (_curr_length > 0 && _minor_count < _minor_limit) { kpeter@648: // Minor iteration: select the best eligible arc from the kpeter@648: // current candidate list kpeter@648: ++_minor_count; kpeter@648: min = 0; kpeter@648: for (int i = 0; i < _curr_length; ++i) { kpeter@648: e = _candidates[i]; kpeter@648: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@648: if (c < min) { kpeter@648: min = c; kpeter@774: _in_arc = e; kpeter@648: } kpeter@774: else if (c >= 0) { kpeter@648: _candidates[i--] = _candidates[--_curr_length]; kpeter@648: } kpeter@648: } kpeter@774: if (min < 0) return true; kpeter@648: } kpeter@648: kpeter@648: // Major iteration: build a new candidate list kpeter@648: min = 0; kpeter@648: _curr_length = 0; kpeter@910: for (e = _next_arc; e != _search_arc_num; ++e) { kpeter@648: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@648: if (c < 0) { kpeter@648: _candidates[_curr_length++] = e; kpeter@648: if (c < min) { kpeter@648: min = c; kpeter@774: _in_arc = e; kpeter@648: } kpeter@774: if (_curr_length == _list_length) goto search_end; kpeter@648: } kpeter@648: } kpeter@910: for (e = 0; e != _next_arc; ++e) { kpeter@774: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@774: if (c < 0) { kpeter@774: _candidates[_curr_length++] = e; kpeter@774: if (c < min) { kpeter@774: min = c; kpeter@774: _in_arc = e; kpeter@648: } kpeter@774: if (_curr_length == _list_length) goto search_end; kpeter@648: } kpeter@648: } kpeter@648: if (_curr_length == 0) return false; alpar@956: alpar@956: search_end: kpeter@648: _minor_count = 1; kpeter@648: _next_arc = e; kpeter@648: return true; kpeter@648: } kpeter@648: kpeter@648: }; //class CandidateListPivotRule kpeter@648: kpeter@648: kpeter@652: // Implementation of the Altering Candidate List pivot rule kpeter@648: class AlteringListPivotRule kpeter@648: { kpeter@648: private: kpeter@648: kpeter@648: // References to the NetworkSimplex class kpeter@648: const IntVector &_source; kpeter@648: const IntVector &_target; kpeter@654: const CostVector &_cost; kpeter@990: const CharVector &_state; kpeter@654: const CostVector &_pi; kpeter@648: int &_in_arc; kpeter@710: int _search_arc_num; kpeter@648: kpeter@648: // Pivot rule data kpeter@648: int _block_size, _head_length, _curr_length; kpeter@648: int _next_arc; kpeter@648: IntVector _candidates; kpeter@654: CostVector _cand_cost; kpeter@648: kpeter@648: // Functor class to compare arcs during sort of the candidate list kpeter@648: class SortFunc kpeter@648: { kpeter@648: private: kpeter@654: const CostVector &_map; kpeter@648: public: kpeter@654: SortFunc(const CostVector &map) : _map(map) {} kpeter@648: bool operator()(int left, int right) { kpeter@1136: return _map[left] < _map[right]; kpeter@648: } kpeter@648: }; kpeter@648: kpeter@648: SortFunc _sort_func; kpeter@648: kpeter@648: public: kpeter@648: kpeter@652: // Constructor kpeter@648: AlteringListPivotRule(NetworkSimplex &ns) : kpeter@650: _source(ns._source), _target(ns._target), kpeter@648: _cost(ns._cost), _state(ns._state), _pi(ns._pi), kpeter@710: _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num), kpeter@710: _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost) kpeter@648: { kpeter@648: // The main parameters of the pivot rule kpeter@774: const double BLOCK_SIZE_FACTOR = 1.0; kpeter@648: const int MIN_BLOCK_SIZE = 10; kpeter@1136: const double HEAD_LENGTH_FACTOR = 0.01; kpeter@648: const int MIN_HEAD_LENGTH = 3; kpeter@648: alpar@659: _block_size = std::max( int(BLOCK_SIZE_FACTOR * kpeter@710: std::sqrt(double(_search_arc_num))), kpeter@648: MIN_BLOCK_SIZE ); kpeter@648: _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size), kpeter@648: MIN_HEAD_LENGTH ); kpeter@648: _candidates.resize(_head_length + _block_size); kpeter@648: _curr_length = 0; kpeter@648: } kpeter@648: kpeter@652: // Find next entering arc kpeter@648: bool findEnteringArc() { kpeter@648: // Check the current candidate list kpeter@648: int e; kpeter@990: Cost c; kpeter@910: for (int i = 0; i != _curr_length; ++i) { kpeter@648: e = _candidates[i]; kpeter@990: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@990: if (c < 0) { kpeter@990: _cand_cost[e] = c; kpeter@990: } else { kpeter@648: _candidates[i--] = _candidates[--_curr_length]; kpeter@648: } kpeter@648: } kpeter@648: kpeter@648: // Extend the list kpeter@648: int cnt = _block_size; kpeter@648: int limit = _head_length; kpeter@648: kpeter@910: for (e = _next_arc; e != _search_arc_num; ++e) { kpeter@990: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@990: if (c < 0) { kpeter@990: _cand_cost[e] = c; kpeter@648: _candidates[_curr_length++] = e; kpeter@648: } kpeter@648: if (--cnt == 0) { kpeter@774: if (_curr_length > limit) goto search_end; kpeter@648: limit = 0; kpeter@648: cnt = _block_size; kpeter@648: } kpeter@648: } kpeter@910: for (e = 0; e != _next_arc; ++e) { kpeter@1136: c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]); kpeter@1136: if (c < 0) { kpeter@1136: _cand_cost[e] = c; kpeter@774: _candidates[_curr_length++] = e; kpeter@774: } kpeter@774: if (--cnt == 0) { kpeter@774: if (_curr_length > limit) goto search_end; kpeter@774: limit = 0; kpeter@774: cnt = _block_size; kpeter@648: } kpeter@648: } kpeter@648: if (_curr_length == 0) return false; alpar@956: kpeter@774: search_end: kpeter@648: kpeter@1136: // Perform partial sort operation on the candidate list kpeter@1136: int new_length = std::min(_head_length + 1, _curr_length); kpeter@1136: std::partial_sort(_candidates.begin(), _candidates.begin() + new_length, kpeter@1136: _candidates.begin() + _curr_length, _sort_func); kpeter@648: kpeter@1136: // Select the entering arc and remove it from the list kpeter@648: _in_arc = _candidates[0]; kpeter@774: _next_arc = e; kpeter@1136: _candidates[0] = _candidates[new_length - 1]; kpeter@1136: _curr_length = new_length - 1; kpeter@648: return true; kpeter@648: } kpeter@648: kpeter@648: }; //class AlteringListPivotRule kpeter@648: kpeter@648: public: kpeter@648: kpeter@652: /// \brief Constructor. kpeter@648: /// kpeter@656: /// The constructor of the class. kpeter@648: /// kpeter@650: /// \param graph The digraph the algorithm runs on. kpeter@991: /// \param arc_mixing Indicate if the arcs will be stored in a alpar@956: /// mixed order in the internal data structure. kpeter@991: /// In general, it leads to similar performance as using the original kpeter@991: /// arc order, but it makes the algorithm more robust and in special kpeter@991: /// cases, even significantly faster. Therefore, it is enabled by default. kpeter@991: NetworkSimplex(const GR& graph, bool arc_mixing = true) : kpeter@689: _graph(graph), _node_id(graph), _arc_id(graph), kpeter@898: _arc_mixing(arc_mixing), kpeter@877: MAX(std::numeric_limits::max()), kpeter@688: INF(std::numeric_limits::has_infinity ? kpeter@877: std::numeric_limits::infinity() : MAX) kpeter@652: { kpeter@878: // Check the number types kpeter@688: LEMON_ASSERT(std::numeric_limits::is_signed, kpeter@687: "The flow type of NetworkSimplex must be signed"); kpeter@687: LEMON_ASSERT(std::numeric_limits::is_signed, kpeter@687: "The cost type of NetworkSimplex must be signed"); kpeter@648: kpeter@898: // Reset data structures kpeter@776: reset(); kpeter@648: } kpeter@648: kpeter@656: /// \name Parameters kpeter@656: /// The parameters of the algorithm can be specified using these kpeter@656: /// functions. kpeter@656: kpeter@656: /// @{ kpeter@656: kpeter@652: /// \brief Set the lower bounds on the arcs. kpeter@652: /// kpeter@652: /// This function sets the lower bounds on the arcs. kpeter@687: /// If it is not used before calling \ref run(), the lower bounds kpeter@687: /// will be set to zero on all arcs. kpeter@652: /// kpeter@652: /// \param map An arc map storing the lower bounds. kpeter@688: /// Its \c Value type must be convertible to the \c Value type kpeter@652: /// of the algorithm. kpeter@652: /// kpeter@652: /// \return (*this) kpeter@687: template kpeter@687: NetworkSimplex& lowerMap(const LowerMap& map) { kpeter@689: _have_lower = true; kpeter@652: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@689: _lower[_arc_id[a]] = map[a]; kpeter@652: } kpeter@652: return *this; kpeter@652: } kpeter@652: kpeter@652: /// \brief Set the upper bounds (capacities) on the arcs. kpeter@652: /// kpeter@652: /// This function sets the upper bounds (capacities) on the arcs. kpeter@687: /// If it is not used before calling \ref run(), the upper bounds kpeter@687: /// will be set to \ref INF on all arcs (i.e. the flow value will be kpeter@878: /// unbounded from above). kpeter@652: /// kpeter@652: /// \param map An arc map storing the upper bounds. kpeter@688: /// Its \c Value type must be convertible to the \c Value type kpeter@652: /// of the algorithm. kpeter@652: /// kpeter@652: /// \return (*this) kpeter@687: template kpeter@687: NetworkSimplex& upperMap(const UpperMap& map) { kpeter@652: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@689: _upper[_arc_id[a]] = map[a]; kpeter@652: } kpeter@652: return *this; kpeter@652: } kpeter@652: kpeter@652: /// \brief Set the costs of the arcs. kpeter@652: /// kpeter@652: /// This function sets the costs of the arcs. kpeter@652: /// If it is not used before calling \ref run(), the costs kpeter@652: /// will be set to \c 1 on all arcs. kpeter@652: /// kpeter@652: /// \param map An arc map storing the costs. kpeter@654: /// Its \c Value type must be convertible to the \c Cost type kpeter@652: /// of the algorithm. kpeter@652: /// kpeter@652: /// \return (*this) kpeter@687: template kpeter@687: NetworkSimplex& costMap(const CostMap& map) { kpeter@652: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@689: _cost[_arc_id[a]] = map[a]; kpeter@652: } kpeter@652: return *this; kpeter@652: } kpeter@652: kpeter@652: /// \brief Set the supply values of the nodes. kpeter@652: /// kpeter@652: /// This function sets the supply values of the nodes. kpeter@652: /// If neither this function nor \ref stSupply() is used before kpeter@652: /// calling \ref run(), the supply of each node will be set to zero. kpeter@652: /// kpeter@652: /// \param map A node map storing the supply values. kpeter@688: /// Its \c Value type must be convertible to the \c Value type kpeter@652: /// of the algorithm. kpeter@652: /// kpeter@652: /// \return (*this) kpeter@1023: /// kpeter@1023: /// \sa supplyType() kpeter@687: template kpeter@687: NetworkSimplex& supplyMap(const SupplyMap& map) { kpeter@652: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@689: _supply[_node_id[n]] = map[n]; kpeter@652: } kpeter@652: return *this; kpeter@652: } kpeter@652: kpeter@652: /// \brief Set single source and target nodes and a supply value. kpeter@652: /// kpeter@652: /// This function sets a single source node and a single target node kpeter@652: /// and the required flow value. kpeter@652: /// If neither this function nor \ref supplyMap() is used before kpeter@652: /// calling \ref run(), the supply of each node will be set to zero. kpeter@652: /// kpeter@687: /// Using this function has the same effect as using \ref supplyMap() kpeter@1023: /// with a map in which \c k is assigned to \c s, \c -k is kpeter@687: /// assigned to \c t and all other nodes have zero supply value. kpeter@687: /// kpeter@652: /// \param s The source node. kpeter@652: /// \param t The target node. kpeter@652: /// \param k The required amount of flow from node \c s to node \c t kpeter@652: /// (i.e. the supply of \c s and the demand of \c t). kpeter@652: /// kpeter@652: /// \return (*this) kpeter@688: NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) { kpeter@689: for (int i = 0; i != _node_num; ++i) { kpeter@689: _supply[i] = 0; kpeter@689: } kpeter@689: _supply[_node_id[s]] = k; kpeter@689: _supply[_node_id[t]] = -k; kpeter@652: return *this; kpeter@652: } alpar@956: kpeter@687: /// \brief Set the type of the supply constraints. kpeter@656: /// kpeter@687: /// This function sets the type of the supply/demand constraints. kpeter@687: /// If it is not used before calling \ref run(), the \ref GEQ supply kpeter@656: /// type will be used. kpeter@656: /// kpeter@833: /// For more information, see \ref SupplyType. kpeter@656: /// kpeter@656: /// \return (*this) kpeter@687: NetworkSimplex& supplyType(SupplyType supply_type) { kpeter@687: _stype = supply_type; kpeter@656: return *this; kpeter@656: } kpeter@652: kpeter@656: /// @} kpeter@648: kpeter@652: /// \name Execution Control kpeter@652: /// The algorithm can be executed using \ref run(). kpeter@652: kpeter@648: /// @{ kpeter@648: kpeter@648: /// \brief Run the algorithm. kpeter@648: /// kpeter@648: /// This function runs the algorithm. kpeter@656: /// The paramters can be specified using functions \ref lowerMap(), alpar@956: /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), kpeter@689: /// \ref supplyType(). kpeter@656: /// For example, kpeter@652: /// \code kpeter@652: /// NetworkSimplex ns(graph); kpeter@687: /// ns.lowerMap(lower).upperMap(upper).costMap(cost) kpeter@652: /// .supplyMap(sup).run(); kpeter@652: /// \endcode kpeter@648: /// kpeter@898: /// This function can be called more than once. All the given parameters kpeter@898: /// are kept for the next call, unless \ref resetParams() or \ref reset() kpeter@898: /// is used, thus only the modified parameters have to be set again. kpeter@898: /// If the underlying digraph was also modified after the construction kpeter@898: /// of the class (or the last \ref reset() call), then the \ref reset() kpeter@898: /// function must be called. kpeter@653: /// kpeter@652: /// \param pivot_rule The pivot rule that will be used during the kpeter@833: /// algorithm. For more information, see \ref PivotRule. kpeter@648: /// kpeter@687: /// \return \c INFEASIBLE if no feasible flow exists, kpeter@687: /// \n \c OPTIMAL if the problem has optimal solution kpeter@687: /// (i.e. it is feasible and bounded), and the algorithm has found kpeter@687: /// optimal flow and node potentials (primal and dual solutions), kpeter@687: /// \n \c UNBOUNDED if the objective function of the problem is kpeter@687: /// unbounded, i.e. there is a directed cycle having negative total kpeter@687: /// cost and infinite upper bound. kpeter@687: /// kpeter@687: /// \see ProblemType, PivotRule kpeter@898: /// \see resetParams(), reset() kpeter@687: ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) { kpeter@687: if (!init()) return INFEASIBLE; kpeter@687: return start(pivot_rule); kpeter@648: } kpeter@648: kpeter@653: /// \brief Reset all the parameters that have been given before. kpeter@653: /// kpeter@653: /// This function resets all the paramaters that have been given kpeter@656: /// before using functions \ref lowerMap(), \ref upperMap(), kpeter@689: /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType(). kpeter@653: /// kpeter@898: /// It is useful for multiple \ref run() calls. Basically, all the given kpeter@898: /// parameters are kept for the next \ref run() call, unless kpeter@898: /// \ref resetParams() or \ref reset() is used. kpeter@898: /// If the underlying digraph was also modified after the construction kpeter@898: /// of the class or the last \ref reset() call, then the \ref reset() kpeter@898: /// function must be used, otherwise \ref resetParams() is sufficient. kpeter@653: /// kpeter@653: /// For example, kpeter@653: /// \code kpeter@653: /// NetworkSimplex ns(graph); kpeter@653: /// kpeter@653: /// // First run kpeter@687: /// ns.lowerMap(lower).upperMap(upper).costMap(cost) kpeter@653: /// .supplyMap(sup).run(); kpeter@653: /// kpeter@898: /// // Run again with modified cost map (resetParams() is not called, kpeter@653: /// // so only the cost map have to be set again) kpeter@653: /// cost[e] += 100; kpeter@653: /// ns.costMap(cost).run(); kpeter@653: /// kpeter@898: /// // Run again from scratch using resetParams() kpeter@653: /// // (the lower bounds will be set to zero on all arcs) kpeter@898: /// ns.resetParams(); kpeter@687: /// ns.upperMap(capacity).costMap(cost) kpeter@653: /// .supplyMap(sup).run(); kpeter@653: /// \endcode kpeter@653: /// kpeter@653: /// \return (*this) kpeter@898: /// kpeter@898: /// \see reset(), run() kpeter@898: NetworkSimplex& resetParams() { kpeter@689: for (int i = 0; i != _node_num; ++i) { kpeter@689: _supply[i] = 0; kpeter@689: } kpeter@689: for (int i = 0; i != _arc_num; ++i) { kpeter@689: _lower[i] = 0; kpeter@689: _upper[i] = INF; kpeter@689: _cost[i] = 1; kpeter@689: } kpeter@689: _have_lower = false; kpeter@687: _stype = GEQ; kpeter@653: return *this; kpeter@653: } kpeter@653: kpeter@898: /// \brief Reset the internal data structures and all the parameters kpeter@898: /// that have been given before. kpeter@898: /// kpeter@898: /// This function resets the internal data structures and all the kpeter@898: /// paramaters that have been given before using functions \ref lowerMap(), kpeter@898: /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), kpeter@898: /// \ref supplyType(). kpeter@898: /// kpeter@898: /// It is useful for multiple \ref run() calls. Basically, all the given kpeter@898: /// parameters are kept for the next \ref run() call, unless kpeter@898: /// \ref resetParams() or \ref reset() is used. kpeter@898: /// If the underlying digraph was also modified after the construction kpeter@898: /// of the class or the last \ref reset() call, then the \ref reset() kpeter@898: /// function must be used, otherwise \ref resetParams() is sufficient. kpeter@898: /// kpeter@898: /// See \ref resetParams() for examples. kpeter@898: /// kpeter@898: /// \return (*this) kpeter@898: /// kpeter@898: /// \see resetParams(), run() kpeter@898: NetworkSimplex& reset() { kpeter@898: // Resize vectors kpeter@898: _node_num = countNodes(_graph); kpeter@898: _arc_num = countArcs(_graph); kpeter@898: int all_node_num = _node_num + 1; kpeter@898: int max_arc_num = _arc_num + 2 * _node_num; kpeter@898: kpeter@898: _source.resize(max_arc_num); kpeter@898: _target.resize(max_arc_num); kpeter@898: kpeter@898: _lower.resize(_arc_num); kpeter@898: _upper.resize(_arc_num); kpeter@898: _cap.resize(max_arc_num); kpeter@898: _cost.resize(max_arc_num); kpeter@898: _supply.resize(all_node_num); kpeter@898: _flow.resize(max_arc_num); kpeter@898: _pi.resize(all_node_num); kpeter@898: kpeter@898: _parent.resize(all_node_num); kpeter@898: _pred.resize(all_node_num); kpeter@990: _pred_dir.resize(all_node_num); kpeter@898: _thread.resize(all_node_num); kpeter@898: _rev_thread.resize(all_node_num); kpeter@898: _succ_num.resize(all_node_num); kpeter@898: _last_succ.resize(all_node_num); kpeter@898: _state.resize(max_arc_num); kpeter@898: kpeter@898: // Copy the graph kpeter@898: int i = 0; kpeter@898: for (NodeIt n(_graph); n != INVALID; ++n, ++i) { kpeter@898: _node_id[n] = i; kpeter@898: } kpeter@898: if (_arc_mixing) { kpeter@898: // Store the arcs in a mixed order kpeter@991: const int skip = std::max(_arc_num / _node_num, 3); kpeter@898: int i = 0, j = 0; kpeter@898: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@898: _arc_id[a] = i; kpeter@898: _source[i] = _node_id[_graph.source(a)]; kpeter@898: _target[i] = _node_id[_graph.target(a)]; kpeter@991: if ((i += skip) >= _arc_num) i = ++j; kpeter@898: } kpeter@898: } else { kpeter@898: // Store the arcs in the original order kpeter@898: int i = 0; kpeter@898: for (ArcIt a(_graph); a != INVALID; ++a, ++i) { kpeter@898: _arc_id[a] = i; kpeter@898: _source[i] = _node_id[_graph.source(a)]; kpeter@898: _target[i] = _node_id[_graph.target(a)]; kpeter@898: } kpeter@898: } alpar@956: kpeter@898: // Reset parameters kpeter@898: resetParams(); kpeter@898: return *this; kpeter@898: } alpar@956: kpeter@648: /// @} kpeter@648: kpeter@648: /// \name Query Functions kpeter@648: /// The results of the algorithm can be obtained using these kpeter@648: /// functions.\n kpeter@652: /// The \ref run() function must be called before using them. kpeter@652: kpeter@648: /// @{ kpeter@648: kpeter@652: /// \brief Return the total cost of the found flow. kpeter@652: /// kpeter@652: /// This function returns the total cost of the found flow. kpeter@687: /// Its complexity is O(e). kpeter@652: /// kpeter@652: /// \note The return type of the function can be specified as a kpeter@652: /// template parameter. For example, kpeter@652: /// \code kpeter@652: /// ns.totalCost(); kpeter@652: /// \endcode kpeter@654: /// It is useful if the total cost cannot be stored in the \c Cost kpeter@652: /// type of the algorithm, which is the default return type of the kpeter@652: /// function. kpeter@652: /// kpeter@652: /// \pre \ref run() must be called before using this function. kpeter@689: template kpeter@689: Number totalCost() const { kpeter@689: Number c = 0; kpeter@689: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@689: int i = _arc_id[a]; kpeter@689: c += Number(_flow[i]) * Number(_cost[i]); kpeter@652: } kpeter@652: return c; kpeter@652: } kpeter@652: kpeter@652: #ifndef DOXYGEN kpeter@654: Cost totalCost() const { kpeter@654: return totalCost(); kpeter@652: } kpeter@652: #endif kpeter@652: kpeter@652: /// \brief Return the flow on the given arc. kpeter@652: /// kpeter@652: /// This function returns the flow on the given arc. kpeter@652: /// kpeter@652: /// \pre \ref run() must be called before using this function. kpeter@688: Value flow(const Arc& a) const { kpeter@689: return _flow[_arc_id[a]]; kpeter@652: } kpeter@652: kpeter@1165: /// \brief Copy the flow values (the primal solution) into the kpeter@1165: /// given map. kpeter@648: /// kpeter@689: /// This function copies the flow value on each arc into the given kpeter@689: /// map. The \c Value type of the algorithm must be convertible to kpeter@689: /// the \c Value type of the map. kpeter@648: /// kpeter@648: /// \pre \ref run() must be called before using this function. kpeter@689: template kpeter@689: void flowMap(FlowMap &map) const { kpeter@689: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@689: map.set(a, _flow[_arc_id[a]]); kpeter@689: } kpeter@648: } kpeter@648: kpeter@652: /// \brief Return the potential (dual value) of the given node. kpeter@652: /// kpeter@652: /// This function returns the potential (dual value) of the kpeter@652: /// given node. kpeter@652: /// kpeter@652: /// \pre \ref run() must be called before using this function. kpeter@654: Cost potential(const Node& n) const { kpeter@689: return _pi[_node_id[n]]; kpeter@652: } kpeter@652: kpeter@1165: /// \brief Copy the potential values (the dual solution) into the kpeter@1165: /// given map. kpeter@648: /// kpeter@689: /// This function copies the potential (dual value) of each node kpeter@689: /// into the given map. kpeter@689: /// The \c Cost type of the algorithm must be convertible to the kpeter@689: /// \c Value type of the map. kpeter@648: /// kpeter@648: /// \pre \ref run() must be called before using this function. kpeter@689: template kpeter@689: void potentialMap(PotentialMap &map) const { kpeter@689: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@689: map.set(n, _pi[_node_id[n]]); kpeter@689: } kpeter@648: } kpeter@648: kpeter@648: /// @} kpeter@648: kpeter@648: private: kpeter@648: kpeter@648: // Initialize internal data structures kpeter@648: bool init() { kpeter@652: if (_node_num == 0) return false; kpeter@648: kpeter@689: // Check the sum of supply values kpeter@689: _sum_supply = 0; kpeter@689: for (int i = 0; i != _node_num; ++i) { kpeter@689: _sum_supply += _supply[i]; kpeter@689: } alpar@690: if ( !((_stype == GEQ && _sum_supply <= 0) || alpar@690: (_stype == LEQ && _sum_supply >= 0)) ) return false; kpeter@648: kpeter@689: // Remove non-zero lower bounds kpeter@689: if (_have_lower) { kpeter@689: for (int i = 0; i != _arc_num; ++i) { kpeter@689: Value c = _lower[i]; kpeter@689: if (c >= 0) { kpeter@877: _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF; kpeter@689: } else { kpeter@877: _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF; kpeter@689: } kpeter@689: _supply[_source[i]] -= c; kpeter@689: _supply[_target[i]] += c; kpeter@689: } kpeter@689: } else { kpeter@689: for (int i = 0; i != _arc_num; ++i) { kpeter@689: _cap[i] = _upper[i]; kpeter@689: } kpeter@652: } kpeter@648: kpeter@656: // Initialize artifical cost kpeter@687: Cost ART_COST; kpeter@656: if (std::numeric_limits::is_exact) { kpeter@710: ART_COST = std::numeric_limits::max() / 2 + 1; kpeter@656: } else { kpeter@976: ART_COST = 0; kpeter@656: for (int i = 0; i != _arc_num; ++i) { kpeter@687: if (_cost[i] > ART_COST) ART_COST = _cost[i]; kpeter@656: } kpeter@687: ART_COST = (ART_COST + 1) * _node_num; kpeter@656: } kpeter@656: kpeter@689: // Initialize arc maps kpeter@689: for (int i = 0; i != _arc_num; ++i) { kpeter@689: _flow[i] = 0; kpeter@689: _state[i] = STATE_LOWER; kpeter@689: } alpar@956: kpeter@648: // Set data for the artificial root node kpeter@648: _root = _node_num; kpeter@648: _parent[_root] = -1; kpeter@648: _pred[_root] = -1; kpeter@648: _thread[_root] = 0; kpeter@651: _rev_thread[0] = _root; kpeter@689: _succ_num[_root] = _node_num + 1; kpeter@651: _last_succ[_root] = _root - 1; kpeter@687: _supply[_root] = -_sum_supply; kpeter@710: _pi[_root] = 0; kpeter@648: kpeter@648: // Add artificial arcs and initialize the spanning tree data structure kpeter@710: if (_sum_supply == 0) { kpeter@710: // EQ supply constraints kpeter@710: _search_arc_num = _arc_num; kpeter@710: _all_arc_num = _arc_num + _node_num; kpeter@710: for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) { kpeter@710: _parent[u] = _root; kpeter@710: _pred[u] = e; kpeter@710: _thread[u] = u + 1; kpeter@710: _rev_thread[u + 1] = u; kpeter@710: _succ_num[u] = 1; kpeter@710: _last_succ[u] = u; kpeter@710: _cap[e] = INF; kpeter@710: _state[e] = STATE_TREE; kpeter@710: if (_supply[u] >= 0) { kpeter@990: _pred_dir[u] = DIR_UP; kpeter@710: _pi[u] = 0; kpeter@710: _source[e] = u; kpeter@710: _target[e] = _root; kpeter@710: _flow[e] = _supply[u]; kpeter@710: _cost[e] = 0; kpeter@710: } else { kpeter@990: _pred_dir[u] = DIR_DOWN; kpeter@710: _pi[u] = ART_COST; kpeter@710: _source[e] = _root; kpeter@710: _target[e] = u; kpeter@710: _flow[e] = -_supply[u]; kpeter@710: _cost[e] = ART_COST; kpeter@710: } kpeter@648: } kpeter@648: } kpeter@710: else if (_sum_supply > 0) { kpeter@710: // LEQ supply constraints kpeter@710: _search_arc_num = _arc_num + _node_num; kpeter@710: int f = _arc_num + _node_num; kpeter@710: for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) { kpeter@710: _parent[u] = _root; kpeter@710: _thread[u] = u + 1; kpeter@710: _rev_thread[u + 1] = u; kpeter@710: _succ_num[u] = 1; kpeter@710: _last_succ[u] = u; kpeter@710: if (_supply[u] >= 0) { kpeter@990: _pred_dir[u] = DIR_UP; kpeter@710: _pi[u] = 0; kpeter@710: _pred[u] = e; kpeter@710: _source[e] = u; kpeter@710: _target[e] = _root; kpeter@710: _cap[e] = INF; kpeter@710: _flow[e] = _supply[u]; kpeter@710: _cost[e] = 0; kpeter@710: _state[e] = STATE_TREE; kpeter@710: } else { kpeter@990: _pred_dir[u] = DIR_DOWN; kpeter@710: _pi[u] = ART_COST; kpeter@710: _pred[u] = f; kpeter@710: _source[f] = _root; kpeter@710: _target[f] = u; kpeter@710: _cap[f] = INF; kpeter@710: _flow[f] = -_supply[u]; kpeter@710: _cost[f] = ART_COST; kpeter@710: _state[f] = STATE_TREE; kpeter@710: _source[e] = u; kpeter@710: _target[e] = _root; kpeter@710: _cap[e] = INF; kpeter@710: _flow[e] = 0; kpeter@710: _cost[e] = 0; kpeter@710: _state[e] = STATE_LOWER; kpeter@710: ++f; kpeter@710: } kpeter@710: } kpeter@710: _all_arc_num = f; kpeter@710: } kpeter@710: else { kpeter@710: // GEQ supply constraints kpeter@710: _search_arc_num = _arc_num + _node_num; kpeter@710: int f = _arc_num + _node_num; kpeter@710: for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) { kpeter@710: _parent[u] = _root; kpeter@710: _thread[u] = u + 1; kpeter@710: _rev_thread[u + 1] = u; kpeter@710: _succ_num[u] = 1; kpeter@710: _last_succ[u] = u; kpeter@710: if (_supply[u] <= 0) { kpeter@990: _pred_dir[u] = DIR_DOWN; kpeter@710: _pi[u] = 0; kpeter@710: _pred[u] = e; kpeter@710: _source[e] = _root; kpeter@710: _target[e] = u; kpeter@710: _cap[e] = INF; kpeter@710: _flow[e] = -_supply[u]; kpeter@710: _cost[e] = 0; kpeter@710: _state[e] = STATE_TREE; kpeter@710: } else { kpeter@990: _pred_dir[u] = DIR_UP; kpeter@710: _pi[u] = -ART_COST; kpeter@710: _pred[u] = f; kpeter@710: _source[f] = u; kpeter@710: _target[f] = _root; kpeter@710: _cap[f] = INF; kpeter@710: _flow[f] = _supply[u]; kpeter@710: _state[f] = STATE_TREE; kpeter@710: _cost[f] = ART_COST; kpeter@710: _source[e] = _root; kpeter@710: _target[e] = u; kpeter@710: _cap[e] = INF; kpeter@710: _flow[e] = 0; kpeter@710: _cost[e] = 0; kpeter@710: _state[e] = STATE_LOWER; kpeter@710: ++f; kpeter@710: } kpeter@710: } kpeter@710: _all_arc_num = f; kpeter@710: } kpeter@648: kpeter@648: return true; kpeter@648: } kpeter@648: kpeter@648: // Find the join node kpeter@648: void findJoinNode() { kpeter@650: int u = _source[in_arc]; kpeter@650: int v = _target[in_arc]; kpeter@648: while (u != v) { kpeter@651: if (_succ_num[u] < _succ_num[v]) { kpeter@651: u = _parent[u]; kpeter@651: } else { kpeter@651: v = _parent[v]; kpeter@651: } kpeter@648: } kpeter@648: join = u; kpeter@648: } kpeter@648: kpeter@648: // Find the leaving arc of the cycle and returns true if the kpeter@648: // leaving arc is not the same as the entering arc kpeter@648: bool findLeavingArc() { kpeter@648: // Initialize first and second nodes according to the direction kpeter@648: // of the cycle kpeter@990: int first, second; kpeter@650: if (_state[in_arc] == STATE_LOWER) { kpeter@650: first = _source[in_arc]; kpeter@650: second = _target[in_arc]; kpeter@648: } else { kpeter@650: first = _target[in_arc]; kpeter@650: second = _source[in_arc]; kpeter@648: } kpeter@650: delta = _cap[in_arc]; kpeter@648: int result = 0; kpeter@990: Value c, d; kpeter@648: int e; kpeter@648: kpeter@990: // Search the cycle form the first node to the join node kpeter@648: for (int u = first; u != join; u = _parent[u]) { kpeter@648: e = _pred[u]; kpeter@990: d = _flow[e]; kpeter@990: if (_pred_dir[u] == DIR_DOWN) { kpeter@990: c = _cap[e]; kpeter@990: d = c >= MAX ? INF : c - d; kpeter@990: } kpeter@648: if (d < delta) { kpeter@648: delta = d; kpeter@648: u_out = u; kpeter@648: result = 1; kpeter@648: } kpeter@648: } kpeter@990: kpeter@990: // Search the cycle form the second node to the join node kpeter@648: for (int u = second; u != join; u = _parent[u]) { kpeter@648: e = _pred[u]; kpeter@990: d = _flow[e]; kpeter@990: if (_pred_dir[u] == DIR_UP) { kpeter@990: c = _cap[e]; kpeter@990: d = c >= MAX ? INF : c - d; kpeter@990: } kpeter@648: if (d <= delta) { kpeter@648: delta = d; kpeter@648: u_out = u; kpeter@648: result = 2; kpeter@648: } kpeter@648: } kpeter@648: kpeter@648: if (result == 1) { kpeter@648: u_in = first; kpeter@648: v_in = second; kpeter@648: } else { kpeter@648: u_in = second; kpeter@648: v_in = first; kpeter@648: } kpeter@648: return result != 0; kpeter@648: } kpeter@648: kpeter@648: // Change _flow and _state vectors kpeter@648: void changeFlow(bool change) { kpeter@648: // Augment along the cycle kpeter@648: if (delta > 0) { kpeter@688: Value val = _state[in_arc] * delta; kpeter@650: _flow[in_arc] += val; kpeter@650: for (int u = _source[in_arc]; u != join; u = _parent[u]) { kpeter@990: _flow[_pred[u]] -= _pred_dir[u] * val; kpeter@648: } kpeter@650: for (int u = _target[in_arc]; u != join; u = _parent[u]) { kpeter@990: _flow[_pred[u]] += _pred_dir[u] * val; kpeter@648: } kpeter@648: } kpeter@648: // Update the state of the entering and leaving arcs kpeter@648: if (change) { kpeter@650: _state[in_arc] = STATE_TREE; kpeter@648: _state[_pred[u_out]] = kpeter@648: (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER; kpeter@648: } else { kpeter@650: _state[in_arc] = -_state[in_arc]; kpeter@648: } kpeter@648: } kpeter@648: kpeter@651: // Update the tree structure kpeter@651: void updateTreeStructure() { kpeter@651: int old_rev_thread = _rev_thread[u_out]; kpeter@651: int old_succ_num = _succ_num[u_out]; kpeter@651: int old_last_succ = _last_succ[u_out]; kpeter@648: v_out = _parent[u_out]; kpeter@648: kpeter@990: // Check if u_in and u_out coincide kpeter@990: if (u_in == u_out) { kpeter@990: // Update _parent, _pred, _pred_dir kpeter@990: _parent[u_in] = v_in; kpeter@990: _pred[u_in] = in_arc; kpeter@990: _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN; kpeter@651: kpeter@990: // Update _thread and _rev_thread kpeter@990: if (_thread[v_in] != u_out) { kpeter@990: int after = _thread[old_last_succ]; kpeter@990: _thread[old_rev_thread] = after; kpeter@990: _rev_thread[after] = old_rev_thread; kpeter@990: after = _thread[v_in]; kpeter@990: _thread[v_in] = u_out; kpeter@990: _rev_thread[u_out] = v_in; kpeter@990: _thread[old_last_succ] = after; kpeter@990: _rev_thread[after] = old_last_succ; kpeter@990: } kpeter@651: } else { kpeter@990: // Handle the case when old_rev_thread equals to v_in kpeter@990: // (it also means that join and v_out coincide) kpeter@990: int thread_continue = old_rev_thread == v_in ? kpeter@990: _thread[old_last_succ] : _thread[v_in]; kpeter@648: kpeter@990: // Update _thread and _parent along the stem nodes (i.e. the nodes kpeter@990: // between u_in and u_out, whose parent have to be changed) kpeter@990: int stem = u_in; // the current stem node kpeter@990: int par_stem = v_in; // the new parent of stem kpeter@990: int next_stem; // the next stem node kpeter@990: int last = _last_succ[u_in]; // the last successor of stem kpeter@990: int before, after = _thread[last]; kpeter@990: _thread[v_in] = u_in; kpeter@990: _dirty_revs.clear(); kpeter@990: _dirty_revs.push_back(v_in); kpeter@990: while (stem != u_out) { kpeter@990: // Insert the next stem node into the thread list kpeter@990: next_stem = _parent[stem]; kpeter@990: _thread[last] = next_stem; kpeter@990: _dirty_revs.push_back(last); kpeter@648: kpeter@990: // Remove the subtree of stem from the thread list kpeter@990: before = _rev_thread[stem]; kpeter@990: _thread[before] = after; kpeter@990: _rev_thread[after] = before; kpeter@648: kpeter@990: // Change the parent node and shift stem nodes kpeter@990: _parent[stem] = par_stem; kpeter@990: par_stem = stem; kpeter@990: stem = next_stem; kpeter@648: kpeter@990: // Update last and after kpeter@990: last = _last_succ[stem] == _last_succ[par_stem] ? kpeter@990: _rev_thread[par_stem] : _last_succ[stem]; kpeter@990: after = _thread[last]; kpeter@990: } kpeter@990: _parent[u_out] = par_stem; kpeter@990: _thread[last] = thread_continue; kpeter@990: _rev_thread[thread_continue] = last; kpeter@990: _last_succ[u_out] = last; kpeter@648: kpeter@990: // Remove the subtree of u_out from the thread list except for kpeter@990: // the case when old_rev_thread equals to v_in kpeter@990: if (old_rev_thread != v_in) { kpeter@990: _thread[old_rev_thread] = after; kpeter@990: _rev_thread[after] = old_rev_thread; kpeter@990: } kpeter@651: kpeter@990: // Update _rev_thread using the new _thread values kpeter@990: for (int i = 0; i != int(_dirty_revs.size()); ++i) { kpeter@990: int u = _dirty_revs[i]; kpeter@990: _rev_thread[_thread[u]] = u; kpeter@990: } kpeter@651: kpeter@990: // Update _pred, _pred_dir, _last_succ and _succ_num for the kpeter@990: // stem nodes from u_out to u_in kpeter@990: int tmp_sc = 0, tmp_ls = _last_succ[u_out]; kpeter@990: for (int u = u_out, p = _parent[u]; u != u_in; u = p, p = _parent[u]) { kpeter@990: _pred[u] = _pred[p]; kpeter@990: _pred_dir[u] = -_pred_dir[p]; kpeter@990: tmp_sc += _succ_num[u] - _succ_num[p]; kpeter@990: _succ_num[u] = tmp_sc; kpeter@990: _last_succ[p] = tmp_ls; kpeter@990: } kpeter@990: _pred[u_in] = in_arc; kpeter@990: _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN; kpeter@990: _succ_num[u_in] = old_succ_num; kpeter@651: } kpeter@651: kpeter@651: // Update _last_succ from v_in towards the root kpeter@990: int up_limit_out = _last_succ[join] == v_in ? join : -1; kpeter@990: int last_succ_out = _last_succ[u_out]; kpeter@990: for (int u = v_in; u != -1 && _last_succ[u] == v_in; u = _parent[u]) { kpeter@990: _last_succ[u] = last_succ_out; kpeter@651: } kpeter@990: kpeter@651: // Update _last_succ from v_out towards the root kpeter@651: if (join != old_rev_thread && v_in != old_rev_thread) { kpeter@990: for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ; kpeter@651: u = _parent[u]) { kpeter@651: _last_succ[u] = old_rev_thread; kpeter@651: } kpeter@990: } kpeter@990: else if (last_succ_out != old_last_succ) { kpeter@990: for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ; kpeter@651: u = _parent[u]) { kpeter@990: _last_succ[u] = last_succ_out; kpeter@651: } kpeter@651: } kpeter@651: kpeter@651: // Update _succ_num from v_in to join kpeter@990: for (int u = v_in; u != join; u = _parent[u]) { kpeter@651: _succ_num[u] += old_succ_num; kpeter@651: } kpeter@651: // Update _succ_num from v_out to join kpeter@990: for (int u = v_out; u != join; u = _parent[u]) { kpeter@651: _succ_num[u] -= old_succ_num; kpeter@648: } kpeter@648: } kpeter@648: kpeter@990: // Update potentials in the subtree that has been moved kpeter@651: void updatePotential() { kpeter@990: Cost sigma = _pi[v_in] - _pi[u_in] - kpeter@990: _pred_dir[u_in] * _cost[in_arc]; kpeter@655: int end = _thread[_last_succ[u_in]]; kpeter@655: for (int u = u_in; u != end; u = _thread[u]) { kpeter@655: _pi[u] += sigma; kpeter@648: } kpeter@648: } kpeter@648: kpeter@910: // Heuristic initial pivots kpeter@910: bool initialPivots() { kpeter@910: Value curr, total = 0; kpeter@910: std::vector supply_nodes, demand_nodes; kpeter@910: for (NodeIt u(_graph); u != INVALID; ++u) { kpeter@910: curr = _supply[_node_id[u]]; kpeter@910: if (curr > 0) { kpeter@910: total += curr; kpeter@910: supply_nodes.push_back(u); kpeter@910: } kpeter@910: else if (curr < 0) { kpeter@910: demand_nodes.push_back(u); kpeter@910: } kpeter@910: } kpeter@910: if (_sum_supply > 0) total -= _sum_supply; kpeter@910: if (total <= 0) return true; kpeter@910: kpeter@910: IntVector arc_vector; kpeter@910: if (_sum_supply >= 0) { kpeter@910: if (supply_nodes.size() == 1 && demand_nodes.size() == 1) { kpeter@910: // Perform a reverse graph search from the sink to the source kpeter@910: typename GR::template NodeMap reached(_graph, false); kpeter@910: Node s = supply_nodes[0], t = demand_nodes[0]; kpeter@910: std::vector stack; kpeter@910: reached[t] = true; kpeter@910: stack.push_back(t); kpeter@910: while (!stack.empty()) { kpeter@910: Node u, v = stack.back(); kpeter@910: stack.pop_back(); kpeter@910: if (v == s) break; kpeter@910: for (InArcIt a(_graph, v); a != INVALID; ++a) { kpeter@910: if (reached[u = _graph.source(a)]) continue; kpeter@910: int j = _arc_id[a]; kpeter@910: if (_cap[j] >= total) { kpeter@910: arc_vector.push_back(j); kpeter@910: reached[u] = true; kpeter@910: stack.push_back(u); kpeter@910: } kpeter@910: } kpeter@910: } kpeter@910: } else { kpeter@1217: // Find the min. cost incoming arc for each demand node kpeter@910: for (int i = 0; i != int(demand_nodes.size()); ++i) { kpeter@910: Node v = demand_nodes[i]; kpeter@910: Cost c, min_cost = std::numeric_limits::max(); kpeter@910: Arc min_arc = INVALID; kpeter@910: for (InArcIt a(_graph, v); a != INVALID; ++a) { kpeter@910: c = _cost[_arc_id[a]]; kpeter@910: if (c < min_cost) { kpeter@910: min_cost = c; kpeter@910: min_arc = a; kpeter@910: } kpeter@910: } kpeter@910: if (min_arc != INVALID) { kpeter@910: arc_vector.push_back(_arc_id[min_arc]); kpeter@910: } kpeter@910: } kpeter@910: } kpeter@910: } else { kpeter@910: // Find the min. cost outgoing arc for each supply node kpeter@910: for (int i = 0; i != int(supply_nodes.size()); ++i) { kpeter@910: Node u = supply_nodes[i]; kpeter@910: Cost c, min_cost = std::numeric_limits::max(); kpeter@910: Arc min_arc = INVALID; kpeter@910: for (OutArcIt a(_graph, u); a != INVALID; ++a) { kpeter@910: c = _cost[_arc_id[a]]; kpeter@910: if (c < min_cost) { kpeter@910: min_cost = c; kpeter@910: min_arc = a; kpeter@910: } kpeter@910: } kpeter@910: if (min_arc != INVALID) { kpeter@910: arc_vector.push_back(_arc_id[min_arc]); kpeter@910: } kpeter@910: } kpeter@910: } kpeter@910: kpeter@910: // Perform heuristic initial pivots kpeter@910: for (int i = 0; i != int(arc_vector.size()); ++i) { kpeter@910: in_arc = arc_vector[i]; kpeter@910: if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] - kpeter@910: _pi[_target[in_arc]]) >= 0) continue; kpeter@910: findJoinNode(); kpeter@910: bool change = findLeavingArc(); kpeter@910: if (delta >= MAX) return false; kpeter@910: changeFlow(change); kpeter@910: if (change) { kpeter@910: updateTreeStructure(); kpeter@910: updatePotential(); kpeter@910: } kpeter@910: } kpeter@910: return true; kpeter@910: } kpeter@910: kpeter@648: // Execute the algorithm kpeter@687: ProblemType start(PivotRule pivot_rule) { kpeter@648: // Select the pivot rule implementation kpeter@648: switch (pivot_rule) { kpeter@652: case FIRST_ELIGIBLE: kpeter@648: return start(); kpeter@652: case BEST_ELIGIBLE: kpeter@648: return start(); kpeter@652: case BLOCK_SEARCH: kpeter@648: return start(); kpeter@652: case CANDIDATE_LIST: kpeter@648: return start(); kpeter@652: case ALTERING_LIST: kpeter@648: return start(); kpeter@648: } kpeter@687: return INFEASIBLE; // avoid warning kpeter@648: } kpeter@648: kpeter@652: template kpeter@687: ProblemType start() { kpeter@652: PivotRuleImpl pivot(*this); kpeter@648: kpeter@910: // Perform heuristic initial pivots kpeter@910: if (!initialPivots()) return UNBOUNDED; kpeter@910: kpeter@652: // Execute the Network Simplex algorithm kpeter@648: while (pivot.findEnteringArc()) { kpeter@648: findJoinNode(); kpeter@648: bool change = findLeavingArc(); kpeter@877: if (delta >= MAX) return UNBOUNDED; kpeter@648: changeFlow(change); kpeter@648: if (change) { kpeter@651: updateTreeStructure(); kpeter@651: updatePotential(); kpeter@648: } kpeter@648: } alpar@956: kpeter@687: // Check feasibility kpeter@710: for (int e = _search_arc_num; e != _all_arc_num; ++e) { kpeter@710: if (_flow[e] != 0) return INFEASIBLE; kpeter@687: } kpeter@648: kpeter@689: // Transform the solution and the supply map to the original form kpeter@689: if (_have_lower) { kpeter@648: for (int i = 0; i != _arc_num; ++i) { kpeter@689: Value c = _lower[i]; kpeter@689: if (c != 0) { kpeter@689: _flow[i] += c; kpeter@689: _supply[_source[i]] += c; kpeter@689: _supply[_target[i]] -= c; kpeter@689: } kpeter@648: } kpeter@648: } alpar@956: kpeter@710: // Shift potentials to meet the requirements of the GEQ/LEQ type kpeter@710: // optimality conditions kpeter@710: if (_sum_supply == 0) { kpeter@710: if (_stype == GEQ) { kpeter@976: Cost max_pot = -std::numeric_limits::max(); kpeter@710: for (int i = 0; i != _node_num; ++i) { kpeter@710: if (_pi[i] > max_pot) max_pot = _pi[i]; kpeter@710: } kpeter@710: if (max_pot > 0) { kpeter@710: for (int i = 0; i != _node_num; ++i) kpeter@710: _pi[i] -= max_pot; kpeter@710: } kpeter@710: } else { kpeter@710: Cost min_pot = std::numeric_limits::max(); kpeter@710: for (int i = 0; i != _node_num; ++i) { kpeter@710: if (_pi[i] < min_pot) min_pot = _pi[i]; kpeter@710: } kpeter@710: if (min_pot < 0) { kpeter@710: for (int i = 0; i != _node_num; ++i) kpeter@710: _pi[i] -= min_pot; kpeter@710: } kpeter@710: } kpeter@710: } kpeter@648: kpeter@687: return OPTIMAL; kpeter@648: } kpeter@648: kpeter@648: }; //class NetworkSimplex kpeter@648: kpeter@648: ///@} kpeter@648: kpeter@648: } //namespace lemon kpeter@648: kpeter@648: #endif //LEMON_NETWORK_SIMPLEX_H