/* -*- mode: C++; indent-tabs-mode: nil; -*-
* This file is a part of LEMON, a generic C++ optimization library.
* Copyright (C) 2003-2009
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
#ifndef LEMON_NETWORK_SIMPLEX_H
#define LEMON_NETWORK_SIMPLEX_H
/// \ingroup min_cost_flow
/// \brief Network Simplex algorithm for finding a minimum cost flow.
#include <lemon/circulation.h>
#include <lemon/adaptors.h>
/// \addtogroup min_cost_flow
/// \brief Implementation of the primal Network Simplex algorithm
/// for finding a \ref min_cost_flow "minimum cost flow".
/// \ref NetworkSimplex implements the primal Network Simplex algorithm
/// for finding a \ref min_cost_flow "minimum cost flow".
/// This algorithm is a specialized version of the linear programming
/// simplex method directly for the minimum cost flow problem.
/// It is one of the most efficient solution methods.
/// In general this class is the fastest implementation available
/// in LEMON for the minimum cost flow problem.
/// Moreover it supports both direction of the supply/demand inequality
/// constraints. For more information see \ref ProblemType.
/// \tparam GR The digraph type the algorithm runs on.
/// \tparam F The value type used for flow amounts, capacity bounds
/// and supply values in the algorithm. By default it is \c int.
/// \tparam C The value type used for costs and potentials in the
/// algorithm. By default it is the same as \c F.
/// \warning Both value types must be signed and all input data must
/// \note %NetworkSimplex provides five different pivot rule
/// implementations, from which the most efficient one is used
/// by default. For more information see \ref PivotRule.
template <typename GR, typename F = int, typename C = F>
/// The flow type of the algorithm
/// The cost type of the algorithm
/// The type of the flow map
typedef GR::ArcMap<Flow> FlowMap;
/// The type of the potential map
typedef GR::NodeMap<Cost> PotentialMap;
/// The type of the flow map
typedef typename GR::template ArcMap<Flow> FlowMap;
/// The type of the potential map
typedef typename GR::template NodeMap<Cost> PotentialMap;
/// \brief Enum type for selecting the pivot rule.
/// Enum type for selecting the pivot rule for the \ref run()
/// \ref NetworkSimplex provides five different pivot rule
/// implementations that significantly affect the running time
/// By default \ref BLOCK_SEARCH "Block Search" is used, which
/// proved to be the most efficient and the most robust on various
/// test inputs according to our benchmark tests.
/// However another pivot rule can be selected using the \ref run()
/// function with the proper parameter.
/// The First Eligible pivot rule.
/// The next eligible arc is selected in a wraparound fashion
/// The Best Eligible pivot rule.
/// The best eligible arc is selected in every iteration.
/// The Block Search pivot rule.
/// A specified number of arcs are examined in every iteration
/// in a wraparound fashion and the best eligible arc is selected
/// The Candidate List pivot rule.
/// In a major iteration a candidate list is built from eligible arcs
/// in a wraparound fashion and in the following minor iterations
/// the best eligible arc is selected from this list.
/// The Altering Candidate List pivot rule.
/// It is a modified version of the Candidate List method.
/// It keeps only the several best eligible arcs from the former
/// candidate list and extends this list in every iteration.
/// \brief Enum type for selecting the problem type.
/// Enum type for selecting the problem type, i.e. the direction of
/// the inequalities in the supply/demand constraints of the
/// \ref min_cost_flow "minimum cost flow problem".
/// The default problem type is \c GEQ, since this form is supported
/// by other minimum cost flow algorithms and the \ref Circulation
/// The \c LEQ problem type can be selected using the \ref problemType()
/// Note that the equality form is a special case of both problem type.
/// This option means that there are "<em>greater or equal</em>"
/// constraints in the defintion, i.e. the exact formulation of the
/// problem is the following.
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
sup(u) \quad \forall u\in V \f]
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
/// It means that the total demand must be greater or equal to the
/// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
/// negative) and all the supplies have to be carried out from
/// the supply nodes, but there could be demands that are not
/// It is just an alias for the \c GEQ option.
/// This option means that there are "<em>less or equal</em>"
/// constraints in the defintion, i.e. the exact formulation of the
/// problem is the following.
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
sup(u) \quad \forall u\in V \f]
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
/// It means that the total demand must be less or equal to the
/// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
/// positive) and all the demands have to be satisfied, but there
/// could be supplies that are not carried out from the supply
/// It is just an alias for the \c LEQ option.
TEMPLATE_DIGRAPH_TYPEDEFS(GR);
typedef typename GR::template ArcMap<Flow> FlowArcMap;
typedef typename GR::template ArcMap<Cost> CostArcMap;
typedef typename GR::template NodeMap<Flow> FlowNodeMap;
typedef std::vector<Arc> ArcVector;
typedef std::vector<Node> NodeVector;
typedef std::vector<int> IntVector;
typedef std::vector<bool> BoolVector;
typedef std::vector<Flow> FlowVector;
typedef std::vector<Cost> CostVector;
// State constants for arcs
// Data related to the underlying digraph
// Parameters of the problem
PotentialMap *_potential_map;
// Data structures for storing the digraph
// Data for storing the spanning tree structure
// Temporary data used in the current pivot iteration
int in_arc, join, u_in, v_in, u_out, v_out;
int first, second, right, last;
int stem, par_stem, new_stem;
// Implementation of the First Eligible pivot rule
class FirstEligiblePivotRule
// References to the NetworkSimplex class
const IntVector &_source;
const IntVector &_target;
FirstEligiblePivotRule(NetworkSimplex &ns) :
_source(ns._source), _target(ns._target),
_cost(ns._cost), _state(ns._state), _pi(ns._pi),
_in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
// Find next entering arc
for (int e = _next_arc; e < _arc_num; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
for (int e = 0; e < _next_arc; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
}; //class FirstEligiblePivotRule
// Implementation of the Best Eligible pivot rule
class BestEligiblePivotRule
// References to the NetworkSimplex class
const IntVector &_source;
const IntVector &_target;
BestEligiblePivotRule(NetworkSimplex &ns) :
_source(ns._source), _target(ns._target),
_cost(ns._cost), _state(ns._state), _pi(ns._pi),
_in_arc(ns.in_arc), _arc_num(ns._arc_num)
// Find next entering arc
for (int e = 0; e < _arc_num; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
}; //class BestEligiblePivotRule
// Implementation of the Block Search pivot rule
class BlockSearchPivotRule
// References to the NetworkSimplex class
const IntVector &_source;
const IntVector &_target;
BlockSearchPivotRule(NetworkSimplex &ns) :
_source(ns._source), _target(ns._target),
_cost(ns._cost), _state(ns._state), _pi(ns._pi),
_in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
// The main parameters of the pivot rule
const double BLOCK_SIZE_FACTOR = 2.0;
const int MIN_BLOCK_SIZE = 10;
_block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
// Find next entering arc
int e, min_arc = _next_arc;
for (e = _next_arc; e < _arc_num; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
if (min == 0 || cnt > 0) {
for (e = 0; e < _next_arc; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
if (min >= 0) return false;
}; //class BlockSearchPivotRule
// Implementation of the Candidate List pivot rule
class CandidateListPivotRule
// References to the NetworkSimplex class
const IntVector &_source;
const IntVector &_target;
int _list_length, _minor_limit;
int _curr_length, _minor_count;
CandidateListPivotRule(NetworkSimplex &ns) :
_source(ns._source), _target(ns._target),
_cost(ns._cost), _state(ns._state), _pi(ns._pi),
_in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
// The main parameters of the pivot rule
const double LIST_LENGTH_FACTOR = 1.0;
const int MIN_LIST_LENGTH = 10;
const double MINOR_LIMIT_FACTOR = 0.1;
const int MIN_MINOR_LIMIT = 3;
_list_length = std::max( int(LIST_LENGTH_FACTOR * sqrt(_arc_num)),
_minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
_curr_length = _minor_count = 0;
_candidates.resize(_list_length);
/// Find next entering arc
int e, min_arc = _next_arc;
if (_curr_length > 0 && _minor_count < _minor_limit) {
// Minor iteration: select the best eligible arc from the
// current candidate list
for (int i = 0; i < _curr_length; ++i) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[i--] = _candidates[--_curr_length];
// Major iteration: build a new candidate list
for (e = _next_arc; e < _arc_num; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[_curr_length++] = e;
if (_curr_length == _list_length) break;
if (_curr_length < _list_length) {
for (e = 0; e < _next_arc; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[_curr_length++] = e;
if (_curr_length == _list_length) break;
if (_curr_length == 0) return false;
}; //class CandidateListPivotRule
// Implementation of the Altering Candidate List pivot rule
class AlteringListPivotRule
// References to the NetworkSimplex class
const IntVector &_source;
const IntVector &_target;
int _block_size, _head_length, _curr_length;
// Functor class to compare arcs during sort of the candidate list
SortFunc(const CostVector &map) : _map(map) {}
bool operator()(int left, int right) {
return _map[left] > _map[right];
AlteringListPivotRule(NetworkSimplex &ns) :
_source(ns._source), _target(ns._target),
_cost(ns._cost), _state(ns._state), _pi(ns._pi),
_in_arc(ns.in_arc), _arc_num(ns._arc_num),
_next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
// The main parameters of the pivot rule
const double BLOCK_SIZE_FACTOR = 1.5;
const int MIN_BLOCK_SIZE = 10;
const double HEAD_LENGTH_FACTOR = 0.1;
const int MIN_HEAD_LENGTH = 3;
_block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_arc_num)),
_head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
_candidates.resize(_head_length + _block_size);
// Find next entering arc
// Check the current candidate list
for (int i = 0; i < _curr_length; ++i) {
_cand_cost[e] = _state[e] *
(_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
if (_cand_cost[e] >= 0) {
_candidates[i--] = _candidates[--_curr_length];
int limit = _head_length;
for (int e = _next_arc; e < _arc_num; ++e) {
_cand_cost[e] = _state[e] *
(_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[_curr_length++] = e;
if (_curr_length > limit) break;
if (_curr_length <= limit) {
for (int e = 0; e < _next_arc; ++e) {
_cand_cost[e] = _state[e] *
(_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[_curr_length++] = e;
if (_curr_length > limit) break;
if (_curr_length == 0) return false;
_next_arc = last_arc + 1;
// Make heap of the candidate list (approximating a partial sort)
make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
// Pop the first element of the heap
_in_arc = _candidates[0];
pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
_curr_length = std::min(_head_length, _curr_length - 1);
}; //class AlteringListPivotRule
/// The constructor of the class.
/// \param graph The digraph the algorithm runs on.
NetworkSimplex(const GR& graph) :
_plower(NULL), _pupper(NULL), _pcost(NULL),
_psupply(NULL), _pstsup(false), _ptype(GEQ),
_flow_map(NULL), _potential_map(NULL),
_local_flow(false), _local_potential(false),
LEMON_ASSERT(std::numeric_limits<Flow>::is_integer &&
std::numeric_limits<Flow>::is_signed,
"The flow type of NetworkSimplex must be signed integer");
LEMON_ASSERT(std::numeric_limits<Cost>::is_integer &&
std::numeric_limits<Cost>::is_signed,
"The cost type of NetworkSimplex must be signed integer");
if (_local_flow) delete _flow_map;
if (_local_potential) delete _potential_map;
/// The parameters of the algorithm can be specified using these
/// \brief Set the lower bounds on the arcs.
/// This function sets the lower bounds on the arcs.
/// If neither this function nor \ref boundMaps() is used before
/// calling \ref run(), the lower bounds will be set to zero
/// \param map An arc map storing the lower bounds.
/// Its \c Value type must be convertible to the \c Flow type
/// \return <tt>(*this)</tt>
template <typename LOWER>
NetworkSimplex& lowerMap(const LOWER& map) {
_plower = new FlowArcMap(_graph);
for (ArcIt a(_graph); a != INVALID; ++a) {
/// \brief Set the upper bounds (capacities) on the arcs.
/// This function sets the upper bounds (capacities) on the arcs.
/// If none of the functions \ref upperMap(), \ref capacityMap()
/// and \ref boundMaps() is used before calling \ref run(),
/// the upper bounds (capacities) will be set to
/// \c std::numeric_limits<Flow>::max() on all arcs.
/// \param map An arc map storing the upper bounds.
/// Its \c Value type must be convertible to the \c Flow type
/// \return <tt>(*this)</tt>
NetworkSimplex& upperMap(const UPPER& map) {
_pupper = new FlowArcMap(_graph);
for (ArcIt a(_graph); a != INVALID; ++a) {
/// \brief Set the upper bounds (capacities) on the arcs.
/// This function sets the upper bounds (capacities) on the arcs.
/// It is just an alias for \ref upperMap().
/// \return <tt>(*this)</tt>
NetworkSimplex& capacityMap(const CAP& map) {
/// \brief Set the lower and upper bounds on the arcs.
/// This function sets the lower and upper bounds on the arcs.
/// If neither this function nor \ref lowerMap() is used before
/// calling \ref run(), the lower bounds will be set to zero
/// If none of the functions \ref upperMap(), \ref capacityMap()
/// and \ref boundMaps() is used before calling \ref run(),
/// the upper bounds (capacities) will be set to
/// \c std::numeric_limits<Flow>::max() on all arcs.
/// \param lower An arc map storing the lower bounds.
/// \param upper An arc map storing the upper bounds.
/// The \c Value type of the maps must be convertible to the
/// \c Flow type of the algorithm.
/// \note This function is just a shortcut of calling \ref lowerMap()
/// and \ref upperMap() separately.
/// \return <tt>(*this)</tt>
template <typename LOWER, typename UPPER>
NetworkSimplex& boundMaps(const LOWER& lower, const UPPER& upper) {
return lowerMap(lower).upperMap(upper);
/// \brief Set the costs of the arcs.
/// This function sets the costs of the arcs.
/// If it is not used before calling \ref run(), the costs
/// will be set to \c 1 on all arcs.
/// \param map An arc map storing the costs.
/// Its \c Value type must be convertible to the \c Cost type
/// \return <tt>(*this)</tt>
NetworkSimplex& costMap(const COST& map) {
_pcost = new CostArcMap(_graph);
for (ArcIt a(_graph); a != INVALID; ++a) {
/// \brief Set the supply values of the nodes.
/// This function sets the supply values of the nodes.
/// If neither this function nor \ref stSupply() is used before
/// calling \ref run(), the supply of each node will be set to zero.
/// (It makes sense only if non-zero lower bounds are given.)
/// \param map A node map storing the supply values.
/// Its \c Value type must be convertible to the \c Flow type
/// \return <tt>(*this)</tt>
NetworkSimplex& supplyMap(const SUP& map) {
_psupply = new FlowNodeMap(_graph);
for (NodeIt n(_graph); n != INVALID; ++n) {
/// \brief Set single source and target nodes and a supply value.
/// This function sets a single source node and a single target node
/// and the required flow value.
/// If neither this function nor \ref supplyMap() is used before
/// calling \ref run(), the supply of each node will be set to zero.
/// (It makes sense only if non-zero lower bounds are given.)
/// \param s The source node.
/// \param t The target node.
/// \param k The required amount of flow from node \c s to node \c t
/// (i.e. the supply of \c s and the demand of \c t).
/// \return <tt>(*this)</tt>
NetworkSimplex& stSupply(const Node& s, const Node& t, Flow k) {
/// \brief Set the problem type.
/// This function sets the problem type for the algorithm.
/// If it is not used before calling \ref run(), the \ref GEQ problem
/// For more information see \ref ProblemType.
/// \return <tt>(*this)</tt>
NetworkSimplex& problemType(ProblemType problem_type) {
/// \brief Set the flow map.
/// This function sets the flow map.
/// If it is not used before calling \ref run(), an instance will
/// be allocated automatically. The destructor deallocates this
/// automatically allocated map, of course.
/// \return <tt>(*this)</tt>
NetworkSimplex& flowMap(FlowMap& map) {
/// \brief Set the potential map.
/// This function sets the potential map, which is used for storing
/// If it is not used before calling \ref run(), an instance will
/// be allocated automatically. The destructor deallocates this
/// automatically allocated map, of course.
/// \return <tt>(*this)</tt>
NetworkSimplex& potentialMap(PotentialMap& map) {
_local_potential = false;
/// \name Execution Control
/// The algorithm can be executed using \ref run().
/// \brief Run the algorithm.
/// This function runs the algorithm.
/// The paramters can be specified using functions \ref lowerMap(),
/// \ref upperMap(), \ref capacityMap(), \ref boundMaps(),
/// \ref costMap(), \ref supplyMap(), \ref stSupply(),
/// \ref problemType(), \ref flowMap() and \ref potentialMap().
/// NetworkSimplex<ListDigraph> ns(graph);
/// ns.boundMaps(lower, upper).costMap(cost)
/// .supplyMap(sup).run();
/// This function can be called more than once. All the parameters
/// that have been given are kept for the next call, unless
/// \ref reset() is called, thus only the modified parameters
/// have to be set again. See \ref reset() for examples.
/// \param pivot_rule The pivot rule that will be used during the
/// algorithm. For more information see \ref PivotRule.
/// \return \c true if a feasible flow can be found.
bool run(PivotRule pivot_rule = BLOCK_SEARCH) {
return init() && start(pivot_rule);
/// \brief Reset all the parameters that have been given before.
/// This function resets all the paramaters that have been given
/// before using functions \ref lowerMap(), \ref upperMap(),
/// \ref capacityMap(), \ref boundMaps(), \ref costMap(),
/// \ref supplyMap(), \ref stSupply(), \ref problemType(),
/// \ref flowMap() and \ref potentialMap().
/// It is useful for multiple run() calls. If this function is not
/// used, all the parameters given before are kept for the next
/// NetworkSimplex<ListDigraph> ns(graph);
/// ns.lowerMap(lower).capacityMap(cap).costMap(cost)
/// .supplyMap(sup).run();
/// // Run again with modified cost map (reset() is not called,
/// // so only the cost map have to be set again)
/// ns.costMap(cost).run();
/// // Run again from scratch using reset()
/// // (the lower bounds will be set to zero on all arcs)
/// ns.capacityMap(cap).costMap(cost)
/// .supplyMap(sup).run();
/// \return <tt>(*this)</tt>
NetworkSimplex& reset() {
if (_local_flow) delete _flow_map;
if (_local_potential) delete _potential_map;
_local_potential = false;
/// \name Query Functions
/// The results of the algorithm can be obtained using these
/// The \ref run() function must be called before using them.
/// \brief Return the total cost of the found flow.
/// This function returns the total cost of the found flow.
/// The complexity of the function is O(e).
/// \note The return type of the function can be specified as a
/// template parameter. For example,
/// ns.totalCost<double>();
/// It is useful if the total cost cannot be stored in the \c Cost
/// type of the algorithm, which is the default return type of the
/// \pre \ref run() must be called before using this function.
for (ArcIt e(_graph); e != INVALID; ++e)
c += (*_flow_map)[e] * (*_pcost)[e];
for (ArcIt e(_graph); e != INVALID; ++e)
return totalCost<Cost>();
/// \brief Return the flow on the given arc.
/// This function returns the flow on the given arc.
/// \pre \ref run() must be called before using this function.
Flow flow(const Arc& a) const {
/// \brief Return a const reference to the flow map.
/// This function returns a const reference to an arc map storing
/// \pre \ref run() must be called before using this function.
const FlowMap& flowMap() const {
/// \brief Return the potential (dual value) of the given node.
/// This function returns the potential (dual value) of the
/// \pre \ref run() must be called before using this function.
Cost potential(const Node& n) const {
return (*_potential_map)[n];
/// \brief Return a const reference to the potential map
/// This function returns a const reference to a node map storing
/// the found potentials, which form the dual solution of the
/// \ref min_cost_flow "minimum cost flow" problem.
/// \pre \ref run() must be called before using this function.
const PotentialMap& potentialMap() const {
// Initialize internal data structures
// Initialize result maps
_flow_map = new FlowMap(_graph);
_potential_map = new PotentialMap(_graph);
_node_num = countNodes(_graph);
_arc_num = countArcs(_graph);
int all_node_num = _node_num + 1;
int all_arc_num = _arc_num + _node_num;
if (_node_num == 0) return false;
_arc_ref.resize(_arc_num);
_source.resize(all_arc_num);
_target.resize(all_arc_num);
_cap.resize(all_arc_num);
_cost.resize(all_arc_num);
_supply.resize(all_node_num);
_flow.resize(all_arc_num);
_pi.resize(all_node_num);
_parent.resize(all_node_num);
_pred.resize(all_node_num);
_forward.resize(all_node_num);
_thread.resize(all_node_num);
_rev_thread.resize(all_node_num);
_succ_num.resize(all_node_num);
_last_succ.resize(all_node_num);
_state.resize(all_arc_num);
// Initialize node related data
bool valid_supply = true;
if (!_pstsup && !_psupply) {
_psource = _ptarget = NodeIt(_graph);
for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
_supply[i] = (*_psupply)[n];
sum_supply += _supply[i];
valid_supply = (_ptype == GEQ && sum_supply <= 0) ||
(_ptype == LEQ && sum_supply >= 0);
for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
_supply[_node_id[_psource]] = _pstflow;
_supply[_node_id[_ptarget]] = -_pstflow;
if (!valid_supply) return false;
// Infinite capacity value
std::numeric_limits<Flow>::has_infinity ?
std::numeric_limits<Flow>::infinity() :
std::numeric_limits<Flow>::max();
// Initialize artifical cost
if (std::numeric_limits<Cost>::is_exact) {
art_cost = std::numeric_limits<Cost>::max() / 4 + 1;
art_cost = std::numeric_limits<Cost>::min();
for (int i = 0; i != _arc_num; ++i) {
if (_cost[i] > art_cost) art_cost = _cost[i];
art_cost = (art_cost + 1) * _node_num;
// Run Circulation to check if a feasible solution exists
typedef ConstMap<Arc, Flow> ConstArcMap;
ConstArcMap zero_arc_map(0), inf_arc_map(inf_cap);
FlowNodeMap *csup = NULL;
csup = new FlowNodeMap(_graph, 0);
(*csup)[_psource] = _pstflow;
(*csup)[_ptarget] = -_pstflow;
bool circ_result = false;
if (_ptype == GEQ || (_ptype == LEQ && sum_supply == 0)) {
Circulation<GR, FlowArcMap, FlowArcMap, FlowNodeMap>
circ(_graph, *_plower, *_pupper, *csup);
circ_result = circ.run();
Circulation<GR, FlowArcMap, ConstArcMap, FlowNodeMap>
circ(_graph, *_plower, inf_arc_map, *csup);
circ_result = circ.run();
Circulation<GR, ConstArcMap, FlowArcMap, FlowNodeMap>
circ(_graph, zero_arc_map, *_pupper, *csup);
circ_result = circ.run();
Circulation<GR, ConstArcMap, ConstArcMap, FlowNodeMap>
circ(_graph, zero_arc_map, inf_arc_map, *csup);
circ_result = circ.run();
typedef ReverseDigraph<const GR> RevGraph;
typedef NegMap<FlowNodeMap> NegNodeMap;
NegNodeMap neg_csup(*csup);
Circulation<RevGraph, FlowArcMap, FlowArcMap, NegNodeMap>
circ(rgraph, *_plower, *_pupper, neg_csup);
circ_result = circ.run();
Circulation<RevGraph, FlowArcMap, ConstArcMap, NegNodeMap>
circ(rgraph, *_plower, inf_arc_map, neg_csup);
circ_result = circ.run();
Circulation<RevGraph, ConstArcMap, FlowArcMap, NegNodeMap>
circ(rgraph, zero_arc_map, *_pupper, neg_csup);
circ_result = circ.run();
Circulation<RevGraph, ConstArcMap, ConstArcMap, NegNodeMap>
circ(rgraph, zero_arc_map, inf_arc_map, neg_csup);
circ_result = circ.run();
if (local_csup) delete csup;
if (!circ_result) return false;
// Set data for the artificial root node
_succ_num[_root] = all_node_num;
_last_succ[_root] = _root - 1;
_supply[_root] = -sum_supply;
// Store the arcs in a mixed order
int k = std::max(int(sqrt(_arc_num)), 10);
for (ArcIt e(_graph); e != INVALID; ++e) {
if ((i += k) >= _arc_num) i = (i % k) + 1;
for (int i = 0; i != _arc_num; ++i) {
_source[i] = _node_id[_graph.source(e)];
_target[i] = _node_id[_graph.target(e)];
for (int i = 0; i != _arc_num; ++i) {
_source[i] = _node_id[_graph.source(e)];
_target[i] = _node_id[_graph.target(e)];
for (int i = 0; i != _arc_num; ++i)
_cap[i] = (*_pupper)[_arc_ref[i]];
for (int i = 0; i != _arc_num; ++i)
for (int i = 0; i != _arc_num; ++i)
_cost[i] = (*_pcost)[_arc_ref[i]];
for (int i = 0; i != _arc_num; ++i)
// Remove non-zero lower bounds
for (int i = 0; i != _arc_num; ++i) {
Flow c = (*_plower)[_arc_ref[i]];
_supply[_source[i]] -= c;
_supply[_target[i]] += c;
// Add artificial arcs and initialize the spanning tree data structure
for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
if (_supply[u] > 0 || (_supply[u] == 0 && sum_supply <= 0)) {
_pi[u] = -art_cost + _pi[_root];
_pi[u] = art_cost + _pi[_root];
if (_succ_num[u] < _succ_num[v]) {
// Find the leaving arc of the cycle and returns true if the
// leaving arc is not the same as the entering arc
// Initialize first and second nodes according to the direction
if (_state[in_arc] == STATE_LOWER) {
second = _target[in_arc];
second = _source[in_arc];
// Search the cycle along the path form the first node to the root
for (int u = first; u != join; u = _parent[u]) {
d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
// Search the cycle along the path form the second node to the root
for (int u = second; u != join; u = _parent[u]) {
d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
// Change _flow and _state vectors
void changeFlow(bool change) {
// Augment along the cycle
Flow val = _state[in_arc] * delta;
for (int u = _source[in_arc]; u != join; u = _parent[u]) {
_flow[_pred[u]] += _forward[u] ? -val : val;
for (int u = _target[in_arc]; u != join; u = _parent[u]) {
_flow[_pred[u]] += _forward[u] ? val : -val;
// Update the state of the entering and leaving arcs
_state[in_arc] = STATE_TREE;
(_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
_state[in_arc] = -_state[in_arc];
// Update the tree structure
void updateTreeStructure() {
int old_rev_thread = _rev_thread[u_out];
int old_succ_num = _succ_num[u_out];
int old_last_succ = _last_succ[u_out];
u = _last_succ[u_in]; // the last successor of u_in
right = _thread[u]; // the node after it
// Handle the case when old_rev_thread equals to v_in
// (it also means that join and v_out coincide)
if (old_rev_thread == v_in) {
last = _thread[_last_succ[u_out]];
// Update _thread and _parent along the stem nodes (i.e. the nodes
// between u_in and u_out, whose parent have to be changed)
_thread[v_in] = stem = u_in;
_dirty_revs.push_back(v_in);
// Insert the next stem node into the thread list
new_stem = _parent[stem];
_dirty_revs.push_back(u);
// Remove the subtree of stem from the thread list
// Change the parent node and shift stem nodes
_parent[stem] = par_stem;
u = _last_succ[stem] == _last_succ[par_stem] ?
_rev_thread[par_stem] : _last_succ[stem];
_parent[u_out] = par_stem;
// Remove the subtree of u_out from the thread list except for
// the case when old_rev_thread equals to v_in
// (it also means that join and v_out coincide)
if (old_rev_thread != v_in) {
_thread[old_rev_thread] = right;
_rev_thread[right] = old_rev_thread;
// Update _rev_thread using the new _thread values
for (int i = 0; i < int(_dirty_revs.size()); ++i) {
_rev_thread[_thread[u]] = u;
// Update _pred, _forward, _last_succ and _succ_num for the
// stem nodes from u_out to u_in
int tmp_sc = 0, tmp_ls = _last_succ[u_out];
_forward[u] = !_forward[w];
tmp_sc += _succ_num[u] - _succ_num[w];
_forward[u_in] = (u_in == _source[in_arc]);
_succ_num[u_in] = old_succ_num;
// Set limits for updating _last_succ form v_in and v_out
if (_last_succ[join] == v_in) {
// Update _last_succ from v_in towards the root
for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
_last_succ[u] = _last_succ[u_out];
// Update _last_succ from v_out towards the root
if (join != old_rev_thread && v_in != old_rev_thread) {
for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
_last_succ[u] = old_rev_thread;
for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
_last_succ[u] = _last_succ[u_out];
// Update _succ_num from v_in to join
for (u = v_in; u != join; u = _parent[u]) {
_succ_num[u] += old_succ_num;
// Update _succ_num from v_out to join
for (u = v_out; u != join; u = _parent[u]) {
_succ_num[u] -= old_succ_num;
Cost sigma = _forward[u_in] ?
_pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
_pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
// Update potentials in the subtree, which has been moved
int end = _thread[_last_succ[u_in]];
for (int u = u_in; u != end; u = _thread[u]) {
bool start(PivotRule pivot_rule) {
// Select the pivot rule implementation
return start<FirstEligiblePivotRule>();
return start<BestEligiblePivotRule>();
return start<BlockSearchPivotRule>();
return start<CandidateListPivotRule>();
return start<AlteringListPivotRule>();
template <typename PivotRuleImpl>
PivotRuleImpl pivot(*this);
// Execute the Network Simplex algorithm
while (pivot.findEnteringArc()) {
bool change = findLeavingArc();
// Copy flow values to _flow_map
for (int i = 0; i != _arc_num; ++i) {
_flow_map->set(e, (*_plower)[e] + _flow[i]);
for (int i = 0; i != _arc_num; ++i) {
_flow_map->set(_arc_ref[i], _flow[i]);
// Copy potential values to _potential_map
for (NodeIt n(_graph); n != INVALID; ++n) {
_potential_map->set(n, _pi[_node_id[n]]);
}; //class NetworkSimplex
#endif //LEMON_NETWORK_SIMPLEX_H