/* -*- C++ -*- * * This file is a part of LEMON, a generic C++ optimization library * * Copyright (C) 2003-2008 * 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 * purpose. * */ #ifndef LEMON_NETWORK_SIMPLEX_H #define LEMON_NETWORK_SIMPLEX_H /// \ingroup min_cost_flow /// /// \file /// \brief Network simplex algorithm for finding a minimum cost flow. #include #include #include #include #include #include namespace lemon { /// \addtogroup min_cost_flow /// @{ /// \brief Implementation of the primal network simplex algorithm /// for finding a minimum cost flow. /// /// \ref NetworkSimplex implements the primal network simplex algorithm /// for finding a minimum cost flow. /// /// \tparam Graph The directed graph type the algorithm runs on. /// \tparam LowerMap The type of the lower bound map. /// \tparam CapacityMap The type of the capacity (upper bound) map. /// \tparam CostMap The type of the cost (length) map. /// \tparam SupplyMap The type of the supply map. /// /// \warning /// - Edge capacities and costs should be \e non-negative \e integers. /// - Supply values should be \e signed \e integers. /// - The value types of the maps should be convertible to each other. /// - \c CostMap::Value must be signed type. /// /// \note \ref NetworkSimplex provides five different pivot rule /// implementations that significantly affect the efficiency of the /// algorithm. /// By default "Block Search" pivot rule is used, which proved to be /// by far the most efficient according to our benchmark tests. /// However another pivot rule can be selected using \ref run() /// function with the proper parameter. /// /// \author Peter Kovacs template < typename Graph, typename LowerMap = typename Graph::template EdgeMap, typename CapacityMap = typename Graph::template EdgeMap, typename CostMap = typename Graph::template EdgeMap, typename SupplyMap = typename Graph::template NodeMap > class NetworkSimplex { typedef typename CapacityMap::Value Capacity; typedef typename CostMap::Value Cost; typedef typename SupplyMap::Value Supply; typedef SmartGraph SGraph; GRAPH_TYPEDEFS(typename SGraph); typedef typename SGraph::template EdgeMap SCapacityMap; typedef typename SGraph::template EdgeMap SCostMap; typedef typename SGraph::template NodeMap SSupplyMap; typedef typename SGraph::template NodeMap SPotentialMap; typedef typename SGraph::template NodeMap IntNodeMap; typedef typename SGraph::template NodeMap BoolNodeMap; typedef typename SGraph::template NodeMap NodeNodeMap; typedef typename SGraph::template NodeMap EdgeNodeMap; typedef typename SGraph::template EdgeMap IntEdgeMap; typedef typename SGraph::template EdgeMap BoolEdgeMap; typedef typename Graph::template NodeMap NodeRefMap; typedef typename Graph::template EdgeMap EdgeRefMap; typedef std::vector EdgeVector; public: /// The type of the flow map. typedef typename Graph::template EdgeMap FlowMap; /// The type of the potential map. typedef typename Graph::template NodeMap PotentialMap; public: /// Enum type to select the pivot rule used by \ref run(). enum PivotRuleEnum { FIRST_ELIGIBLE_PIVOT, BEST_ELIGIBLE_PIVOT, BLOCK_SEARCH_PIVOT, CANDIDATE_LIST_PIVOT, ALTERING_LIST_PIVOT }; private: /// \brief Map adaptor class for handling reduced edge costs. /// /// Map adaptor class for handling reduced edge costs. class ReducedCostMap : public MapBase { private: const SGraph &_gr; const SCostMap &_cost_map; const SPotentialMap &_pot_map; public: ///\e ReducedCostMap( const SGraph &gr, const SCostMap &cost_map, const SPotentialMap &pot_map ) : _gr(gr), _cost_map(cost_map), _pot_map(pot_map) {} ///\e Cost operator[](const Edge &e) const { return _cost_map[e] + _pot_map[_gr.source(e)] - _pot_map[_gr.target(e)]; } }; //class ReducedCostMap private: /// \brief Implementation of the "First Eligible" pivot rule for the /// \ref NetworkSimplex "network simplex" algorithm. /// /// This class implements the "First Eligible" pivot rule /// for the \ref NetworkSimplex "network simplex" algorithm. /// /// For more information see \ref NetworkSimplex::run(). class FirstEligiblePivotRule { private: // References to the NetworkSimplex class NetworkSimplex &_ns; EdgeVector &_edges; int _next_edge; public: /// Constructor FirstEligiblePivotRule(NetworkSimplex &ns, EdgeVector &edges) : _ns(ns), _edges(edges), _next_edge(0) {} /// Find next entering edge inline bool findEnteringEdge() { Edge e; for (int i = _next_edge; i < int(_edges.size()); ++i) { e = _edges[i]; if (_ns._state[e] * _ns._red_cost[e] < 0) { _ns._in_edge = e; _next_edge = i + 1; return true; } } for (int i = 0; i < _next_edge; ++i) { e = _edges[i]; if (_ns._state[e] * _ns._red_cost[e] < 0) { _ns._in_edge = e; _next_edge = i + 1; return true; } } return false; } }; //class FirstEligiblePivotRule /// \brief Implementation of the "Best Eligible" pivot rule for the /// \ref NetworkSimplex "network simplex" algorithm. /// /// This class implements the "Best Eligible" pivot rule /// for the \ref NetworkSimplex "network simplex" algorithm. /// /// For more information see \ref NetworkSimplex::run(). class BestEligiblePivotRule { private: // References to the NetworkSimplex class NetworkSimplex &_ns; EdgeVector &_edges; public: /// Constructor BestEligiblePivotRule(NetworkSimplex &ns, EdgeVector &edges) : _ns(ns), _edges(edges) {} /// Find next entering edge inline bool findEnteringEdge() { Cost min = 0; Edge e; for (int i = 0; i < int(_edges.size()); ++i) { e = _edges[i]; if (_ns._state[e] * _ns._red_cost[e] < min) { min = _ns._state[e] * _ns._red_cost[e]; _ns._in_edge = e; } } return min < 0; } }; //class BestEligiblePivotRule /// \brief Implementation of the "Block Search" pivot rule for the /// \ref NetworkSimplex "network simplex" algorithm. /// /// This class implements the "Block Search" pivot rule /// for the \ref NetworkSimplex "network simplex" algorithm. /// /// For more information see \ref NetworkSimplex::run(). class BlockSearchPivotRule { private: // References to the NetworkSimplex class NetworkSimplex &_ns; EdgeVector &_edges; int _block_size; int _next_edge, _min_edge; public: /// Constructor BlockSearchPivotRule(NetworkSimplex &ns, EdgeVector &edges) : _ns(ns), _edges(edges), _next_edge(0), _min_edge(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(_edges.size())), MIN_BLOCK_SIZE ); } /// Find next entering edge inline bool findEnteringEdge() { Cost curr, min = 0; Edge e; int cnt = _block_size; int i; for (i = _next_edge; i < int(_edges.size()); ++i) { e = _edges[i]; if ((curr = _ns._state[e] * _ns._red_cost[e]) < min) { min = curr; _min_edge = i; } if (--cnt == 0) { if (min < 0) break; cnt = _block_size; } } if (min == 0 || cnt > 0) { for (i = 0; i < _next_edge; ++i) { e = _edges[i]; if ((curr = _ns._state[e] * _ns._red_cost[e]) < min) { min = curr; _min_edge = i; } if (--cnt == 0) { if (min < 0) break; cnt = _block_size; } } } if (min >= 0) return false; _ns._in_edge = _edges[_min_edge]; _next_edge = i; return true; } }; //class BlockSearchPivotRule /// \brief Implementation of the "Candidate List" pivot rule for the /// \ref NetworkSimplex "network simplex" algorithm. /// /// This class implements the "Candidate List" pivot rule /// for the \ref NetworkSimplex "network simplex" algorithm. /// /// For more information see \ref NetworkSimplex::run(). class CandidateListPivotRule { private: // References to the NetworkSimplex class NetworkSimplex &_ns; EdgeVector &_edges; EdgeVector _candidates; int _list_length, _minor_limit; int _curr_length, _minor_count; int _next_edge, _min_edge; public: /// Constructor CandidateListPivotRule(NetworkSimplex &ns, EdgeVector &edges) : _ns(ns), _edges(edges), _next_edge(0), _min_edge(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(_edges.size())), MIN_LIST_LENGTH ); _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length), MIN_MINOR_LIMIT ); _curr_length = _minor_count = 0; _candidates.resize(_list_length); } /// Find next entering edge inline bool findEnteringEdge() { Cost min, curr; if (_curr_length > 0 && _minor_count < _minor_limit) { // Minor iteration: selecting the best eligible edge from // the current candidate list ++_minor_count; Edge e; min = 0; for (int i = 0; i < _curr_length; ++i) { e = _candidates[i]; curr = _ns._state[e] * _ns._red_cost[e]; if (curr < min) { min = curr; _ns._in_edge = e; } if (curr >= 0) { _candidates[i--] = _candidates[--_curr_length]; } } if (min < 0) return true; } // Major iteration: building a new candidate list Edge e; min = 0; _curr_length = 0; int i; for (i = _next_edge; i < int(_edges.size()); ++i) { e = _edges[i]; if ((curr = _ns._state[e] * _ns._red_cost[e]) < 0) { _candidates[_curr_length++] = e; if (curr < min) { min = curr; _min_edge = i; } if (_curr_length == _list_length) break; } } if (_curr_length < _list_length) { for (i = 0; i < _next_edge; ++i) { e = _edges[i]; if ((curr = _ns._state[e] * _ns._red_cost[e]) < 0) { _candidates[_curr_length++] = e; if (curr < min) { min = curr; _min_edge = i; } if (_curr_length == _list_length) break; } } } if (_curr_length == 0) return false; _minor_count = 1; _ns._in_edge = _edges[_min_edge]; _next_edge = i; return true; } }; //class CandidateListPivotRule /// \brief Implementation of the "Altering Candidate List" pivot rule /// for the \ref NetworkSimplex "network simplex" algorithm. /// /// This class implements the "Altering Candidate List" pivot rule /// for the \ref NetworkSimplex "network simplex" algorithm. /// /// For more information see \ref NetworkSimplex::run(). class AlteringListPivotRule { private: // References to the NetworkSimplex class NetworkSimplex &_ns; EdgeVector &_edges; EdgeVector _candidates; SCostMap _cand_cost; int _block_size, _head_length, _curr_length; int _next_edge; // Functor class to compare edges during sort of the candidate list class SortFunc { private: const SCostMap &_map; public: SortFunc(const SCostMap &map) : _map(map) {} bool operator()(const Edge &e1, const Edge &e2) { return _map[e1] < _map[e2]; } }; SortFunc _sort_func; public: /// Constructor AlteringListPivotRule(NetworkSimplex &ns, EdgeVector &edges) : _ns(ns), _edges(edges), _cand_cost(_ns._graph), _next_edge(0), _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 = 5; _block_size = std::max( int(BLOCK_SIZE_FACTOR * sqrt(_edges.size())), MIN_BLOCK_SIZE ); _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size), MIN_HEAD_LENGTH ); _candidates.resize(_head_length + _block_size); _curr_length = 0; } /// Find next entering edge inline bool findEnteringEdge() { // Checking the current candidate list Edge e; for (int idx = 0; idx < _curr_length; ++idx) { e = _candidates[idx]; if ((_cand_cost[e] = _ns._state[e] * _ns._red_cost[e]) >= 0) { _candidates[idx--] = _candidates[--_curr_length]; } } // Extending the list int cnt = _block_size; int last_edge = 0; int limit = _head_length; for (int i = _next_edge; i < int(_edges.size()); ++i) { e = _edges[i]; if ((_cand_cost[e] = _ns._state[e] * _ns._red_cost[e]) < 0) { _candidates[_curr_length++] = e; last_edge = i; } if (--cnt == 0) { if (_curr_length > limit) break; limit = 0; cnt = _block_size; } } if (_curr_length <= limit) { for (int i = 0; i < _next_edge; ++i) { e = _edges[i]; if ((_cand_cost[e] = _ns._state[e] * _ns._red_cost[e]) < 0) { _candidates[_curr_length++] = e; last_edge = i; } if (--cnt == 0) { if (_curr_length > limit) break; limit = 0; cnt = _block_size; } } } if (_curr_length == 0) return false; _next_edge = last_edge + 1; // Sorting the list partially EdgeVector::iterator sort_end = _candidates.begin(); EdgeVector::iterator vector_end = _candidates.begin(); for (int idx = 0; idx < _curr_length; ++idx) { ++vector_end; if (idx <= _head_length) ++sort_end; } partial_sort(_candidates.begin(), sort_end, vector_end, _sort_func); _ns._in_edge = _candidates[0]; if (_curr_length > _head_length) { _candidates[0] = _candidates[_head_length - 1]; _curr_length = _head_length - 1; } else { _candidates[0] = _candidates[_curr_length - 1]; --_curr_length; } return true; } }; //class AlteringListPivotRule private: // State constants for edges enum EdgeStateEnum { STATE_UPPER = -1, STATE_TREE = 0, STATE_LOWER = 1 }; private: // The directed graph the algorithm runs on SGraph _graph; // The original graph const Graph &_graph_ref; // The original lower bound map const LowerMap *_lower; // The capacity map SCapacityMap _capacity; // The cost map SCostMap _cost; // The supply map SSupplyMap _supply; bool _valid_supply; // Edge map of the current flow SCapacityMap _flow; // Node map of the current potentials SPotentialMap _potential; // The depth node map of the spanning tree structure IntNodeMap _depth; // The parent node map of the spanning tree structure NodeNodeMap _parent; // The pred_edge node map of the spanning tree structure EdgeNodeMap _pred_edge; // The thread node map of the spanning tree structure NodeNodeMap _thread; // The forward node map of the spanning tree structure BoolNodeMap _forward; // The state edge map IntEdgeMap _state; // The root node of the starting spanning tree Node _root; // The reduced cost map ReducedCostMap _red_cost; // The non-artifical edges EdgeVector _edges; // Members for handling the original graph FlowMap *_flow_result; PotentialMap *_potential_result; bool _local_flow; bool _local_potential; NodeRefMap _node_ref; EdgeRefMap _edge_ref; // The entering edge of the current pivot iteration. Edge _in_edge; // Temporary nodes used in the current pivot iteration. Node join, u_in, v_in, u_out, v_out; Node right, first, second, last; Node stem, par_stem, new_stem; // The maximum augment amount along the found cycle in the current // pivot iteration. Capacity delta; public : /// \brief General constructor (with lower bounds). /// /// General constructor (with lower bounds). /// /// \param graph The directed graph the algorithm runs on. /// \param lower The lower bounds of the edges. /// \param capacity The capacities (upper bounds) of the edges. /// \param cost The cost (length) values of the edges. /// \param supply The supply values of the nodes (signed). NetworkSimplex( const Graph &graph, const LowerMap &lower, const CapacityMap &capacity, const CostMap &cost, const SupplyMap &supply ) : _graph(), _graph_ref(graph), _lower(&lower), _capacity(_graph), _cost(_graph), _supply(_graph), _flow(_graph), _potential(_graph), _depth(_graph), _parent(_graph), _pred_edge(_graph), _thread(_graph), _forward(_graph), _state(_graph), _red_cost(_graph, _cost, _potential), _flow_result(NULL), _potential_result(NULL), _local_flow(false), _local_potential(false), _node_ref(graph), _edge_ref(graph) { // Checking the sum of supply values Supply sum = 0; for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) sum += supply[n]; if (!(_valid_supply = sum == 0)) return; // Copying _graph_ref to _graph _graph.reserveNode(countNodes(_graph_ref) + 1); _graph.reserveEdge(countEdges(_graph_ref) + countNodes(_graph_ref)); copyGraph(_graph, _graph_ref) .edgeMap(_cost, cost) .nodeRef(_node_ref) .edgeRef(_edge_ref) .run(); // Removing non-zero lower bounds for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) { _capacity[_edge_ref[e]] = capacity[e] - lower[e]; } for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) { Supply s = supply[n]; for (typename Graph::InEdgeIt e(_graph_ref, n); e != INVALID; ++e) s += lower[e]; for (typename Graph::OutEdgeIt e(_graph_ref, n); e != INVALID; ++e) s -= lower[e]; _supply[_node_ref[n]] = s; } } /// \brief General constructor (without lower bounds). /// /// General constructor (without lower bounds). /// /// \param graph The directed graph the algorithm runs on. /// \param capacity The capacities (upper bounds) of the edges. /// \param cost The cost (length) values of the edges. /// \param supply The supply values of the nodes (signed). NetworkSimplex( const Graph &graph, const CapacityMap &capacity, const CostMap &cost, const SupplyMap &supply ) : _graph(), _graph_ref(graph), _lower(NULL), _capacity(_graph), _cost(_graph), _supply(_graph), _flow(_graph), _potential(_graph), _depth(_graph), _parent(_graph), _pred_edge(_graph), _thread(_graph), _forward(_graph), _state(_graph), _red_cost(_graph, _cost, _potential), _flow_result(NULL), _potential_result(NULL), _local_flow(false), _local_potential(false), _node_ref(graph), _edge_ref(graph) { // Checking the sum of supply values Supply sum = 0; for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) sum += supply[n]; if (!(_valid_supply = sum == 0)) return; // Copying _graph_ref to graph copyGraph(_graph, _graph_ref) .edgeMap(_capacity, capacity) .edgeMap(_cost, cost) .nodeMap(_supply, supply) .nodeRef(_node_ref) .edgeRef(_edge_ref) .run(); } /// \brief Simple constructor (with lower bounds). /// /// Simple constructor (with lower bounds). /// /// \param graph The directed graph the algorithm runs on. /// \param lower The lower bounds of the edges. /// \param capacity The capacities (upper bounds) of the edges. /// \param cost The cost (length) values of the edges. /// \param s The source node. /// \param t The target node. /// \param flow_value 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). NetworkSimplex( const Graph &graph, const LowerMap &lower, const CapacityMap &capacity, const CostMap &cost, typename Graph::Node s, typename Graph::Node t, typename SupplyMap::Value flow_value ) : _graph(), _graph_ref(graph), _lower(&lower), _capacity(_graph), _cost(_graph), _supply(_graph), _flow(_graph), _potential(_graph), _depth(_graph), _parent(_graph), _pred_edge(_graph), _thread(_graph), _forward(_graph), _state(_graph), _red_cost(_graph, _cost, _potential), _flow_result(NULL), _potential_result(NULL), _local_flow(false), _local_potential(false), _node_ref(graph), _edge_ref(graph) { // Copying _graph_ref to graph copyGraph(_graph, _graph_ref) .edgeMap(_cost, cost) .nodeRef(_node_ref) .edgeRef(_edge_ref) .run(); // Removing non-zero lower bounds for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) { _capacity[_edge_ref[e]] = capacity[e] - lower[e]; } for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) { Supply sum = 0; if (n == s) sum = flow_value; if (n == t) sum = -flow_value; for (typename Graph::InEdgeIt e(_graph_ref, n); e != INVALID; ++e) sum += lower[e]; for (typename Graph::OutEdgeIt e(_graph_ref, n); e != INVALID; ++e) sum -= lower[e]; _supply[_node_ref[n]] = sum; } _valid_supply = true; } /// \brief Simple constructor (without lower bounds). /// /// Simple constructor (without lower bounds). /// /// \param graph The directed graph the algorithm runs on. /// \param capacity The capacities (upper bounds) of the edges. /// \param cost The cost (length) values of the edges. /// \param s The source node. /// \param t The target node. /// \param flow_value 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). NetworkSimplex( const Graph &graph, const CapacityMap &capacity, const CostMap &cost, typename Graph::Node s, typename Graph::Node t, typename SupplyMap::Value flow_value ) : _graph(), _graph_ref(graph), _lower(NULL), _capacity(_graph), _cost(_graph), _supply(_graph, 0), _flow(_graph), _potential(_graph), _depth(_graph), _parent(_graph), _pred_edge(_graph), _thread(_graph), _forward(_graph), _state(_graph), _red_cost(_graph, _cost, _potential), _flow_result(NULL), _potential_result(NULL), _local_flow(false), _local_potential(false), _node_ref(graph), _edge_ref(graph) { // Copying _graph_ref to graph copyGraph(_graph, _graph_ref) .edgeMap(_capacity, capacity) .edgeMap(_cost, cost) .nodeRef(_node_ref) .edgeRef(_edge_ref) .run(); _supply[_node_ref[s]] = flow_value; _supply[_node_ref[t]] = -flow_value; _valid_supply = true; } /// Destructor. ~NetworkSimplex() { if (_local_flow) delete _flow_result; if (_local_potential) delete _potential_result; } /// \brief Set the flow map. /// /// Set the flow map. /// /// \return \c (*this) NetworkSimplex& flowMap(FlowMap &map) { if (_local_flow) { delete _flow_result; _local_flow = false; } _flow_result = ↦ return *this; } /// \brief Set the potential map. /// /// Set the potential map. /// /// \return \c (*this) NetworkSimplex& potentialMap(PotentialMap &map) { if (_local_potential) { delete _potential_result; _local_potential = false; } _potential_result = ↦ return *this; } /// \name Execution control /// @{ /// \brief Runs the algorithm. /// /// Runs the algorithm. /// /// \param pivot_rule The pivot rule that is used during the /// algorithm. /// /// The available pivot rules: /// /// - FIRST_ELIGIBLE_PIVOT The next eligible edge is selected in /// a wraparound fashion in every iteration /// (\ref FirstEligiblePivotRule). /// /// - BEST_ELIGIBLE_PIVOT The best eligible edge is selected in /// every iteration (\ref BestEligiblePivotRule). /// /// - BLOCK_SEARCH_PIVOT A specified number of edges are examined in /// every iteration in a wraparound fashion and the best eligible /// edge is selected from this block (\ref BlockSearchPivotRule). /// /// - CANDIDATE_LIST_PIVOT In a major iteration a candidate list is /// built from eligible edges in a wraparound fashion and in the /// following minor iterations the best eligible edge is selected /// from this list (\ref CandidateListPivotRule). /// /// - ALTERING_LIST_PIVOT It is a modified version of the /// "Candidate List" pivot rule. It keeps only the several best /// eligible edges from the former candidate list and extends this /// list in every iteration (\ref AlteringListPivotRule). /// /// According to our comprehensive benchmark tests the "Block Search" /// pivot rule proved to be by far the fastest and the most robust /// on various test inputs. Thus it is the default option. /// /// \return \c true if a feasible flow can be found. bool run(PivotRuleEnum pivot_rule = BLOCK_SEARCH_PIVOT) { return init() && start(pivot_rule); } /// @} /// \name Query Functions /// The results of the algorithm can be obtained using these /// functions.\n /// \ref lemon::NetworkSimplex::run() "run()" must be called before /// using them. /// @{ /// \brief Return a const reference to the edge map storing the /// found flow. /// /// Return a const reference to the edge map storing the found flow. /// /// \pre \ref run() must be called before using this function. const FlowMap& flowMap() const { return *_flow_result; } /// \brief Return a const reference to the node map storing the /// found potentials (the dual solution). /// /// Return a const reference to the node map storing the found /// potentials (the dual solution). /// /// \pre \ref run() must be called before using this function. const PotentialMap& potentialMap() const { return *_potential_result; } /// \brief Return the flow on the given edge. /// /// Return the flow on the given edge. /// /// \pre \ref run() must be called before using this function. Capacity flow(const typename Graph::Edge& edge) const { return (*_flow_result)[edge]; } /// \brief Return the potential of the given node. /// /// Return the potential of the given node. /// /// \pre \ref run() must be called before using this function. Cost potential(const typename Graph::Node& node) const { return (*_potential_result)[node]; } /// \brief Return the total cost of the found flow. /// /// Return the total cost of the found flow. The complexity of the /// function is \f$ O(e) \f$. /// /// \pre \ref run() must be called before using this function. Cost totalCost() const { Cost c = 0; for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) c += (*_flow_result)[e] * _cost[_edge_ref[e]]; return c; } /// @} private: /// \brief Extend the underlying graph and initialize all the /// node and edge maps. bool init() { if (!_valid_supply) return false; // Initializing result maps if (!_flow_result) { _flow_result = new FlowMap(_graph_ref); _local_flow = true; } if (!_potential_result) { _potential_result = new PotentialMap(_graph_ref); _local_potential = true; } // Initializing the edge vector and the edge maps _edges.reserve(countEdges(_graph)); for (EdgeIt e(_graph); e != INVALID; ++e) { _edges.push_back(e); _flow[e] = 0; _state[e] = STATE_LOWER; } // Adding an artificial root node to the graph _root = _graph.addNode(); _parent[_root] = INVALID; _pred_edge[_root] = INVALID; _depth[_root] = 0; _supply[_root] = 0; _potential[_root] = 0; // Adding artificial edges to the graph and initializing the node // maps of the spanning tree data structure Node last = _root; Edge e; Cost max_cost = std::numeric_limits::max() / 4; for (NodeIt u(_graph); u != INVALID; ++u) { if (u == _root) continue; _thread[last] = u; last = u; _parent[u] = _root; _depth[u] = 1; if (_supply[u] >= 0) { e = _graph.addEdge(u, _root); _flow[e] = _supply[u]; _forward[u] = true; _potential[u] = -max_cost; } else { e = _graph.addEdge(_root, u); _flow[e] = -_supply[u]; _forward[u] = false; _potential[u] = max_cost; } _cost[e] = max_cost; _capacity[e] = std::numeric_limits::max(); _state[e] = STATE_TREE; _pred_edge[u] = e; } _thread[last] = _root; return true; } /// Find the join node. inline Node findJoinNode() { Node u = _graph.source(_in_edge); Node v = _graph.target(_in_edge); while (u != v) { if (_depth[u] == _depth[v]) { u = _parent[u]; v = _parent[v]; } else if (_depth[u] > _depth[v]) u = _parent[u]; else v = _parent[v]; } return u; } /// \brief Find the leaving edge of the cycle. /// \return \c true if the leaving edge is not the same as the /// entering edge. inline bool findLeavingEdge() { // Initializing first and second nodes according to the direction // of the cycle if (_state[_in_edge] == STATE_LOWER) { first = _graph.source(_in_edge); second = _graph.target(_in_edge); } else { first = _graph.target(_in_edge); second = _graph.source(_in_edge); } delta = _capacity[_in_edge]; bool result = false; Capacity d; Edge e; // Searching the cycle along the path form the first node to the // root node for (Node u = first; u != join; u = _parent[u]) { e = _pred_edge[u]; d = _forward[u] ? _flow[e] : _capacity[e] - _flow[e]; if (d < delta) { delta = d; u_out = u; u_in = first; v_in = second; result = true; } } // Searching the cycle along the path form the second node to the // root node for (Node u = second; u != join; u = _parent[u]) { e = _pred_edge[u]; d = _forward[u] ? _capacity[e] - _flow[e] : _flow[e]; if (d <= delta) { delta = d; u_out = u; u_in = second; v_in = first; result = true; } } return result; } /// Change \c flow and \c state edge maps. inline void changeFlows(bool change) { // Augmenting along the cycle if (delta > 0) { Capacity val = _state[_in_edge] * delta; _flow[_in_edge] += val; for (Node u = _graph.source(_in_edge); u != join; u = _parent[u]) { _flow[_pred_edge[u]] += _forward[u] ? -val : val; } for (Node u = _graph.target(_in_edge); u != join; u = _parent[u]) { _flow[_pred_edge[u]] += _forward[u] ? val : -val; } } // Updating the state of the entering and leaving edges if (change) { _state[_in_edge] = STATE_TREE; _state[_pred_edge[u_out]] = (_flow[_pred_edge[u_out]] == 0) ? STATE_LOWER : STATE_UPPER; } else { _state[_in_edge] = -_state[_in_edge]; } } /// Update \c thread and \c parent node maps. inline void updateThreadParent() { Node u; v_out = _parent[u_out]; // Handling the case when join and v_out coincide bool par_first = false; if (join == v_out) { for (u = join; u != u_in && u != v_in; u = _thread[u]) ; if (u == v_in) { par_first = true; while (_thread[u] != u_out) u = _thread[u]; first = u; } } // Finding the last successor of u_in (u) and the node after it // (right) according to the thread index for (u = u_in; _depth[_thread[u]] > _depth[u_in]; u = _thread[u]) ; right = _thread[u]; if (_thread[v_in] == u_out) { for (last = u; _depth[last] > _depth[u_out]; last = _thread[last]) ; if (last == u_out) last = _thread[last]; } else last = _thread[v_in]; // Updating stem nodes _thread[v_in] = stem = u_in; par_stem = v_in; while (stem != u_out) { _thread[u] = new_stem = _parent[stem]; // Finding the node just before the stem node (u) according to // the original thread index for (u = new_stem; _thread[u] != stem; u = _thread[u]) ; _thread[u] = right; // Changing the parent node of stem and shifting stem and // par_stem nodes _parent[stem] = par_stem; par_stem = stem; stem = new_stem; // Finding the last successor of stem (u) and the node after it // (right) according to the thread index for (u = stem; _depth[_thread[u]] > _depth[stem]; u = _thread[u]) ; right = _thread[u]; } _parent[u_out] = par_stem; _thread[u] = last; if (join == v_out && par_first) { if (first != v_in) _thread[first] = right; } else { for (u = v_out; _thread[u] != u_out; u = _thread[u]) ; _thread[u] = right; } } /// Update \c pred_edge and \c forward node maps. inline void updatePredEdge() { Node u = u_out, v; while (u != u_in) { v = _parent[u]; _pred_edge[u] = _pred_edge[v]; _forward[u] = !_forward[v]; u = v; } _pred_edge[u_in] = _in_edge; _forward[u_in] = (u_in == _graph.source(_in_edge)); } /// Update \c depth and \c potential node maps. inline void updateDepthPotential() { _depth[u_in] = _depth[v_in] + 1; Cost sigma = _forward[u_in] ? _potential[v_in] - _potential[u_in] - _cost[_pred_edge[u_in]] : _potential[v_in] - _potential[u_in] + _cost[_pred_edge[u_in]]; _potential[u_in] += sigma; for(Node u = _thread[u_in]; _parent[u] != INVALID; u = _thread[u]) { _depth[u] = _depth[_parent[u]] + 1; if (_depth[u] <= _depth[u_in]) break; _potential[u] += sigma; } } /// Execute the algorithm. bool start(PivotRuleEnum pivot_rule) { // Selecting the pivot rule implementation switch (pivot_rule) { case FIRST_ELIGIBLE_PIVOT: return start(); case BEST_ELIGIBLE_PIVOT: return start(); case BLOCK_SEARCH_PIVOT: return start(); case CANDIDATE_LIST_PIVOT: return start(); case ALTERING_LIST_PIVOT: return start(); } return false; } template bool start() { PivotRuleImplementation pivot(*this, _edges); // Executing the network simplex algorithm while (pivot.findEnteringEdge()) { join = findJoinNode(); bool change = findLeavingEdge(); changeFlows(change); if (change) { updateThreadParent(); updatePredEdge(); updateDepthPotential(); } } // Checking if the flow amount equals zero on all the artificial // edges for (InEdgeIt e(_graph, _root); e != INVALID; ++e) if (_flow[e] > 0) return false; for (OutEdgeIt e(_graph, _root); e != INVALID; ++e) if (_flow[e] > 0) return false; // Copying flow values to _flow_result if (_lower) { for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) (*_flow_result)[e] = (*_lower)[e] + _flow[_edge_ref[e]]; } else { for (typename Graph::EdgeIt e(_graph_ref); e != INVALID; ++e) (*_flow_result)[e] = _flow[_edge_ref[e]]; } // Copying potential values to _potential_result for (typename Graph::NodeIt n(_graph_ref); n != INVALID; ++n) (*_potential_result)[n] = _potential[_node_ref[n]]; return true; } }; //class NetworkSimplex ///@} } //namespace lemon #endif //LEMON_NETWORK_SIMPLEX_H