/* -*- 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_algs
/// \brief Network Simplex algorithm for finding a minimum cost flow.
/// \addtogroup min_cost_flow_algs
/// \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"
/// \ref amo93networkflows, \ref dantzig63linearprog,
/// \ref kellyoneill91netsimplex.
/// 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 directions of the supply/demand inequality
/// constraints. For more information, see \ref SupplyType.
/// Most of the parameters of the problem (except for the digraph)
/// can be given using separate functions, and the algorithm can be
/// executed using the \ref run() function. If some parameters are not
/// specified, then default values will be used.
/// \tparam GR The digraph type the algorithm runs on.
/// \tparam V 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 V.
/// \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 V = int, typename C = V>
/// The type of the flow amounts, capacity bounds and supply values
/// The type of the arc costs
/// \brief Problem type constants for the \c run() function.
/// Enum type containing the problem type constants that can be
/// returned by the \ref run() function of the algorithm.
/// The problem has no feasible solution (flow).
/// The problem has optimal solution (i.e. it is feasible and
/// bounded), and the algorithm has found optimal flow and node
/// potentials (primal and dual solutions).
/// The objective function of the problem is unbounded, i.e.
/// there is a directed cycle having negative total cost and
/// infinite upper bound.
/// \brief Constants for selecting the type of the supply constraints.
/// Enum type containing constants for selecting the supply 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 supply type is \c GEQ, the \c LEQ type can be
/// selected using \ref supplyType().
/// The equality form is a special case of both supply types.
/// This option means that there are <em>"greater or equal"</em>
/// supply/demand constraints in the definition of the problem.
/// This option means that there are <em>"less or equal"</em>
/// supply/demand constraints in the definition of the problem.
/// \brief Constants for selecting the pivot rule.
/// Enum type containing constants for selecting the pivot rule for
/// the \ref run() function.
/// \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 \e First \e Eligible pivot rule.
/// The next eligible arc is selected in a wraparound fashion
/// The \e Best \e Eligible pivot rule.
/// The best eligible arc is selected in every iteration.
/// The \e Block \e 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 \e Candidate \e 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 \e Altering \e Candidate \e 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.
TEMPLATE_DIGRAPH_TYPEDEFS(GR);
typedef std::vector<int> IntVector;
typedef std::vector<bool> BoolVector;
typedef std::vector<Value> ValueVector;
typedef std::vector<Cost> CostVector;
// State constants for arcs
// Data related to the underlying digraph
// Parameters of the problem
// 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;
/// \brief Constant for infinite upper bounds (capacities).
/// Constant for infinite upper bounds (capacities).
/// It is \c std::numeric_limits<Value>::infinity() if available,
/// \c std::numeric_limits<Value>::max() otherwise.
// 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), _search_arc_num(ns._search_arc_num),
// Find next entering arc
for (int e = _next_arc; e < _search_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), _search_arc_num(ns._search_arc_num)
// Find next entering arc
for (int e = 0; e < _search_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), _search_arc_num(ns._search_arc_num),
// The main parameters of the pivot rule
const double BLOCK_SIZE_FACTOR = 0.5;
const int MIN_BLOCK_SIZE = 10;
_block_size = std::max( int(BLOCK_SIZE_FACTOR *
std::sqrt(double(_search_arc_num))),
// Find next entering arc
for (e = _next_arc; e < _search_arc_num; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
if (min < 0) goto search_end;
for (e = 0; e < _next_arc; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
if (min < 0) goto search_end;
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), _search_arc_num(ns._search_arc_num),
// The main parameters of the pivot rule
const double LIST_LENGTH_FACTOR = 0.25;
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 *
std::sqrt(double(_search_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
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];
if (min < 0) return true;
// Major iteration: build a new candidate list
for (e = _next_arc; e < _search_arc_num; ++e) {
c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[_curr_length++] = e;
if (_curr_length == _list_length) goto search_end;
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) goto search_end;
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), _search_arc_num(ns._search_arc_num),
_next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
// The main parameters of the pivot rule
const double BLOCK_SIZE_FACTOR = 1.0;
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 *
std::sqrt(double(_search_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 (e = _next_arc; e < _search_arc_num; ++e) {
_cand_cost[e] = _state[e] *
(_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
_candidates[_curr_length++] = e;
if (_curr_length > limit) goto search_end;
for (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) goto search_end;
if (_curr_length == 0) return false;
// 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.
/// \param arc_mixing Indicate if the arcs have to be stored in a
/// mixed order in the internal data structure.
/// In special cases, it could lead to better overall performance,
/// but it is usually slower. Therefore it is disabled by default.
NetworkSimplex(const GR& graph, bool arc_mixing = false) :
_graph(graph), _node_id(graph), _arc_id(graph),
INF(std::numeric_limits<Value>::has_infinity ?
std::numeric_limits<Value>::infinity() :
std::numeric_limits<Value>::max())
LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
"The flow type of NetworkSimplex must be signed");
LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
"The cost type of NetworkSimplex must be signed");
_node_num = countNodes(_graph);
_arc_num = countArcs(_graph);
int all_node_num = _node_num + 1;
int max_arc_num = _arc_num + 2 * _node_num;
_source.resize(max_arc_num);
_target.resize(max_arc_num);
_cap.resize(max_arc_num);
_cost.resize(max_arc_num);
_supply.resize(all_node_num);
_flow.resize(max_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(max_arc_num);
for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
// Store the arcs in a mixed order
int k = std::max(int(std::sqrt(double(_arc_num))), 10);
for (ArcIt a(_graph); a != INVALID; ++a) {
_source[i] = _node_id[_graph.source(a)];
_target[i] = _node_id[_graph.target(a)];
if ((i += k) >= _arc_num) i = ++j;
// Store the arcs in the original order
for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
_source[i] = _node_id[_graph.source(a)];
_target[i] = _node_id[_graph.target(a)];
/// 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 it is not used before calling \ref run(), the lower bounds
/// will be set to zero on all arcs.
/// \param map An arc map storing the lower bounds.
/// Its \c Value type must be convertible to the \c Value type
/// \return <tt>(*this)</tt>
template <typename LowerMap>
NetworkSimplex& lowerMap(const LowerMap& map) {
for (ArcIt a(_graph); a != INVALID; ++a) {
_lower[_arc_id[a]] = map[a];
/// \brief Set the upper bounds (capacities) on the arcs.
/// This function sets the upper bounds (capacities) on the arcs.
/// If it is not used before calling \ref run(), the upper bounds
/// will be set to \ref INF on all arcs (i.e. the flow value will be
/// unbounded from above on each arc).
/// \param map An arc map storing the upper bounds.
/// Its \c Value type must be convertible to the \c Value type
/// \return <tt>(*this)</tt>
template<typename UpperMap>
NetworkSimplex& upperMap(const UpperMap& map) {
for (ArcIt a(_graph); a != INVALID; ++a) {
_upper[_arc_id[a]] = map[a];
/// \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>
template<typename CostMap>
NetworkSimplex& costMap(const CostMap& map) {
for (ArcIt a(_graph); a != INVALID; ++a) {
_cost[_arc_id[a]] = map[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.
/// \param map A node map storing the supply values.
/// Its \c Value type must be convertible to the \c Value type
/// \return <tt>(*this)</tt>
template<typename SupplyMap>
NetworkSimplex& supplyMap(const SupplyMap& map) {
for (NodeIt n(_graph); n != INVALID; ++n) {
_supply[_node_id[n]] = map[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.
/// Using this function has the same effect as using \ref supplyMap()
/// with such a map in which \c k is assigned to \c s, \c -k is
/// assigned to \c t and all other nodes have zero supply value.
/// \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, Value k) {
for (int i = 0; i != _node_num; ++i) {
_supply[_node_id[s]] = k;
_supply[_node_id[t]] = -k;
/// \brief Set the type of the supply constraints.
/// This function sets the type of the supply/demand constraints.
/// If it is not used before calling \ref run(), the \ref GEQ supply
/// For more information, see \ref SupplyType.
/// \return <tt>(*this)</tt>
NetworkSimplex& supplyType(SupplyType supply_type) {
/// \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 costMap(), \ref supplyMap(), \ref stSupply(),
/// NetworkSimplex<ListDigraph> ns(graph);
/// ns.lowerMap(lower).upperMap(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.
/// However, the underlying digraph must not be modified after this
/// class have been constructed, since it copies and extends the graph.
/// \param pivot_rule The pivot rule that will be used during the
/// algorithm. For more information, see \ref PivotRule.
/// \return \c INFEASIBLE if no feasible flow exists,
/// \n \c OPTIMAL if the problem has optimal solution
/// (i.e. it is feasible and bounded), and the algorithm has found
/// optimal flow and node potentials (primal and dual solutions),
/// \n \c UNBOUNDED if the objective function of the problem is
/// unbounded, i.e. there is a directed cycle having negative total
/// cost and infinite upper bound.
/// \see ProblemType, PivotRule
ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
if (!init()) return INFEASIBLE;
return 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 costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
/// It is useful for multiple run() calls. If this function is not
/// used, all the parameters given before are kept for the next
/// However, the underlying digraph must not be modified after this
/// class have been constructed, since it copies and extends the graph.
/// NetworkSimplex<ListDigraph> ns(graph);
/// ns.lowerMap(lower).upperMap(upper).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.upperMap(capacity).costMap(cost)
/// .supplyMap(sup).run();
/// \return <tt>(*this)</tt>
NetworkSimplex& reset() {
for (int i = 0; i != _node_num; ++i) {
for (int i = 0; i != _arc_num; ++i) {
/// \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.
/// Its complexity 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.
template <typename Number>
Number totalCost() const {
for (ArcIt a(_graph); a != INVALID; ++a) {
c += Number(_flow[i]) * Number(_cost[i]);
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.
Value flow(const Arc& a) const {
return _flow[_arc_id[a]];
/// \brief Return the flow map (the primal solution).
/// This function copies the flow value on each arc into the given
/// map. The \c Value type of the algorithm must be convertible to
/// the \c Value type of the map.
/// \pre \ref run() must be called before using this function.
template <typename FlowMap>
void flowMap(FlowMap &map) const {
for (ArcIt a(_graph); a != INVALID; ++a) {
map.set(a, _flow[_arc_id[a]]);
/// \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 {
/// \brief Return the potential map (the dual solution).
/// This function copies the potential (dual value) of each node
/// The \c Cost type of the algorithm must be convertible to the
/// \c Value type of the map.
/// \pre \ref run() must be called before using this function.
template <typename PotentialMap>
void potentialMap(PotentialMap &map) const {
for (NodeIt n(_graph); n != INVALID; ++n) {
map.set(n, _pi[_node_id[n]]);
// Initialize internal data structures
if (_node_num == 0) return false;
// Check the sum of supply values
for (int i = 0; i != _node_num; ++i) {
_sum_supply += _supply[i];
if ( !((_stype == GEQ && _sum_supply <= 0) ||
(_stype == LEQ && _sum_supply >= 0)) ) return false;
// Remove non-zero lower bounds
for (int i = 0; i != _arc_num; ++i) {
_cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
_cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
_supply[_source[i]] -= c;
_supply[_target[i]] += c;
for (int i = 0; i != _arc_num; ++i) {
// Initialize artifical cost
if (std::numeric_limits<Cost>::is_exact) {
ART_COST = std::numeric_limits<Cost>::max() / 2 + 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;
for (int i = 0; i != _arc_num; ++i) {
// Set data for the artificial root node
_succ_num[_root] = _node_num + 1;
_last_succ[_root] = _root - 1;
_supply[_root] = -_sum_supply;
// Add artificial arcs and initialize the spanning tree data structure
_search_arc_num = _arc_num;
_all_arc_num = _arc_num + _node_num;
for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
else if (_sum_supply > 0) {
// LEQ supply constraints
_search_arc_num = _arc_num + _node_num;
int f = _arc_num + _node_num;
for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
// GEQ supply constraints
_search_arc_num = _arc_num + _node_num;
int f = _arc_num + _node_num;
for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
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]) {
_flow[e] : (_cap[e] == INF ? INF : _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]) {
(_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
// Change _flow and _state vectors
void changeFlow(bool change) {
// Augment along the cycle
Value 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]) {
ProblemType start(PivotRule pivot_rule) {
// Select the pivot rule implementation
return start<FirstEligiblePivotRule>();
return start<BestEligiblePivotRule>();
return start<BlockSearchPivotRule>();
return start<CandidateListPivotRule>();
return start<AlteringListPivotRule>();
return INFEASIBLE; // avoid warning
template <typename PivotRuleImpl>
PivotRuleImpl pivot(*this);
// Execute the Network Simplex algorithm
while (pivot.findEnteringArc()) {
bool change = findLeavingArc();
if (delta >= INF) return UNBOUNDED;
for (int e = _search_arc_num; e != _all_arc_num; ++e) {
if (_flow[e] != 0) return INFEASIBLE;
// Transform the solution and the supply map to the original form
for (int i = 0; i != _arc_num; ++i) {
_supply[_source[i]] += c;
_supply[_target[i]] -= c;
// Shift potentials to meet the requirements of the GEQ/LEQ type
Cost max_pot = std::numeric_limits<Cost>::min();
for (int i = 0; i != _node_num; ++i) {
if (_pi[i] > max_pot) max_pot = _pi[i];
for (int i = 0; i != _node_num; ++i)
Cost min_pot = std::numeric_limits<Cost>::max();
for (int i = 0; i != _node_num; ++i) {
if (_pi[i] < min_pot) min_pot = _pi[i];
for (int i = 0; i != _node_num; ++i)
}; //class NetworkSimplex
#endif //LEMON_NETWORK_SIMPLEX_H