alpar@956: /* -*- mode: C++; indent-tabs-mode: nil; -*- kpeter@874: * alpar@956: * This file is a part of LEMON, a generic C++ optimization library. kpeter@874: * alpar@956: * Copyright (C) 2003-2010 kpeter@874: * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport kpeter@874: * (Egervary Research Group on Combinatorial Optimization, EGRES). kpeter@874: * kpeter@874: * Permission to use, modify and distribute this software is granted kpeter@874: * provided that this copyright notice appears in all copies. For kpeter@874: * precise terms see the accompanying LICENSE file. kpeter@874: * kpeter@874: * This software is provided "AS IS" with no warranty of any kind, kpeter@874: * express or implied, and with no claim as to its suitability for any kpeter@874: * purpose. kpeter@874: * kpeter@874: */ kpeter@874: kpeter@874: #ifndef LEMON_COST_SCALING_H kpeter@874: #define LEMON_COST_SCALING_H kpeter@874: kpeter@874: /// \ingroup min_cost_flow_algs kpeter@874: /// \file kpeter@874: /// \brief Cost scaling algorithm for finding a minimum cost flow. kpeter@874: kpeter@874: #include kpeter@874: #include kpeter@874: #include kpeter@874: kpeter@874: #include kpeter@874: #include kpeter@874: #include kpeter@875: #include kpeter@874: #include kpeter@874: #include kpeter@874: kpeter@874: namespace lemon { kpeter@874: kpeter@875: /// \brief Default traits class of CostScaling algorithm. kpeter@875: /// kpeter@875: /// Default traits class of CostScaling algorithm. kpeter@875: /// \tparam GR Digraph type. kpeter@878: /// \tparam V The number type used for flow amounts, capacity bounds kpeter@875: /// and supply values. By default it is \c int. kpeter@878: /// \tparam C The number type used for costs and potentials. kpeter@875: /// By default it is the same as \c V. kpeter@875: #ifdef DOXYGEN kpeter@875: template kpeter@875: #else kpeter@875: template < typename GR, typename V = int, typename C = V, kpeter@875: bool integer = std::numeric_limits::is_integer > kpeter@875: #endif kpeter@875: struct CostScalingDefaultTraits kpeter@875: { kpeter@875: /// The type of the digraph kpeter@875: typedef GR Digraph; kpeter@875: /// The type of the flow amounts, capacity bounds and supply values kpeter@875: typedef V Value; kpeter@875: /// The type of the arc costs kpeter@875: typedef C Cost; kpeter@875: kpeter@875: /// \brief The large cost type used for internal computations kpeter@875: /// kpeter@875: /// The large cost type used for internal computations. kpeter@875: /// It is \c long \c long if the \c Cost type is integer, kpeter@875: /// otherwise it is \c double. kpeter@875: /// \c Cost must be convertible to \c LargeCost. kpeter@875: typedef double LargeCost; kpeter@875: }; kpeter@875: kpeter@875: // Default traits class for integer cost types kpeter@875: template kpeter@875: struct CostScalingDefaultTraits kpeter@875: { kpeter@875: typedef GR Digraph; kpeter@875: typedef V Value; kpeter@875: typedef C Cost; kpeter@875: #ifdef LEMON_HAVE_LONG_LONG kpeter@875: typedef long long LargeCost; kpeter@875: #else kpeter@875: typedef long LargeCost; kpeter@875: #endif kpeter@875: }; kpeter@875: kpeter@875: kpeter@874: /// \addtogroup min_cost_flow_algs kpeter@874: /// @{ kpeter@874: kpeter@875: /// \brief Implementation of the Cost Scaling algorithm for kpeter@875: /// finding a \ref min_cost_flow "minimum cost flow". kpeter@874: /// kpeter@875: /// \ref CostScaling implements a cost scaling algorithm that performs kpeter@879: /// push/augment and relabel operations for finding a \ref min_cost_flow alpar@1221: /// "minimum cost flow" \cite amo93networkflows, \cite goldberg90approximation, alpar@1221: /// \cite goldberg97efficient, \cite bunnagel98efficient. kpeter@879: /// It is a highly efficient primal-dual solution method, which kpeter@875: /// can be viewed as the generalization of the \ref Preflow kpeter@875: /// "preflow push-relabel" algorithm for the maximum flow problem. kpeter@1217: /// It is a polynomial algorithm, its running time complexity is kpeter@1217: /// \f$O(n^2e\log(nK))\f$, where K denotes the maximum arc cost. kpeter@874: /// 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: /// kpeter@875: /// Most of the parameters of the problem (except for the digraph) kpeter@875: /// can be given using separate functions, and the algorithm can be kpeter@875: /// executed using the \ref run() function. If some parameters are not kpeter@875: /// specified, then default values will be used. kpeter@874: /// kpeter@875: /// \tparam GR The digraph type the algorithm runs on. kpeter@878: /// \tparam V The number type used for flow amounts, capacity bounds kpeter@891: /// 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@891: /// algorithm. By default, it is the same as \c V. kpeter@891: /// \tparam TR The traits class that defines various types used by the kpeter@891: /// algorithm. By default, it is \ref CostScalingDefaultTraits kpeter@891: /// "CostScalingDefaultTraits". kpeter@891: /// In most cases, this parameter should not be set directly, kpeter@891: /// consider to use the named template parameters instead. kpeter@874: /// 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@875: /// be integer. kpeter@1023: /// \warning This algorithm does not support negative costs for kpeter@1023: /// arcs having infinite upper bound. kpeter@876: /// kpeter@876: /// \note %CostScaling provides three different internal methods, kpeter@876: /// from which the most efficient one is used by default. kpeter@876: /// For more information, see \ref Method. kpeter@875: #ifdef DOXYGEN kpeter@875: template kpeter@875: #else kpeter@875: template < typename GR, typename V = int, typename C = V, kpeter@875: typename TR = CostScalingDefaultTraits > kpeter@875: #endif kpeter@874: class CostScaling kpeter@874: { kpeter@875: public: kpeter@874: kpeter@875: /// The type of the digraph kpeter@875: typedef typename TR::Digraph Digraph; kpeter@875: /// The type of the flow amounts, capacity bounds and supply values kpeter@875: typedef typename TR::Value Value; kpeter@875: /// The type of the arc costs kpeter@875: typedef typename TR::Cost Cost; kpeter@874: kpeter@875: /// \brief The large cost type kpeter@875: /// kpeter@875: /// The large cost type used for internal computations. kpeter@891: /// By default, it is \c long \c long if the \c Cost type is integer, kpeter@875: /// otherwise it is \c double. kpeter@875: typedef typename TR::LargeCost LargeCost; kpeter@874: alpar@1250: /// \brief The \ref lemon::CostScalingDefaultTraits "traits class" alpar@1250: /// of the algorithm kpeter@875: typedef TR Traits; kpeter@874: kpeter@874: public: kpeter@874: kpeter@875: /// \brief Problem type constants for the \c run() function. kpeter@875: /// kpeter@875: /// Enum type containing the problem type constants that can be kpeter@875: /// returned by the \ref run() function of the algorithm. kpeter@875: enum ProblemType { kpeter@875: /// The problem has no feasible solution (flow). kpeter@875: INFEASIBLE, kpeter@875: /// The problem has optimal solution (i.e. it is feasible and kpeter@875: /// bounded), and the algorithm has found optimal flow and node kpeter@875: /// potentials (primal and dual solutions). kpeter@875: OPTIMAL, kpeter@875: /// The digraph contains an arc of negative cost and infinite kpeter@875: /// upper bound. It means that the objective function is unbounded kpeter@878: /// on that arc, however, note that it could actually be bounded kpeter@875: /// over the feasible flows, but this algroithm cannot handle kpeter@875: /// these cases. kpeter@875: UNBOUNDED kpeter@875: }; kpeter@874: kpeter@876: /// \brief Constants for selecting the internal method. kpeter@876: /// kpeter@876: /// Enum type containing constants for selecting the internal method kpeter@876: /// for the \ref run() function. kpeter@876: /// kpeter@876: /// \ref CostScaling provides three internal methods that differ mainly kpeter@876: /// in their base operations, which are used in conjunction with the kpeter@876: /// relabel operation. kpeter@876: /// By default, the so called \ref PARTIAL_AUGMENT kpeter@1023: /// "Partial Augment-Relabel" method is used, which turned out to be kpeter@876: /// the most efficient and the most robust on various test inputs. kpeter@876: /// However, the other methods can be selected using the \ref run() kpeter@876: /// function with the proper parameter. kpeter@876: enum Method { kpeter@876: /// Local push operations are used, i.e. flow is moved only on one kpeter@876: /// admissible arc at once. kpeter@876: PUSH, kpeter@876: /// Augment operations are used, i.e. flow is moved on admissible kpeter@876: /// paths from a node with excess to a node with deficit. kpeter@876: AUGMENT, alpar@956: /// Partial augment operations are used, i.e. flow is moved on kpeter@876: /// admissible paths started from a node with excess, but the kpeter@876: /// lengths of these paths are limited. This method can be viewed kpeter@876: /// as a combined version of the previous two operations. kpeter@876: PARTIAL_AUGMENT kpeter@876: }; kpeter@876: kpeter@874: private: kpeter@874: kpeter@875: TEMPLATE_DIGRAPH_TYPEDEFS(GR); kpeter@874: kpeter@875: typedef std::vector IntVector; kpeter@875: typedef std::vector ValueVector; kpeter@875: typedef std::vector CostVector; kpeter@875: typedef std::vector LargeCostVector; kpeter@910: typedef std::vector BoolVector; kpeter@910: // Note: vector is used instead of vector for efficiency reasons kpeter@874: kpeter@875: private: alpar@956: kpeter@875: template kpeter@886: class StaticVectorMap { kpeter@874: public: kpeter@875: typedef KT Key; kpeter@875: typedef VT Value; alpar@956: kpeter@886: StaticVectorMap(std::vector& v) : _v(v) {} alpar@956: kpeter@875: const Value& operator[](const Key& key) const { kpeter@875: return _v[StaticDigraph::id(key)]; kpeter@874: } kpeter@874: kpeter@875: Value& operator[](const Key& key) { kpeter@875: return _v[StaticDigraph::id(key)]; kpeter@875: } alpar@956: kpeter@875: void set(const Key& key, const Value& val) { kpeter@875: _v[StaticDigraph::id(key)] = val; kpeter@874: } kpeter@874: kpeter@875: private: kpeter@875: std::vector& _v; kpeter@875: }; kpeter@875: kpeter@886: typedef StaticVectorMap LargeCostArcMap; kpeter@874: kpeter@874: private: kpeter@874: kpeter@875: // Data related to the underlying digraph kpeter@875: const GR &_graph; kpeter@875: int _node_num; kpeter@875: int _arc_num; kpeter@875: int _res_node_num; kpeter@875: int _res_arc_num; kpeter@875: int _root; kpeter@874: kpeter@875: // Parameters of the problem kpeter@875: bool _have_lower; kpeter@875: Value _sum_supply; kpeter@910: int _sup_node_num; kpeter@874: kpeter@875: // Data structures for storing the digraph kpeter@875: IntNodeMap _node_id; kpeter@875: IntArcMap _arc_idf; kpeter@875: IntArcMap _arc_idb; kpeter@875: IntVector _first_out; kpeter@875: BoolVector _forward; kpeter@875: IntVector _source; kpeter@875: IntVector _target; kpeter@875: IntVector _reverse; kpeter@875: kpeter@875: // Node and arc data kpeter@875: ValueVector _lower; kpeter@875: ValueVector _upper; kpeter@875: CostVector _scost; kpeter@875: ValueVector _supply; kpeter@875: kpeter@875: ValueVector _res_cap; kpeter@875: LargeCostVector _cost; kpeter@875: LargeCostVector _pi; kpeter@875: ValueVector _excess; kpeter@875: IntVector _next_out; kpeter@875: std::deque _active_nodes; kpeter@875: kpeter@875: // Data for scaling kpeter@875: LargeCost _epsilon; kpeter@874: int _alpha; kpeter@874: kpeter@910: IntVector _buckets; kpeter@910: IntVector _bucket_next; kpeter@910: IntVector _bucket_prev; kpeter@910: IntVector _rank; kpeter@910: int _max_rank; alpar@956: kpeter@875: public: alpar@956: kpeter@875: /// \brief Constant for infinite upper bounds (capacities). kpeter@875: /// kpeter@875: /// Constant for infinite upper bounds (capacities). kpeter@875: /// It is \c std::numeric_limits::infinity() if available, kpeter@875: /// \c std::numeric_limits::max() otherwise. kpeter@875: const Value INF; kpeter@875: kpeter@874: public: kpeter@874: kpeter@875: /// \name Named Template Parameters kpeter@875: /// @{ kpeter@875: kpeter@875: template kpeter@875: struct SetLargeCostTraits : public Traits { kpeter@875: typedef T LargeCost; kpeter@875: }; kpeter@875: kpeter@875: /// \brief \ref named-templ-param "Named parameter" for setting kpeter@875: /// \c LargeCost type. kpeter@874: /// kpeter@875: /// \ref named-templ-param "Named parameter" for setting \c LargeCost kpeter@875: /// type, which is used for internal computations in the algorithm. kpeter@875: /// \c Cost must be convertible to \c LargeCost. kpeter@875: template kpeter@875: struct SetLargeCost kpeter@875: : public CostScaling > { kpeter@875: typedef CostScaling > Create; kpeter@875: }; kpeter@875: kpeter@875: /// @} kpeter@875: kpeter@941: protected: kpeter@941: kpeter@941: CostScaling() {} kpeter@941: kpeter@875: public: kpeter@875: kpeter@875: /// \brief Constructor. kpeter@874: /// kpeter@875: /// The constructor of the class. kpeter@875: /// kpeter@875: /// \param graph The digraph the algorithm runs on. kpeter@875: CostScaling(const GR& graph) : kpeter@875: _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph), kpeter@875: INF(std::numeric_limits::has_infinity ? kpeter@875: std::numeric_limits::infinity() : kpeter@875: std::numeric_limits::max()) kpeter@874: { kpeter@878: // Check the number types kpeter@875: LEMON_ASSERT(std::numeric_limits::is_signed, kpeter@875: "The flow type of CostScaling must be signed"); kpeter@875: LEMON_ASSERT(std::numeric_limits::is_signed, kpeter@875: "The cost type of CostScaling must be signed"); alpar@956: kpeter@898: // Reset data structures kpeter@875: reset(); kpeter@874: } kpeter@874: kpeter@875: /// \name Parameters kpeter@875: /// The parameters of the algorithm can be specified using these kpeter@875: /// functions. kpeter@875: kpeter@875: /// @{ kpeter@875: kpeter@875: /// \brief Set the lower bounds on the arcs. kpeter@874: /// kpeter@875: /// This function sets the lower bounds on the arcs. kpeter@875: /// If it is not used before calling \ref run(), the lower bounds kpeter@875: /// will be set to zero on all arcs. kpeter@874: /// kpeter@875: /// \param map An arc map storing the lower bounds. kpeter@875: /// Its \c Value type must be convertible to the \c Value type kpeter@875: /// of the algorithm. kpeter@875: /// kpeter@875: /// \return (*this) kpeter@875: template kpeter@875: CostScaling& lowerMap(const LowerMap& map) { kpeter@875: _have_lower = true; kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: _lower[_arc_idf[a]] = map[a]; kpeter@875: _lower[_arc_idb[a]] = map[a]; kpeter@874: } kpeter@874: return *this; kpeter@874: } kpeter@874: kpeter@875: /// \brief Set the upper bounds (capacities) on the arcs. kpeter@874: /// kpeter@875: /// This function sets the upper bounds (capacities) on the arcs. kpeter@875: /// If it is not used before calling \ref run(), the upper bounds kpeter@875: /// will be set to \ref INF on all arcs (i.e. the flow value will be kpeter@878: /// unbounded from above). kpeter@874: /// kpeter@875: /// \param map An arc map storing the upper bounds. kpeter@875: /// Its \c Value type must be convertible to the \c Value type kpeter@875: /// of the algorithm. kpeter@875: /// kpeter@875: /// \return (*this) kpeter@875: template kpeter@875: CostScaling& upperMap(const UpperMap& map) { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: _upper[_arc_idf[a]] = map[a]; kpeter@874: } kpeter@874: return *this; kpeter@874: } kpeter@874: kpeter@875: /// \brief Set the costs of the arcs. kpeter@875: /// kpeter@875: /// This function sets the costs of the arcs. kpeter@875: /// If it is not used before calling \ref run(), the costs kpeter@875: /// will be set to \c 1 on all arcs. kpeter@875: /// kpeter@875: /// \param map An arc map storing the costs. kpeter@875: /// Its \c Value type must be convertible to the \c Cost type kpeter@875: /// of the algorithm. kpeter@875: /// kpeter@875: /// \return (*this) kpeter@875: template kpeter@875: CostScaling& costMap(const CostMap& map) { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: _scost[_arc_idf[a]] = map[a]; kpeter@875: _scost[_arc_idb[a]] = -map[a]; kpeter@875: } kpeter@875: return *this; kpeter@875: } kpeter@875: kpeter@875: /// \brief Set the supply values of the nodes. kpeter@875: /// kpeter@875: /// This function sets the supply values of the nodes. kpeter@875: /// If neither this function nor \ref stSupply() is used before kpeter@875: /// calling \ref run(), the supply of each node will be set to zero. kpeter@875: /// kpeter@875: /// \param map A node map storing the supply values. kpeter@875: /// Its \c Value type must be convertible to the \c Value type kpeter@875: /// of the algorithm. kpeter@875: /// kpeter@875: /// \return (*this) kpeter@875: template kpeter@875: CostScaling& supplyMap(const SupplyMap& map) { kpeter@875: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@875: _supply[_node_id[n]] = map[n]; kpeter@875: } kpeter@875: return *this; kpeter@875: } kpeter@875: kpeter@875: /// \brief Set single source and target nodes and a supply value. kpeter@875: /// kpeter@875: /// This function sets a single source node and a single target node kpeter@875: /// and the required flow value. kpeter@875: /// If neither this function nor \ref supplyMap() is used before kpeter@875: /// calling \ref run(), the supply of each node will be set to zero. kpeter@875: /// kpeter@875: /// 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@875: /// assigned to \c t and all other nodes have zero supply value. kpeter@875: /// kpeter@875: /// \param s The source node. kpeter@875: /// \param t The target node. kpeter@875: /// \param k The required amount of flow from node \c s to node \c t kpeter@875: /// (i.e. the supply of \c s and the demand of \c t). kpeter@875: /// kpeter@875: /// \return (*this) kpeter@875: CostScaling& stSupply(const Node& s, const Node& t, Value k) { kpeter@875: for (int i = 0; i != _res_node_num; ++i) { kpeter@875: _supply[i] = 0; kpeter@875: } kpeter@875: _supply[_node_id[s]] = k; kpeter@875: _supply[_node_id[t]] = -k; kpeter@875: return *this; kpeter@875: } alpar@956: kpeter@875: /// @} kpeter@875: kpeter@874: /// \name Execution control kpeter@875: /// The algorithm can be executed using \ref run(). kpeter@874: kpeter@874: /// @{ kpeter@874: kpeter@874: /// \brief Run the algorithm. kpeter@874: /// kpeter@875: /// This function runs the algorithm. kpeter@875: /// The paramters can be specified using functions \ref lowerMap(), kpeter@875: /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). kpeter@875: /// For example, kpeter@875: /// \code kpeter@875: /// CostScaling cs(graph); kpeter@875: /// cs.lowerMap(lower).upperMap(upper).costMap(cost) kpeter@875: /// .supplyMap(sup).run(); kpeter@875: /// \endcode kpeter@875: /// 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@874: /// kpeter@876: /// \param method The internal method that will be used in the kpeter@876: /// algorithm. For more information, see \ref Method. kpeter@1049: /// \param factor The cost scaling factor. It must be at least two. kpeter@874: /// kpeter@875: /// \return \c INFEASIBLE if no feasible flow exists, kpeter@875: /// \n \c OPTIMAL if the problem has optimal solution kpeter@875: /// (i.e. it is feasible and bounded), and the algorithm has found kpeter@875: /// optimal flow and node potentials (primal and dual solutions), kpeter@875: /// \n \c UNBOUNDED if the digraph contains an arc of negative cost kpeter@875: /// and infinite upper bound. It means that the objective function kpeter@878: /// is unbounded on that arc, however, note that it could actually be kpeter@875: /// bounded over the feasible flows, but this algroithm cannot handle kpeter@875: /// these cases. kpeter@875: /// kpeter@876: /// \see ProblemType, Method kpeter@898: /// \see resetParams(), reset() kpeter@1049: ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) { kpeter@1049: LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2"); kpeter@876: _alpha = factor; kpeter@875: ProblemType pt = init(); kpeter@875: if (pt != OPTIMAL) return pt; kpeter@876: start(method); kpeter@875: return OPTIMAL; kpeter@875: } kpeter@875: kpeter@875: /// \brief Reset all the parameters that have been given before. kpeter@875: /// kpeter@875: /// This function resets all the paramaters that have been given kpeter@875: /// before using functions \ref lowerMap(), \ref upperMap(), kpeter@875: /// \ref costMap(), \ref supplyMap(), \ref stSupply(). kpeter@875: /// 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@875: /// kpeter@875: /// For example, kpeter@875: /// \code kpeter@875: /// CostScaling cs(graph); kpeter@875: /// kpeter@875: /// // First run kpeter@875: /// cs.lowerMap(lower).upperMap(upper).costMap(cost) kpeter@875: /// .supplyMap(sup).run(); kpeter@875: /// kpeter@898: /// // Run again with modified cost map (resetParams() is not called, kpeter@875: /// // so only the cost map have to be set again) kpeter@875: /// cost[e] += 100; kpeter@875: /// cs.costMap(cost).run(); kpeter@875: /// kpeter@898: /// // Run again from scratch using resetParams() kpeter@875: /// // (the lower bounds will be set to zero on all arcs) kpeter@898: /// cs.resetParams(); kpeter@875: /// cs.upperMap(capacity).costMap(cost) kpeter@875: /// .supplyMap(sup).run(); kpeter@875: /// \endcode kpeter@875: /// kpeter@875: /// \return (*this) kpeter@898: /// kpeter@898: /// \see reset(), run() kpeter@898: CostScaling& resetParams() { kpeter@875: for (int i = 0; i != _res_node_num; ++i) { kpeter@875: _supply[i] = 0; kpeter@874: } kpeter@875: int limit = _first_out[_root]; kpeter@875: for (int j = 0; j != limit; ++j) { kpeter@875: _lower[j] = 0; kpeter@875: _upper[j] = INF; kpeter@875: _scost[j] = _forward[j] ? 1 : -1; kpeter@875: } kpeter@875: for (int j = limit; j != _res_arc_num; ++j) { kpeter@875: _lower[j] = 0; kpeter@875: _upper[j] = INF; kpeter@875: _scost[j] = 0; kpeter@875: _scost[_reverse[j]] = 0; alpar@956: } kpeter@875: _have_lower = false; kpeter@875: return *this; kpeter@874: } kpeter@874: kpeter@1045: /// \brief Reset the internal data structures and all the parameters kpeter@1045: /// that have been given before. kpeter@898: /// kpeter@1045: /// This function resets the internal data structures and all the kpeter@1045: /// paramaters that have been given before using functions \ref lowerMap(), kpeter@1045: /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). kpeter@898: /// kpeter@1045: /// It is useful for multiple \ref run() calls. By default, all the given kpeter@1045: /// parameters are kept for the next \ref run() call, unless kpeter@1045: /// \ref resetParams() or \ref reset() is used. kpeter@1045: /// If the underlying digraph was also modified after the construction kpeter@1045: /// of the class or the last \ref reset() call, then the \ref reset() kpeter@1045: /// function must be used, otherwise \ref resetParams() is sufficient. kpeter@1045: /// kpeter@1045: /// See \ref resetParams() for examples. kpeter@1045: /// kpeter@898: /// \return (*this) kpeter@1045: /// kpeter@1045: /// \see resetParams(), run() kpeter@898: CostScaling& reset() { kpeter@898: // Resize vectors kpeter@898: _node_num = countNodes(_graph); kpeter@898: _arc_num = countArcs(_graph); kpeter@898: _res_node_num = _node_num + 1; kpeter@898: _res_arc_num = 2 * (_arc_num + _node_num); kpeter@898: _root = _node_num; kpeter@898: kpeter@898: _first_out.resize(_res_node_num + 1); kpeter@898: _forward.resize(_res_arc_num); kpeter@898: _source.resize(_res_arc_num); kpeter@898: _target.resize(_res_arc_num); kpeter@898: _reverse.resize(_res_arc_num); kpeter@898: kpeter@898: _lower.resize(_res_arc_num); kpeter@898: _upper.resize(_res_arc_num); kpeter@898: _scost.resize(_res_arc_num); kpeter@898: _supply.resize(_res_node_num); alpar@956: kpeter@898: _res_cap.resize(_res_arc_num); kpeter@898: _cost.resize(_res_arc_num); kpeter@898: _pi.resize(_res_node_num); kpeter@898: _excess.resize(_res_node_num); kpeter@898: _next_out.resize(_res_node_num); kpeter@898: kpeter@898: // Copy the graph kpeter@898: int i = 0, j = 0, k = 2 * _arc_num + _node_num; kpeter@898: for (NodeIt n(_graph); n != INVALID; ++n, ++i) { kpeter@898: _node_id[n] = i; kpeter@898: } kpeter@898: i = 0; kpeter@898: for (NodeIt n(_graph); n != INVALID; ++n, ++i) { kpeter@898: _first_out[i] = j; kpeter@898: for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) { kpeter@898: _arc_idf[a] = j; kpeter@898: _forward[j] = true; kpeter@898: _source[j] = i; kpeter@898: _target[j] = _node_id[_graph.runningNode(a)]; kpeter@898: } kpeter@898: for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) { kpeter@898: _arc_idb[a] = j; kpeter@898: _forward[j] = false; kpeter@898: _source[j] = i; kpeter@898: _target[j] = _node_id[_graph.runningNode(a)]; kpeter@898: } kpeter@898: _forward[j] = false; kpeter@898: _source[j] = i; kpeter@898: _target[j] = _root; kpeter@898: _reverse[j] = k; kpeter@898: _forward[k] = true; kpeter@898: _source[k] = _root; kpeter@898: _target[k] = i; kpeter@898: _reverse[k] = j; kpeter@898: ++j; ++k; kpeter@898: } kpeter@898: _first_out[i] = j; kpeter@898: _first_out[_res_node_num] = k; kpeter@898: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@898: int fi = _arc_idf[a]; kpeter@898: int bi = _arc_idb[a]; kpeter@898: _reverse[fi] = bi; kpeter@898: _reverse[bi] = fi; kpeter@898: } alpar@956: kpeter@898: // Reset parameters kpeter@898: resetParams(); kpeter@898: return *this; kpeter@898: } kpeter@898: kpeter@874: /// @} kpeter@874: kpeter@874: /// \name Query Functions kpeter@875: /// The results of the algorithm can be obtained using these kpeter@874: /// functions.\n kpeter@875: /// The \ref run() function must be called before using them. kpeter@874: kpeter@874: /// @{ kpeter@874: kpeter@875: /// \brief Return the total cost of the found flow. kpeter@874: /// kpeter@875: /// This function returns the total cost of the found flow. kpeter@875: /// Its complexity is O(e). kpeter@875: /// kpeter@875: /// \note The return type of the function can be specified as a kpeter@875: /// template parameter. For example, kpeter@875: /// \code kpeter@875: /// cs.totalCost(); kpeter@875: /// \endcode kpeter@875: /// It is useful if the total cost cannot be stored in the \c Cost kpeter@875: /// type of the algorithm, which is the default return type of the kpeter@875: /// function. kpeter@874: /// kpeter@874: /// \pre \ref run() must be called before using this function. kpeter@875: template kpeter@875: Number totalCost() const { kpeter@875: Number c = 0; kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: int i = _arc_idb[a]; kpeter@875: c += static_cast(_res_cap[i]) * kpeter@875: (-static_cast(_scost[i])); kpeter@875: } kpeter@875: return c; kpeter@874: } kpeter@874: kpeter@875: #ifndef DOXYGEN kpeter@875: Cost totalCost() const { kpeter@875: return totalCost(); kpeter@874: } kpeter@875: #endif kpeter@874: kpeter@874: /// \brief Return the flow on the given arc. kpeter@874: /// kpeter@875: /// This function returns the flow on the given arc. kpeter@874: /// kpeter@874: /// \pre \ref run() must be called before using this function. kpeter@875: Value flow(const Arc& a) const { kpeter@875: return _res_cap[_arc_idb[a]]; kpeter@874: } kpeter@874: kpeter@1165: /// \brief Copy the flow values (the primal solution) into the kpeter@1165: /// given map. kpeter@874: /// kpeter@875: /// This function copies the flow value on each arc into the given kpeter@875: /// map. The \c Value type of the algorithm must be convertible to kpeter@875: /// the \c Value type of the map. kpeter@874: /// kpeter@874: /// \pre \ref run() must be called before using this function. kpeter@875: template kpeter@875: void flowMap(FlowMap &map) const { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: map.set(a, _res_cap[_arc_idb[a]]); kpeter@875: } kpeter@874: } kpeter@874: kpeter@875: /// \brief Return the potential (dual value) of the given node. kpeter@874: /// kpeter@875: /// This function returns the potential (dual value) of the kpeter@875: /// given node. kpeter@874: /// kpeter@874: /// \pre \ref run() must be called before using this function. kpeter@875: Cost potential(const Node& n) const { kpeter@875: return static_cast(_pi[_node_id[n]]); kpeter@875: } kpeter@875: kpeter@1165: /// \brief Copy the potential values (the dual solution) into the kpeter@1165: /// given map. kpeter@875: /// kpeter@875: /// This function copies the potential (dual value) of each node kpeter@875: /// into the given map. kpeter@875: /// The \c Cost type of the algorithm must be convertible to the kpeter@875: /// \c Value type of the map. kpeter@875: /// kpeter@875: /// \pre \ref run() must be called before using this function. kpeter@875: template kpeter@875: void potentialMap(PotentialMap &map) const { kpeter@875: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@875: map.set(n, static_cast(_pi[_node_id[n]])); kpeter@875: } kpeter@874: } kpeter@874: kpeter@874: /// @} kpeter@874: kpeter@874: private: kpeter@874: kpeter@875: // Initialize the algorithm kpeter@875: ProblemType init() { kpeter@887: if (_res_node_num <= 1) return INFEASIBLE; kpeter@875: kpeter@875: // Check the sum of supply values kpeter@875: _sum_supply = 0; kpeter@875: for (int i = 0; i != _root; ++i) { kpeter@875: _sum_supply += _supply[i]; kpeter@874: } kpeter@875: if (_sum_supply > 0) return INFEASIBLE; alpar@956: kpeter@1240: // Check lower and upper bounds kpeter@1240: LEMON_DEBUG(checkBoundMaps(), kpeter@1240: "Upper bounds must be greater or equal to the lower bounds"); kpeter@1240: kpeter@875: kpeter@875: // Initialize vectors kpeter@875: for (int i = 0; i != _res_node_num; ++i) { kpeter@875: _pi[i] = 0; kpeter@875: _excess[i] = _supply[i]; kpeter@875: } alpar@956: kpeter@875: // Remove infinite upper bounds and check negative arcs kpeter@875: const Value MAX = std::numeric_limits::max(); kpeter@875: int last_out; kpeter@875: if (_have_lower) { kpeter@875: for (int i = 0; i != _root; ++i) { kpeter@875: last_out = _first_out[i+1]; kpeter@875: for (int j = _first_out[i]; j != last_out; ++j) { kpeter@875: if (_forward[j]) { kpeter@875: Value c = _scost[j] < 0 ? _upper[j] : _lower[j]; kpeter@875: if (c >= MAX) return UNBOUNDED; kpeter@875: _excess[i] -= c; kpeter@875: _excess[_target[j]] += c; kpeter@875: } kpeter@875: } kpeter@875: } kpeter@875: } else { kpeter@875: for (int i = 0; i != _root; ++i) { kpeter@875: last_out = _first_out[i+1]; kpeter@875: for (int j = _first_out[i]; j != last_out; ++j) { kpeter@875: if (_forward[j] && _scost[j] < 0) { kpeter@875: Value c = _upper[j]; kpeter@875: if (c >= MAX) return UNBOUNDED; kpeter@875: _excess[i] -= c; kpeter@875: _excess[_target[j]] += c; kpeter@875: } kpeter@875: } kpeter@875: } kpeter@875: } kpeter@875: Value ex, max_cap = 0; kpeter@875: for (int i = 0; i != _res_node_num; ++i) { kpeter@875: ex = _excess[i]; kpeter@875: _excess[i] = 0; kpeter@875: if (ex < 0) max_cap -= ex; kpeter@875: } kpeter@875: for (int j = 0; j != _res_arc_num; ++j) { kpeter@875: if (_upper[j] >= MAX) _upper[j] = max_cap; kpeter@874: } kpeter@874: kpeter@875: // Initialize the large cost vector and the epsilon parameter kpeter@875: _epsilon = 0; kpeter@875: LargeCost lc; kpeter@875: for (int i = 0; i != _root; ++i) { kpeter@875: last_out = _first_out[i+1]; kpeter@875: for (int j = _first_out[i]; j != last_out; ++j) { kpeter@875: lc = static_cast(_scost[j]) * _res_node_num * _alpha; kpeter@875: _cost[j] = lc; kpeter@875: if (lc > _epsilon) _epsilon = lc; kpeter@875: } kpeter@875: } kpeter@875: _epsilon /= _alpha; kpeter@874: kpeter@875: // Initialize maps for Circulation and remove non-zero lower bounds kpeter@875: ConstMap low(0); kpeter@875: typedef typename Digraph::template ArcMap ValueArcMap; kpeter@875: typedef typename Digraph::template NodeMap ValueNodeMap; kpeter@875: ValueArcMap cap(_graph), flow(_graph); kpeter@875: ValueNodeMap sup(_graph); kpeter@875: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@875: sup[n] = _supply[_node_id[n]]; kpeter@874: } kpeter@875: if (_have_lower) { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: int j = _arc_idf[a]; kpeter@875: Value c = _lower[j]; kpeter@875: cap[a] = _upper[j] - c; kpeter@875: sup[_graph.source(a)] -= c; kpeter@875: sup[_graph.target(a)] += c; kpeter@875: } kpeter@875: } else { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: cap[a] = _upper[_arc_idf[a]]; kpeter@875: } kpeter@875: } kpeter@874: kpeter@910: _sup_node_num = 0; kpeter@910: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@910: if (sup[n] > 0) ++_sup_node_num; kpeter@910: } kpeter@910: kpeter@874: // Find a feasible flow using Circulation kpeter@875: Circulation, ValueArcMap, ValueNodeMap> kpeter@875: circ(_graph, low, cap, sup); kpeter@875: if (!circ.flowMap(flow).run()) return INFEASIBLE; kpeter@875: kpeter@875: // Set residual capacities and handle GEQ supply type kpeter@875: if (_sum_supply < 0) { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: Value fa = flow[a]; kpeter@875: _res_cap[_arc_idf[a]] = cap[a] - fa; kpeter@875: _res_cap[_arc_idb[a]] = fa; kpeter@875: sup[_graph.source(a)] -= fa; kpeter@875: sup[_graph.target(a)] += fa; kpeter@875: } kpeter@875: for (NodeIt n(_graph); n != INVALID; ++n) { kpeter@875: _excess[_node_id[n]] = sup[n]; kpeter@875: } kpeter@875: for (int a = _first_out[_root]; a != _res_arc_num; ++a) { kpeter@875: int u = _target[a]; kpeter@875: int ra = _reverse[a]; kpeter@875: _res_cap[a] = -_sum_supply + 1; kpeter@875: _res_cap[ra] = -_excess[u]; kpeter@875: _cost[a] = 0; kpeter@875: _cost[ra] = 0; kpeter@875: _excess[u] = 0; kpeter@875: } kpeter@875: } else { kpeter@875: for (ArcIt a(_graph); a != INVALID; ++a) { kpeter@875: Value fa = flow[a]; kpeter@875: _res_cap[_arc_idf[a]] = cap[a] - fa; kpeter@875: _res_cap[_arc_idb[a]] = fa; kpeter@875: } kpeter@875: for (int a = _first_out[_root]; a != _res_arc_num; ++a) { kpeter@875: int ra = _reverse[a]; kpeter@910: _res_cap[a] = 0; kpeter@875: _res_cap[ra] = 0; kpeter@875: _cost[a] = 0; kpeter@875: _cost[ra] = 0; kpeter@875: } kpeter@875: } alpar@956: alpar@956: // Initialize data structures for buckets kpeter@910: _max_rank = _alpha * _res_node_num; kpeter@910: _buckets.resize(_max_rank); kpeter@910: _bucket_next.resize(_res_node_num + 1); kpeter@910: _bucket_prev.resize(_res_node_num + 1); kpeter@910: _rank.resize(_res_node_num + 1); alpar@956: kpeter@1045: return OPTIMAL; kpeter@1045: } kpeter@1240: kpeter@1240: // Check if the upper bound is greater or equal to the lower bound kpeter@1240: // on each arc. kpeter@1240: bool checkBoundMaps() { kpeter@1240: for (int j = 0; j != _res_arc_num; ++j) { kpeter@1240: if (_upper[j] < _lower[j]) return false; kpeter@1240: } kpeter@1240: return true; kpeter@1240: } kpeter@1045: kpeter@1045: // Execute the algorithm and transform the results kpeter@1045: void start(Method method) { kpeter@1045: const int MAX_PARTIAL_PATH_LENGTH = 4; kpeter@1045: kpeter@876: switch (method) { kpeter@876: case PUSH: kpeter@876: startPush(); kpeter@876: break; kpeter@876: case AUGMENT: kpeter@1041: startAugment(_res_node_num - 1); kpeter@876: break; kpeter@876: case PARTIAL_AUGMENT: kpeter@1045: startAugment(MAX_PARTIAL_PATH_LENGTH); kpeter@876: break; kpeter@875: } kpeter@875: kpeter@1048: // Compute node potentials (dual solution) kpeter@1048: for (int i = 0; i != _res_node_num; ++i) { kpeter@1048: _pi[i] = static_cast(_pi[i] / (_res_node_num * _alpha)); kpeter@1048: } kpeter@1048: bool optimal = true; kpeter@1048: for (int i = 0; optimal && i != _res_node_num; ++i) { kpeter@1048: LargeCost pi_i = _pi[i]; kpeter@1048: int last_out = _first_out[i+1]; kpeter@1048: for (int j = _first_out[i]; j != last_out; ++j) { kpeter@1048: if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) { kpeter@1048: optimal = false; kpeter@1048: break; kpeter@1048: } kpeter@875: } kpeter@875: } kpeter@875: kpeter@1048: if (!optimal) { kpeter@1048: // Compute node potentials for the original costs with BellmanFord kpeter@1048: // (if it is necessary) kpeter@1048: typedef std::pair IntPair; kpeter@1048: StaticDigraph sgr; kpeter@1048: std::vector arc_vec; kpeter@1048: std::vector cost_vec; kpeter@1048: LargeCostArcMap cost_map(cost_vec); kpeter@1048: kpeter@1048: arc_vec.clear(); kpeter@1048: cost_vec.clear(); kpeter@1048: for (int j = 0; j != _res_arc_num; ++j) { kpeter@1048: if (_res_cap[j] > 0) { kpeter@1048: int u = _source[j], v = _target[j]; kpeter@1048: arc_vec.push_back(IntPair(u, v)); kpeter@1048: cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]); kpeter@1048: } kpeter@1048: } kpeter@1048: sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end()); kpeter@1048: kpeter@1048: typename BellmanFord::Create kpeter@1048: bf(sgr, cost_map); kpeter@1048: bf.init(0); kpeter@1048: bf.start(); kpeter@1048: kpeter@1048: for (int i = 0; i != _res_node_num; ++i) { kpeter@1048: _pi[i] += bf.dist(sgr.node(i)); kpeter@1048: } kpeter@1048: } kpeter@1048: kpeter@1048: // Shift potentials to meet the requirements of the GEQ type kpeter@1048: // optimality conditions kpeter@1048: LargeCost max_pot = _pi[_root]; kpeter@1048: for (int i = 0; i != _res_node_num; ++i) { kpeter@1048: if (_pi[i] > max_pot) max_pot = _pi[i]; kpeter@1048: } kpeter@1048: if (max_pot != 0) { kpeter@1048: for (int i = 0; i != _res_node_num; ++i) { kpeter@1048: _pi[i] -= max_pot; kpeter@1048: } kpeter@1048: } kpeter@875: kpeter@875: // Handle non-zero lower bounds kpeter@875: if (_have_lower) { kpeter@875: int limit = _first_out[_root]; kpeter@875: for (int j = 0; j != limit; ++j) { kpeter@875: if (!_forward[j]) _res_cap[j] += _lower[j]; kpeter@875: } kpeter@875: } kpeter@874: } alpar@956: kpeter@910: // Initialize a cost scaling phase kpeter@910: void initPhase() { kpeter@910: // Saturate arcs not satisfying the optimality condition kpeter@910: for (int u = 0; u != _res_node_num; ++u) { kpeter@910: int last_out = _first_out[u+1]; kpeter@910: LargeCost pi_u = _pi[u]; kpeter@910: for (int a = _first_out[u]; a != last_out; ++a) { kpeter@1045: Value delta = _res_cap[a]; kpeter@1045: if (delta > 0) { kpeter@1045: int v = _target[a]; kpeter@1045: if (_cost[a] + pi_u - _pi[v] < 0) { kpeter@1045: _excess[u] -= delta; kpeter@1045: _excess[v] += delta; kpeter@1045: _res_cap[a] = 0; kpeter@1045: _res_cap[_reverse[a]] += delta; kpeter@1045: } kpeter@910: } kpeter@910: } kpeter@910: } alpar@956: kpeter@910: // Find active nodes (i.e. nodes with positive excess) kpeter@910: for (int u = 0; u != _res_node_num; ++u) { kpeter@910: if (_excess[u] > 0) _active_nodes.push_back(u); kpeter@910: } kpeter@910: kpeter@910: // Initialize the next arcs kpeter@910: for (int u = 0; u != _res_node_num; ++u) { kpeter@910: _next_out[u] = _first_out[u]; kpeter@910: } kpeter@910: } alpar@956: kpeter@1047: // Price (potential) refinement heuristic kpeter@1047: bool priceRefinement() { kpeter@910: kpeter@1047: // Stack for stroing the topological order kpeter@1047: IntVector stack(_res_node_num); kpeter@1047: int stack_top; kpeter@1047: kpeter@1047: // Perform phases kpeter@1047: while (topologicalSort(stack, stack_top)) { kpeter@1047: kpeter@1047: // Compute node ranks in the acyclic admissible network and kpeter@1047: // store the nodes in buckets kpeter@1047: for (int i = 0; i != _res_node_num; ++i) { kpeter@1047: _rank[i] = 0; kpeter@910: } kpeter@1047: const int bucket_end = _root + 1; kpeter@1047: for (int r = 0; r != _max_rank; ++r) { kpeter@1047: _buckets[r] = bucket_end; kpeter@1047: } kpeter@1047: int top_rank = 0; kpeter@1047: for ( ; stack_top >= 0; --stack_top) { kpeter@1047: int u = stack[stack_top], v; kpeter@1047: int rank_u = _rank[u]; kpeter@1047: kpeter@1047: LargeCost rc, pi_u = _pi[u]; kpeter@1047: int last_out = _first_out[u+1]; kpeter@1047: for (int a = _first_out[u]; a != last_out; ++a) { kpeter@1047: if (_res_cap[a] > 0) { kpeter@1047: v = _target[a]; kpeter@1047: rc = _cost[a] + pi_u - _pi[v]; kpeter@1047: if (rc < 0) { kpeter@1047: LargeCost nrc = static_cast((-rc - 0.5) / _epsilon); kpeter@1047: if (nrc < LargeCost(_max_rank)) { kpeter@1047: int new_rank_v = rank_u + static_cast(nrc); kpeter@1047: if (new_rank_v > _rank[v]) { kpeter@1047: _rank[v] = new_rank_v; kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: if (rank_u > 0) { kpeter@1047: top_rank = std::max(top_rank, rank_u); kpeter@1047: int bfirst = _buckets[rank_u]; kpeter@1047: _bucket_next[u] = bfirst; kpeter@1047: _bucket_prev[bfirst] = u; kpeter@1047: _buckets[rank_u] = u; kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: // Check if the current flow is epsilon-optimal kpeter@1047: if (top_rank == 0) { kpeter@1047: return true; kpeter@1047: } kpeter@1047: kpeter@1047: // Process buckets in top-down order kpeter@1047: for (int rank = top_rank; rank > 0; --rank) { kpeter@1047: while (_buckets[rank] != bucket_end) { kpeter@1047: // Remove the first node from the current bucket kpeter@1047: int u = _buckets[rank]; kpeter@1047: _buckets[rank] = _bucket_next[u]; kpeter@1047: kpeter@1047: // Search the outgoing arcs of u kpeter@1047: LargeCost rc, pi_u = _pi[u]; kpeter@1047: int last_out = _first_out[u+1]; kpeter@1047: int v, old_rank_v, new_rank_v; kpeter@1047: for (int a = _first_out[u]; a != last_out; ++a) { kpeter@1047: if (_res_cap[a] > 0) { kpeter@1047: v = _target[a]; kpeter@1047: old_rank_v = _rank[v]; kpeter@1047: kpeter@1047: if (old_rank_v < rank) { kpeter@1047: kpeter@1047: // Compute the new rank of node v kpeter@1047: rc = _cost[a] + pi_u - _pi[v]; kpeter@1047: if (rc < 0) { kpeter@1047: new_rank_v = rank; kpeter@1047: } else { kpeter@1047: LargeCost nrc = rc / _epsilon; kpeter@1047: new_rank_v = 0; kpeter@1047: if (nrc < LargeCost(_max_rank)) { kpeter@1047: new_rank_v = rank - 1 - static_cast(nrc); kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: // Change the rank of node v kpeter@1047: if (new_rank_v > old_rank_v) { kpeter@1047: _rank[v] = new_rank_v; kpeter@1047: kpeter@1047: // Remove v from its old bucket kpeter@1047: if (old_rank_v > 0) { kpeter@1047: if (_buckets[old_rank_v] == v) { kpeter@1047: _buckets[old_rank_v] = _bucket_next[v]; kpeter@1047: } else { kpeter@1047: int pv = _bucket_prev[v], nv = _bucket_next[v]; kpeter@1047: _bucket_next[pv] = nv; kpeter@1047: _bucket_prev[nv] = pv; kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: // Insert v into its new bucket kpeter@1047: int nv = _buckets[new_rank_v]; kpeter@1047: _bucket_next[v] = nv; kpeter@1047: _bucket_prev[nv] = v; kpeter@1047: _buckets[new_rank_v] = v; kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: // Refine potential of node u kpeter@1047: _pi[u] -= rank * _epsilon; kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@910: } kpeter@910: kpeter@1047: return false; kpeter@1047: } kpeter@1047: kpeter@1047: // Find and cancel cycles in the admissible network and kpeter@1047: // determine topological order using DFS kpeter@1047: bool topologicalSort(IntVector &stack, int &stack_top) { kpeter@1047: const int MAX_CYCLE_CANCEL = 1; kpeter@1047: kpeter@1047: BoolVector reached(_res_node_num, false); kpeter@1047: BoolVector processed(_res_node_num, false); kpeter@1047: IntVector pred(_res_node_num); kpeter@1047: for (int i = 0; i != _res_node_num; ++i) { kpeter@1047: _next_out[i] = _first_out[i]; kpeter@910: } kpeter@1047: stack_top = -1; kpeter@1047: kpeter@1047: int cycle_cnt = 0; kpeter@1047: for (int start = 0; start != _res_node_num; ++start) { kpeter@1047: if (reached[start]) continue; kpeter@1047: kpeter@1047: // Start DFS search from this start node kpeter@1047: pred[start] = -1; kpeter@1047: int tip = start, v; kpeter@1047: while (true) { kpeter@1047: // Check the outgoing arcs of the current tip node kpeter@1047: reached[tip] = true; kpeter@1047: LargeCost pi_tip = _pi[tip]; kpeter@1047: int a, last_out = _first_out[tip+1]; kpeter@1047: for (a = _next_out[tip]; a != last_out; ++a) { kpeter@1047: if (_res_cap[a] > 0) { kpeter@1047: v = _target[a]; kpeter@1047: if (_cost[a] + pi_tip - _pi[v] < 0) { kpeter@1047: if (!reached[v]) { kpeter@1047: // A new node is reached kpeter@1047: reached[v] = true; kpeter@1047: pred[v] = tip; kpeter@1047: _next_out[tip] = a; kpeter@1047: tip = v; kpeter@1047: a = _next_out[tip]; kpeter@1047: last_out = _first_out[tip+1]; kpeter@1047: break; kpeter@1047: } kpeter@1047: else if (!processed[v]) { kpeter@1047: // A cycle is found kpeter@1047: ++cycle_cnt; kpeter@1047: _next_out[tip] = a; kpeter@1047: kpeter@1047: // Find the minimum residual capacity along the cycle kpeter@1047: Value d, delta = _res_cap[a]; kpeter@1047: int u, delta_node = tip; kpeter@1047: for (u = tip; u != v; ) { kpeter@1047: u = pred[u]; kpeter@1047: d = _res_cap[_next_out[u]]; kpeter@1047: if (d <= delta) { kpeter@1047: delta = d; kpeter@1047: delta_node = u; kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: // Augment along the cycle kpeter@1047: _res_cap[a] -= delta; kpeter@1047: _res_cap[_reverse[a]] += delta; kpeter@1047: for (u = tip; u != v; ) { kpeter@1047: u = pred[u]; kpeter@1047: int ca = _next_out[u]; kpeter@1047: _res_cap[ca] -= delta; kpeter@1047: _res_cap[_reverse[ca]] += delta; kpeter@1047: } kpeter@1047: kpeter@1047: // Check the maximum number of cycle canceling kpeter@1047: if (cycle_cnt >= MAX_CYCLE_CANCEL) { kpeter@1047: return false; kpeter@1047: } kpeter@1047: kpeter@1047: // Roll back search to delta_node kpeter@1047: if (delta_node != tip) { kpeter@1047: for (u = tip; u != delta_node; u = pred[u]) { kpeter@1047: reached[u] = false; kpeter@1047: } kpeter@1047: tip = delta_node; kpeter@1047: a = _next_out[tip] + 1; kpeter@1047: last_out = _first_out[tip+1]; kpeter@1047: break; kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: // Step back to the previous node kpeter@1047: if (a == last_out) { kpeter@1047: processed[tip] = true; kpeter@1047: stack[++stack_top] = tip; kpeter@1047: tip = pred[tip]; kpeter@1047: if (tip < 0) { kpeter@1047: // Finish DFS from the current start node kpeter@1047: break; kpeter@1047: } kpeter@1047: ++_next_out[tip]; kpeter@1047: } kpeter@1047: } kpeter@1047: kpeter@1047: } kpeter@1047: kpeter@1047: return (cycle_cnt == 0); kpeter@910: } kpeter@910: kpeter@910: // Global potential update heuristic kpeter@910: void globalUpdate() { kpeter@1045: const int bucket_end = _root + 1; alpar@956: kpeter@910: // Initialize buckets kpeter@910: for (int r = 0; r != _max_rank; ++r) { kpeter@910: _buckets[r] = bucket_end; kpeter@910: } kpeter@910: Value total_excess = 0; kpeter@1045: int b0 = bucket_end; kpeter@910: for (int i = 0; i != _res_node_num; ++i) { kpeter@910: if (_excess[i] < 0) { kpeter@910: _rank[i] = 0; kpeter@1045: _bucket_next[i] = b0; kpeter@1045: _bucket_prev[b0] = i; kpeter@1045: b0 = i; kpeter@910: } else { kpeter@910: total_excess += _excess[i]; kpeter@910: _rank[i] = _max_rank; kpeter@910: } kpeter@910: } kpeter@910: if (total_excess == 0) return; kpeter@1045: _buckets[0] = b0; kpeter@910: kpeter@910: // Search the buckets kpeter@910: int r = 0; kpeter@910: for ( ; r != _max_rank; ++r) { kpeter@910: while (_buckets[r] != bucket_end) { kpeter@910: // Remove the first node from the current bucket kpeter@910: int u = _buckets[r]; kpeter@910: _buckets[r] = _bucket_next[u]; alpar@956: kpeter@1217: // Search the incoming arcs of u kpeter@910: LargeCost pi_u = _pi[u]; kpeter@910: int last_out = _first_out[u+1]; kpeter@910: for (int a = _first_out[u]; a != last_out; ++a) { kpeter@910: int ra = _reverse[a]; kpeter@910: if (_res_cap[ra] > 0) { kpeter@910: int v = _source[ra]; kpeter@910: int old_rank_v = _rank[v]; kpeter@910: if (r < old_rank_v) { kpeter@910: // Compute the new rank of v kpeter@910: LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon; kpeter@910: int new_rank_v = old_rank_v; kpeter@1045: if (nrc < LargeCost(_max_rank)) { kpeter@1045: new_rank_v = r + 1 + static_cast(nrc); kpeter@1045: } alpar@956: kpeter@910: // Change the rank of v kpeter@910: if (new_rank_v < old_rank_v) { kpeter@910: _rank[v] = new_rank_v; kpeter@910: _next_out[v] = _first_out[v]; alpar@956: kpeter@910: // Remove v from its old bucket kpeter@910: if (old_rank_v < _max_rank) { kpeter@910: if (_buckets[old_rank_v] == v) { kpeter@910: _buckets[old_rank_v] = _bucket_next[v]; kpeter@910: } else { kpeter@1045: int pv = _bucket_prev[v], nv = _bucket_next[v]; kpeter@1045: _bucket_next[pv] = nv; kpeter@1045: _bucket_prev[nv] = pv; kpeter@910: } kpeter@910: } alpar@956: kpeter@1045: // Insert v into its new bucket kpeter@1045: int nv = _buckets[new_rank_v]; kpeter@1045: _bucket_next[v] = nv; kpeter@1045: _bucket_prev[nv] = v; kpeter@910: _buckets[new_rank_v] = v; kpeter@910: } kpeter@910: } kpeter@910: } kpeter@910: } kpeter@910: kpeter@910: // Finish search if there are no more active nodes kpeter@910: if (_excess[u] > 0) { kpeter@910: total_excess -= _excess[u]; kpeter@910: if (total_excess <= 0) break; kpeter@910: } kpeter@910: } kpeter@910: if (total_excess <= 0) break; kpeter@910: } alpar@956: kpeter@910: // Relabel nodes kpeter@910: for (int u = 0; u != _res_node_num; ++u) { kpeter@910: int k = std::min(_rank[u], r); kpeter@910: if (k > 0) { kpeter@910: _pi[u] -= _epsilon * k; kpeter@910: _next_out[u] = _first_out[u]; kpeter@910: } kpeter@910: } kpeter@910: } kpeter@874: kpeter@876: /// Execute the algorithm performing augment and relabel operations kpeter@1041: void startAugment(int max_length) { kpeter@874: // Paramters for heuristics kpeter@1047: const int PRICE_REFINEMENT_LIMIT = 2; kpeter@1046: const double GLOBAL_UPDATE_FACTOR = 1.0; kpeter@1046: const int global_update_skip = static_cast(GLOBAL_UPDATE_FACTOR * kpeter@910: (_res_node_num + _sup_node_num * _sup_node_num)); kpeter@1046: int next_global_update_limit = global_update_skip; alpar@956: kpeter@875: // Perform cost scaling phases kpeter@1046: IntVector path; kpeter@1046: BoolVector path_arc(_res_arc_num, false); kpeter@1046: int relabel_cnt = 0; kpeter@1047: int eps_phase_cnt = 0; kpeter@874: for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ? kpeter@874: 1 : _epsilon / _alpha ) kpeter@874: { kpeter@1047: ++eps_phase_cnt; kpeter@1047: kpeter@1047: // Price refinement heuristic kpeter@1047: if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) { kpeter@1047: if (priceRefinement()) continue; kpeter@874: } alpar@956: kpeter@910: // Initialize current phase kpeter@910: initPhase(); alpar@956: kpeter@874: // Perform partial augment and relabel operations kpeter@875: while (true) { kpeter@874: // Select an active node (FIFO selection) kpeter@875: while (_active_nodes.size() > 0 && kpeter@875: _excess[_active_nodes.front()] <= 0) { kpeter@875: _active_nodes.pop_front(); kpeter@874: } kpeter@875: if (_active_nodes.size() == 0) break; kpeter@875: int start = _active_nodes.front(); kpeter@874: kpeter@874: // Find an augmenting path from the start node kpeter@875: int tip = start; kpeter@1046: while (int(path.size()) < max_length && _excess[tip] >= 0) { kpeter@875: int u; kpeter@1046: LargeCost rc, min_red_cost = std::numeric_limits::max(); kpeter@1046: LargeCost pi_tip = _pi[tip]; kpeter@910: int last_out = _first_out[tip+1]; kpeter@875: for (int a = _next_out[tip]; a != last_out; ++a) { kpeter@1046: if (_res_cap[a] > 0) { kpeter@1046: u = _target[a]; kpeter@1046: rc = _cost[a] + pi_tip - _pi[u]; kpeter@1046: if (rc < 0) { kpeter@1046: path.push_back(a); kpeter@1046: _next_out[tip] = a; kpeter@1046: if (path_arc[a]) { kpeter@1046: goto augment; // a cycle is found, stop path search kpeter@1046: } kpeter@1046: tip = u; kpeter@1046: path_arc[a] = true; kpeter@1046: goto next_step; kpeter@1046: } kpeter@1046: else if (rc < min_red_cost) { kpeter@1046: min_red_cost = rc; kpeter@1046: } kpeter@874: } kpeter@874: } kpeter@874: kpeter@874: // Relabel tip node kpeter@910: if (tip != start) { kpeter@910: int ra = _reverse[path.back()]; kpeter@1046: min_red_cost = kpeter@1046: std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]); kpeter@910: } kpeter@1046: last_out = _next_out[tip]; kpeter@875: for (int a = _first_out[tip]; a != last_out; ++a) { kpeter@1046: if (_res_cap[a] > 0) { kpeter@1046: rc = _cost[a] + pi_tip - _pi[_target[a]]; kpeter@1046: if (rc < min_red_cost) { kpeter@1046: min_red_cost = rc; kpeter@1046: } kpeter@875: } kpeter@874: } kpeter@875: _pi[tip] -= min_red_cost + _epsilon; kpeter@875: _next_out[tip] = _first_out[tip]; kpeter@910: ++relabel_cnt; kpeter@874: kpeter@874: // Step back kpeter@874: if (tip != start) { kpeter@1046: int pa = path.back(); kpeter@1046: path_arc[pa] = false; kpeter@1046: tip = _source[pa]; kpeter@910: path.pop_back(); kpeter@874: } kpeter@874: kpeter@875: next_step: ; kpeter@874: } kpeter@874: kpeter@874: // Augment along the found path (as much flow as possible) kpeter@1046: augment: kpeter@875: Value delta; kpeter@910: int pa, u, v = start; kpeter@910: for (int i = 0; i != int(path.size()); ++i) { kpeter@910: pa = path[i]; kpeter@875: u = v; kpeter@910: v = _target[pa]; kpeter@1046: path_arc[pa] = false; kpeter@875: delta = std::min(_res_cap[pa], _excess[u]); kpeter@875: _res_cap[pa] -= delta; kpeter@875: _res_cap[_reverse[pa]] += delta; kpeter@875: _excess[u] -= delta; kpeter@875: _excess[v] += delta; kpeter@1046: if (_excess[v] > 0 && _excess[v] <= delta) { kpeter@875: _active_nodes.push_back(v); kpeter@1046: } kpeter@874: } kpeter@1046: path.clear(); kpeter@910: kpeter@910: // Global update heuristic kpeter@1046: if (relabel_cnt >= next_global_update_limit) { kpeter@910: globalUpdate(); kpeter@1046: next_global_update_limit += global_update_skip; kpeter@910: } kpeter@874: } kpeter@1046: kpeter@874: } kpeter@1046: kpeter@874: } kpeter@874: kpeter@875: /// Execute the algorithm performing push and relabel operations kpeter@876: void startPush() { kpeter@874: // Paramters for heuristics kpeter@1047: const int PRICE_REFINEMENT_LIMIT = 2; kpeter@910: const double GLOBAL_UPDATE_FACTOR = 2.0; kpeter@874: kpeter@1046: const int global_update_skip = static_cast(GLOBAL_UPDATE_FACTOR * kpeter@910: (_res_node_num + _sup_node_num * _sup_node_num)); kpeter@1046: int next_global_update_limit = global_update_skip; alpar@956: kpeter@875: // Perform cost scaling phases kpeter@875: BoolVector hyper(_res_node_num, false); kpeter@910: LargeCostVector hyper_cost(_res_node_num); kpeter@1046: int relabel_cnt = 0; kpeter@1047: int eps_phase_cnt = 0; kpeter@874: for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ? kpeter@874: 1 : _epsilon / _alpha ) kpeter@874: { kpeter@1047: ++eps_phase_cnt; kpeter@1047: kpeter@1047: // Price refinement heuristic kpeter@1047: if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) { kpeter@1047: if (priceRefinement()) continue; kpeter@874: } alpar@956: kpeter@910: // Initialize current phase kpeter@910: initPhase(); kpeter@874: kpeter@874: // Perform push and relabel operations kpeter@875: while (_active_nodes.size() > 0) { kpeter@910: LargeCost min_red_cost, rc, pi_n; kpeter@875: Value delta; kpeter@875: int n, t, a, last_out = _res_arc_num; kpeter@875: kpeter@910: next_node: kpeter@874: // Select an active node (FIFO selection) kpeter@875: n = _active_nodes.front(); kpeter@910: last_out = _first_out[n+1]; kpeter@910: pi_n = _pi[n]; alpar@956: kpeter@874: // Perform push operations if there are admissible arcs kpeter@875: if (_excess[n] > 0) { kpeter@875: for (a = _next_out[n]; a != last_out; ++a) { kpeter@875: if (_res_cap[a] > 0 && kpeter@910: _cost[a] + pi_n - _pi[_target[a]] < 0) { kpeter@875: delta = std::min(_res_cap[a], _excess[n]); kpeter@875: t = _target[a]; kpeter@874: kpeter@874: // Push-look-ahead heuristic kpeter@875: Value ahead = -_excess[t]; kpeter@910: int last_out_t = _first_out[t+1]; kpeter@910: LargeCost pi_t = _pi[t]; kpeter@875: for (int ta = _next_out[t]; ta != last_out_t; ++ta) { alpar@956: if (_res_cap[ta] > 0 && kpeter@910: _cost[ta] + pi_t - _pi[_target[ta]] < 0) kpeter@875: ahead += _res_cap[ta]; kpeter@875: if (ahead >= delta) break; kpeter@874: } kpeter@874: if (ahead < 0) ahead = 0; kpeter@874: kpeter@874: // Push flow along the arc kpeter@910: if (ahead < delta && !hyper[t]) { kpeter@875: _res_cap[a] -= ahead; kpeter@875: _res_cap[_reverse[a]] += ahead; kpeter@874: _excess[n] -= ahead; kpeter@874: _excess[t] += ahead; kpeter@875: _active_nodes.push_front(t); kpeter@874: hyper[t] = true; kpeter@910: hyper_cost[t] = _cost[a] + pi_n - pi_t; kpeter@875: _next_out[n] = a; kpeter@875: goto next_node; kpeter@874: } else { kpeter@875: _res_cap[a] -= delta; kpeter@875: _res_cap[_reverse[a]] += delta; kpeter@874: _excess[n] -= delta; kpeter@874: _excess[t] += delta; kpeter@874: if (_excess[t] > 0 && _excess[t] <= delta) kpeter@875: _active_nodes.push_back(t); kpeter@874: } kpeter@874: kpeter@875: if (_excess[n] == 0) { kpeter@875: _next_out[n] = a; kpeter@875: goto remove_nodes; kpeter@875: } kpeter@874: } kpeter@874: } kpeter@875: _next_out[n] = a; kpeter@874: } kpeter@874: kpeter@874: // Relabel the node if it is still active (or hyper) kpeter@875: if (_excess[n] > 0 || hyper[n]) { kpeter@910: min_red_cost = hyper[n] ? -hyper_cost[n] : kpeter@910: std::numeric_limits::max(); kpeter@875: for (int a = _first_out[n]; a != last_out; ++a) { kpeter@1046: if (_res_cap[a] > 0) { kpeter@1046: rc = _cost[a] + pi_n - _pi[_target[a]]; kpeter@1046: if (rc < min_red_cost) { kpeter@1046: min_red_cost = rc; kpeter@1046: } kpeter@875: } kpeter@874: } kpeter@875: _pi[n] -= min_red_cost + _epsilon; kpeter@910: _next_out[n] = _first_out[n]; kpeter@874: hyper[n] = false; kpeter@910: ++relabel_cnt; kpeter@874: } alpar@956: kpeter@874: // Remove nodes that are not active nor hyper kpeter@875: remove_nodes: kpeter@875: while ( _active_nodes.size() > 0 && kpeter@875: _excess[_active_nodes.front()] <= 0 && kpeter@875: !hyper[_active_nodes.front()] ) { kpeter@875: _active_nodes.pop_front(); kpeter@874: } alpar@956: kpeter@910: // Global update heuristic kpeter@1046: if (relabel_cnt >= next_global_update_limit) { kpeter@910: globalUpdate(); kpeter@910: for (int u = 0; u != _res_node_num; ++u) kpeter@910: hyper[u] = false; kpeter@1046: next_global_update_limit += global_update_skip; kpeter@910: } kpeter@874: } kpeter@874: } kpeter@874: } kpeter@874: kpeter@874: }; //class CostScaling kpeter@874: kpeter@874: ///@} kpeter@874: kpeter@874: } //namespace lemon kpeter@874: kpeter@874: #endif //LEMON_COST_SCALING_H