1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
 
     3  * This file is a part of LEMON, a generic C++ optimization library.
 
     5  * Copyright (C) 2003-2013
 
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
 
     9  * Permission to use, modify and distribute this software is granted
 
    10  * provided that this copyright notice appears in all copies. For
 
    11  * precise terms see the accompanying LICENSE file.
 
    13  * This software is provided "AS IS" with no warranty of any kind,
 
    14  * express or implied, and with no claim as to its suitability for any
 
    19 #ifndef LEMON_CYCLE_CANCELING_H
 
    20 #define LEMON_CYCLE_CANCELING_H
 
    22 /// \ingroup min_cost_flow_algs
 
    24 /// \brief Cycle-canceling algorithms for finding a minimum cost flow.
 
    29 #include <lemon/core.h>
 
    30 #include <lemon/maps.h>
 
    31 #include <lemon/path.h>
 
    32 #include <lemon/math.h>
 
    33 #include <lemon/static_graph.h>
 
    34 #include <lemon/adaptors.h>
 
    35 #include <lemon/circulation.h>
 
    36 #include <lemon/bellman_ford.h>
 
    37 #include <lemon/howard_mmc.h>
 
    38 #include <lemon/hartmann_orlin_mmc.h>
 
    42   /// \addtogroup min_cost_flow_algs
 
    45   /// \brief Implementation of cycle-canceling algorithms for
 
    46   /// finding a \ref min_cost_flow "minimum cost flow".
 
    48   /// \ref CycleCanceling implements three different cycle-canceling
 
    49   /// algorithms for finding a \ref min_cost_flow "minimum cost flow"
 
    50   /// \cite amo93networkflows, \cite klein67primal,
 
    51   /// \cite goldberg89cyclecanceling.
 
    52   /// The most efficent one is the \ref CANCEL_AND_TIGHTEN
 
    53   /// "Cancel-and-Tighten" algorithm, thus it is the default method.
 
    54   /// It runs in strongly polynomial time \f$O(n^2 m^2 \log n)\f$,
 
    55   /// but in practice, it is typically orders of magnitude slower than
 
    56   /// the scaling algorithms and \ref NetworkSimplex.
 
    57   /// (For more information, see \ref min_cost_flow_algs "the module page".)
 
    59   /// Most of the parameters of the problem (except for the digraph)
 
    60   /// can be given using separate functions, and the algorithm can be
 
    61   /// executed using the \ref run() function. If some parameters are not
 
    62   /// specified, then default values will be used.
 
    64   /// \tparam GR The digraph type the algorithm runs on.
 
    65   /// \tparam V The number type used for flow amounts, capacity bounds
 
    66   /// and supply values in the algorithm. By default, it is \c int.
 
    67   /// \tparam C The number type used for costs and potentials in the
 
    68   /// algorithm. By default, it is the same as \c V.
 
    70   /// \warning Both \c V and \c C must be signed number types.
 
    71   /// \warning All input data (capacities, supply values, and costs) must
 
    73   /// \warning This algorithm does not support negative costs for
 
    74   /// arcs having infinite upper bound.
 
    76   /// \note For more information about the three available methods,
 
    79   template <typename GR, typename V, typename C>
 
    81   template <typename GR, typename V = int, typename C = V>
 
    87     /// The type of the digraph
 
    89     /// The type of the flow amounts, capacity bounds and supply values
 
    91     /// The type of the arc costs
 
    96     /// \brief Problem type constants for the \c run() function.
 
    98     /// Enum type containing the problem type constants that can be
 
    99     /// returned by the \ref run() function of the algorithm.
 
   101       /// The problem has no feasible solution (flow).
 
   103       /// The problem has optimal solution (i.e. it is feasible and
 
   104       /// bounded), and the algorithm has found optimal flow and node
 
   105       /// potentials (primal and dual solutions).
 
   107       /// The digraph contains an arc of negative cost and infinite
 
   108       /// upper bound. It means that the objective function is unbounded
 
   109       /// on that arc, however, note that it could actually be bounded
 
   110       /// over the feasible flows, but this algroithm cannot handle
 
   115     /// \brief Constants for selecting the used method.
 
   117     /// Enum type containing constants for selecting the used method
 
   118     /// for the \ref run() function.
 
   120     /// \ref CycleCanceling provides three different cycle-canceling
 
   121     /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel-and-Tighten"
 
   122     /// is used, which is by far the most efficient and the most robust.
 
   123     /// However, the other methods can be selected using the \ref run()
 
   124     /// function with the proper parameter.
 
   126       /// A simple cycle-canceling method, which uses the
 
   127       /// \ref BellmanFord "Bellman-Ford" algorithm for detecting negative
 
   128       /// cycles in the residual network.
 
   129       /// The number of Bellman-Ford iterations is bounded by a successively
 
   131       SIMPLE_CYCLE_CANCELING,
 
   132       /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
 
   133       /// well-known strongly polynomial method
 
   134       /// \cite goldberg89cyclecanceling. It improves along a
 
   135       /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
 
   136       /// Its running time complexity is \f$O(n^2 m^3 \log n)\f$.
 
   137       MINIMUM_MEAN_CYCLE_CANCELING,
 
   138       /// The "Cancel-and-Tighten" algorithm, which can be viewed as an
 
   139       /// improved version of the previous method
 
   140       /// \cite goldberg89cyclecanceling.
 
   141       /// It is faster both in theory and in practice, its running time
 
   142       /// complexity is \f$O(n^2 m^2 \log n)\f$.
 
   148     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
 
   150     typedef std::vector<int> IntVector;
 
   151     typedef std::vector<double> DoubleVector;
 
   152     typedef std::vector<Value> ValueVector;
 
   153     typedef std::vector<Cost> CostVector;
 
   154     typedef std::vector<char> BoolVector;
 
   155     // Note: vector<char> is used instead of vector<bool> for efficiency reasons
 
   159     template <typename KT, typename VT>
 
   160     class StaticVectorMap {
 
   165       StaticVectorMap(std::vector<Value>& v) : _v(v) {}
 
   167       const Value& operator[](const Key& key) const {
 
   168         return _v[StaticDigraph::id(key)];
 
   171       Value& operator[](const Key& key) {
 
   172         return _v[StaticDigraph::id(key)];
 
   175       void set(const Key& key, const Value& val) {
 
   176         _v[StaticDigraph::id(key)] = val;
 
   180       std::vector<Value>& _v;
 
   183     typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
 
   184     typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
 
   189     // Data related to the underlying digraph
 
   197     // Parameters of the problem
 
   201     // Data structures for storing the digraph
 
   205     IntVector _first_out;
 
   217     ValueVector _res_cap;
 
   220     // Data for a StaticDigraph structure
 
   221     typedef std::pair<int, int> IntPair;
 
   223     std::vector<IntPair> _arc_vec;
 
   224     std::vector<Cost> _cost_vec;
 
   226     CostArcMap _cost_map;
 
   231     /// \brief Constant for infinite upper bounds (capacities).
 
   233     /// Constant for infinite upper bounds (capacities).
 
   234     /// It is \c std::numeric_limits<Value>::infinity() if available,
 
   235     /// \c std::numeric_limits<Value>::max() otherwise.
 
   240     /// \brief Constructor.
 
   242     /// The constructor of the class.
 
   244     /// \param graph The digraph the algorithm runs on.
 
   245     CycleCanceling(const GR& graph) :
 
   246       _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
 
   247       _cost_map(_cost_vec), _pi_map(_pi),
 
   248       INF(std::numeric_limits<Value>::has_infinity ?
 
   249           std::numeric_limits<Value>::infinity() :
 
   250           std::numeric_limits<Value>::max())
 
   252       // Check the number types
 
   253       LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
 
   254         "The flow type of CycleCanceling must be signed");
 
   255       LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
 
   256         "The cost type of CycleCanceling must be signed");
 
   258       // Reset data structures
 
   263     /// The parameters of the algorithm can be specified using these
 
   268     /// \brief Set the lower bounds on the arcs.
 
   270     /// This function sets the lower bounds on the arcs.
 
   271     /// If it is not used before calling \ref run(), the lower bounds
 
   272     /// will be set to zero on all arcs.
 
   274     /// \param map An arc map storing the lower bounds.
 
   275     /// Its \c Value type must be convertible to the \c Value type
 
   276     /// of the algorithm.
 
   278     /// \return <tt>(*this)</tt>
 
   279     template <typename LowerMap>
 
   280     CycleCanceling& lowerMap(const LowerMap& map) {
 
   282       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   283         _lower[_arc_idf[a]] = map[a];
 
   288     /// \brief Set the upper bounds (capacities) on the arcs.
 
   290     /// This function sets the upper bounds (capacities) on the arcs.
 
   291     /// If it is not used before calling \ref run(), the upper bounds
 
   292     /// will be set to \ref INF on all arcs (i.e. the flow value will be
 
   293     /// unbounded from above).
 
   295     /// \param map An arc map storing the upper bounds.
 
   296     /// Its \c Value type must be convertible to the \c Value type
 
   297     /// of the algorithm.
 
   299     /// \return <tt>(*this)</tt>
 
   300     template<typename UpperMap>
 
   301     CycleCanceling& upperMap(const UpperMap& map) {
 
   302       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   303         _upper[_arc_idf[a]] = map[a];
 
   308     /// \brief Set the costs of the arcs.
 
   310     /// This function sets the costs of the arcs.
 
   311     /// If it is not used before calling \ref run(), the costs
 
   312     /// will be set to \c 1 on all arcs.
 
   314     /// \param map An arc map storing the costs.
 
   315     /// Its \c Value type must be convertible to the \c Cost type
 
   316     /// of the algorithm.
 
   318     /// \return <tt>(*this)</tt>
 
   319     template<typename CostMap>
 
   320     CycleCanceling& costMap(const CostMap& map) {
 
   321       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   322         _cost[_arc_idf[a]] =  map[a];
 
   323         _cost[_arc_idb[a]] = -map[a];
 
   328     /// \brief Set the supply values of the nodes.
 
   330     /// This function sets the supply values of the nodes.
 
   331     /// If neither this function nor \ref stSupply() is used before
 
   332     /// calling \ref run(), the supply of each node will be set to zero.
 
   334     /// \param map A node map storing the supply values.
 
   335     /// Its \c Value type must be convertible to the \c Value type
 
   336     /// of the algorithm.
 
   338     /// \return <tt>(*this)</tt>
 
   339     template<typename SupplyMap>
 
   340     CycleCanceling& supplyMap(const SupplyMap& map) {
 
   341       for (NodeIt n(_graph); n != INVALID; ++n) {
 
   342         _supply[_node_id[n]] = map[n];
 
   347     /// \brief Set single source and target nodes and a supply value.
 
   349     /// This function sets a single source node and a single target node
 
   350     /// and the required flow value.
 
   351     /// If neither this function nor \ref supplyMap() is used before
 
   352     /// calling \ref run(), the supply of each node will be set to zero.
 
   354     /// Using this function has the same effect as using \ref supplyMap()
 
   355     /// with a map in which \c k is assigned to \c s, \c -k is
 
   356     /// assigned to \c t and all other nodes have zero supply value.
 
   358     /// \param s The source node.
 
   359     /// \param t The target node.
 
   360     /// \param k The required amount of flow from node \c s to node \c t
 
   361     /// (i.e. the supply of \c s and the demand of \c t).
 
   363     /// \return <tt>(*this)</tt>
 
   364     CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
 
   365       for (int i = 0; i != _res_node_num; ++i) {
 
   368       _supply[_node_id[s]] =  k;
 
   369       _supply[_node_id[t]] = -k;
 
   375     /// \name Execution control
 
   376     /// The algorithm can be executed using \ref run().
 
   380     /// \brief Run the algorithm.
 
   382     /// This function runs the algorithm.
 
   383     /// The paramters can be specified using functions \ref lowerMap(),
 
   384     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
 
   387     ///   CycleCanceling<ListDigraph> cc(graph);
 
   388     ///   cc.lowerMap(lower).upperMap(upper).costMap(cost)
 
   389     ///     .supplyMap(sup).run();
 
   392     /// This function can be called more than once. All the given parameters
 
   393     /// are kept for the next call, unless \ref resetParams() or \ref reset()
 
   394     /// is used, thus only the modified parameters have to be set again.
 
   395     /// If the underlying digraph was also modified after the construction
 
   396     /// of the class (or the last \ref reset() call), then the \ref reset()
 
   397     /// function must be called.
 
   399     /// \param method The cycle-canceling method that will be used.
 
   400     /// For more information, see \ref Method.
 
   402     /// \return \c INFEASIBLE if no feasible flow exists,
 
   403     /// \n \c OPTIMAL if the problem has optimal solution
 
   404     /// (i.e. it is feasible and bounded), and the algorithm has found
 
   405     /// optimal flow and node potentials (primal and dual solutions),
 
   406     /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
 
   407     /// and infinite upper bound. It means that the objective function
 
   408     /// is unbounded on that arc, however, note that it could actually be
 
   409     /// bounded over the feasible flows, but this algroithm cannot handle
 
   412     /// \see ProblemType, Method
 
   413     /// \see resetParams(), reset()
 
   414     ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
 
   415       ProblemType pt = init();
 
   416       if (pt != OPTIMAL) return pt;
 
   421     /// \brief Reset all the parameters that have been given before.
 
   423     /// This function resets all the paramaters that have been given
 
   424     /// before using functions \ref lowerMap(), \ref upperMap(),
 
   425     /// \ref costMap(), \ref supplyMap(), \ref stSupply().
 
   427     /// It is useful for multiple \ref run() calls. Basically, all the given
 
   428     /// parameters are kept for the next \ref run() call, unless
 
   429     /// \ref resetParams() or \ref reset() is used.
 
   430     /// If the underlying digraph was also modified after the construction
 
   431     /// of the class or the last \ref reset() call, then the \ref reset()
 
   432     /// function must be used, otherwise \ref resetParams() is sufficient.
 
   436     ///   CycleCanceling<ListDigraph> cs(graph);
 
   439     ///   cc.lowerMap(lower).upperMap(upper).costMap(cost)
 
   440     ///     .supplyMap(sup).run();
 
   442     ///   // Run again with modified cost map (resetParams() is not called,
 
   443     ///   // so only the cost map have to be set again)
 
   445     ///   cc.costMap(cost).run();
 
   447     ///   // Run again from scratch using resetParams()
 
   448     ///   // (the lower bounds will be set to zero on all arcs)
 
   449     ///   cc.resetParams();
 
   450     ///   cc.upperMap(capacity).costMap(cost)
 
   451     ///     .supplyMap(sup).run();
 
   454     /// \return <tt>(*this)</tt>
 
   456     /// \see reset(), run()
 
   457     CycleCanceling& resetParams() {
 
   458       for (int i = 0; i != _res_node_num; ++i) {
 
   461       int limit = _first_out[_root];
 
   462       for (int j = 0; j != limit; ++j) {
 
   465         _cost[j] = _forward[j] ? 1 : -1;
 
   467       for (int j = limit; j != _res_arc_num; ++j) {
 
   471         _cost[_reverse[j]] = 0;
 
   477     /// \brief Reset the internal data structures and all the parameters
 
   478     /// that have been given before.
 
   480     /// This function resets the internal data structures and all the
 
   481     /// paramaters that have been given before using functions \ref lowerMap(),
 
   482     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
 
   484     /// It is useful for multiple \ref run() calls. Basically, all the given
 
   485     /// parameters are kept for the next \ref run() call, unless
 
   486     /// \ref resetParams() or \ref reset() is used.
 
   487     /// If the underlying digraph was also modified after the construction
 
   488     /// of the class or the last \ref reset() call, then the \ref reset()
 
   489     /// function must be used, otherwise \ref resetParams() is sufficient.
 
   491     /// See \ref resetParams() for examples.
 
   493     /// \return <tt>(*this)</tt>
 
   495     /// \see resetParams(), run()
 
   496     CycleCanceling& reset() {
 
   498       _node_num = countNodes(_graph);
 
   499       _arc_num = countArcs(_graph);
 
   500       _res_node_num = _node_num + 1;
 
   501       _res_arc_num = 2 * (_arc_num + _node_num);
 
   504       _first_out.resize(_res_node_num + 1);
 
   505       _forward.resize(_res_arc_num);
 
   506       _source.resize(_res_arc_num);
 
   507       _target.resize(_res_arc_num);
 
   508       _reverse.resize(_res_arc_num);
 
   510       _lower.resize(_res_arc_num);
 
   511       _upper.resize(_res_arc_num);
 
   512       _cost.resize(_res_arc_num);
 
   513       _supply.resize(_res_node_num);
 
   515       _res_cap.resize(_res_arc_num);
 
   516       _pi.resize(_res_node_num);
 
   518       _arc_vec.reserve(_res_arc_num);
 
   519       _cost_vec.reserve(_res_arc_num);
 
   520       _id_vec.reserve(_res_arc_num);
 
   523       int i = 0, j = 0, k = 2 * _arc_num + _node_num;
 
   524       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
 
   528       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
 
   530         for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
 
   534           _target[j] = _node_id[_graph.runningNode(a)];
 
   536         for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
 
   540           _target[j] = _node_id[_graph.runningNode(a)];
 
   553       _first_out[_res_node_num] = k;
 
   554       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   555         int fi = _arc_idf[a];
 
   556         int bi = _arc_idb[a];
 
   568     /// \name Query Functions
 
   569     /// The results of the algorithm can be obtained using these
 
   571     /// The \ref run() function must be called before using them.
 
   575     /// \brief Return the total cost of the found flow.
 
   577     /// This function returns the total cost of the found flow.
 
   578     /// Its complexity is O(m).
 
   580     /// \note The return type of the function can be specified as a
 
   581     /// template parameter. For example,
 
   583     ///   cc.totalCost<double>();
 
   585     /// It is useful if the total cost cannot be stored in the \c Cost
 
   586     /// type of the algorithm, which is the default return type of the
 
   589     /// \pre \ref run() must be called before using this function.
 
   590     template <typename Number>
 
   591     Number totalCost() const {
 
   593       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   595         c += static_cast<Number>(_res_cap[i]) *
 
   596              (-static_cast<Number>(_cost[i]));
 
   602     Cost totalCost() const {
 
   603       return totalCost<Cost>();
 
   607     /// \brief Return the flow on the given arc.
 
   609     /// This function returns the flow on the given arc.
 
   611     /// \pre \ref run() must be called before using this function.
 
   612     Value flow(const Arc& a) const {
 
   613       return _res_cap[_arc_idb[a]];
 
   616     /// \brief Copy the flow values (the primal solution) into the
 
   619     /// This function copies the flow value on each arc into the given
 
   620     /// map. The \c Value type of the algorithm must be convertible to
 
   621     /// the \c Value type of the map.
 
   623     /// \pre \ref run() must be called before using this function.
 
   624     template <typename FlowMap>
 
   625     void flowMap(FlowMap &map) const {
 
   626       for (ArcIt a(_graph); a != INVALID; ++a) {
 
   627         map.set(a, _res_cap[_arc_idb[a]]);
 
   631     /// \brief Return the potential (dual value) of the given node.
 
   633     /// This function returns the potential (dual value) of the
 
   636     /// \pre \ref run() must be called before using this function.
 
   637     Cost potential(const Node& n) const {
 
   638       return static_cast<Cost>(_pi[_node_id[n]]);
 
   641     /// \brief Copy the potential values (the dual solution) into the
 
   644     /// This function copies the potential (dual value) of each node
 
   645     /// into the given map.
 
   646     /// The \c Cost type of the algorithm must be convertible to the
 
   647     /// \c Value type of the map.
 
   649     /// \pre \ref run() must be called before using this function.
 
   650     template <typename PotentialMap>
 
   651     void potentialMap(PotentialMap &map) const {
 
   652       for (NodeIt n(_graph); n != INVALID; ++n) {
 
   653         map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
 
   661     // Initialize the algorithm
 
   663       if (_res_node_num <= 1) return INFEASIBLE;
 
   665       // Check the sum of supply values
 
   667       for (int i = 0; i != _root; ++i) {
 
   668         _sum_supply += _supply[i];
 
   670       if (_sum_supply > 0) return INFEASIBLE;
 
   672       // Check lower and upper bounds
 
   673       LEMON_DEBUG(checkBoundMaps(),
 
   674           "Upper bounds must be greater or equal to the lower bounds");
 
   677       // Initialize vectors
 
   678       for (int i = 0; i != _res_node_num; ++i) {
 
   681       ValueVector excess(_supply);
 
   683       // Remove infinite upper bounds and check negative arcs
 
   684       const Value MAX = std::numeric_limits<Value>::max();
 
   687         for (int i = 0; i != _root; ++i) {
 
   688           last_out = _first_out[i+1];
 
   689           for (int j = _first_out[i]; j != last_out; ++j) {
 
   691               Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
 
   692               if (c >= MAX) return UNBOUNDED;
 
   694               excess[_target[j]] += c;
 
   699         for (int i = 0; i != _root; ++i) {
 
   700           last_out = _first_out[i+1];
 
   701           for (int j = _first_out[i]; j != last_out; ++j) {
 
   702             if (_forward[j] && _cost[j] < 0) {
 
   704               if (c >= MAX) return UNBOUNDED;
 
   706               excess[_target[j]] += c;
 
   711       Value ex, max_cap = 0;
 
   712       for (int i = 0; i != _res_node_num; ++i) {
 
   714         if (ex < 0) max_cap -= ex;
 
   716       for (int j = 0; j != _res_arc_num; ++j) {
 
   717         if (_upper[j] >= MAX) _upper[j] = max_cap;
 
   720       // Initialize maps for Circulation and remove non-zero lower bounds
 
   721       ConstMap<Arc, Value> low(0);
 
   722       typedef typename Digraph::template ArcMap<Value> ValueArcMap;
 
   723       typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
 
   724       ValueArcMap cap(_graph), flow(_graph);
 
   725       ValueNodeMap sup(_graph);
 
   726       for (NodeIt n(_graph); n != INVALID; ++n) {
 
   727         sup[n] = _supply[_node_id[n]];
 
   730         for (ArcIt a(_graph); a != INVALID; ++a) {
 
   733           cap[a] = _upper[j] - c;
 
   734           sup[_graph.source(a)] -= c;
 
   735           sup[_graph.target(a)] += c;
 
   738         for (ArcIt a(_graph); a != INVALID; ++a) {
 
   739           cap[a] = _upper[_arc_idf[a]];
 
   743       // Find a feasible flow using Circulation
 
   744       Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
 
   745         circ(_graph, low, cap, sup);
 
   746       if (!circ.flowMap(flow).run()) return INFEASIBLE;
 
   748       // Set residual capacities and handle GEQ supply type
 
   749       if (_sum_supply < 0) {
 
   750         for (ArcIt a(_graph); a != INVALID; ++a) {
 
   752           _res_cap[_arc_idf[a]] = cap[a] - fa;
 
   753           _res_cap[_arc_idb[a]] = fa;
 
   754           sup[_graph.source(a)] -= fa;
 
   755           sup[_graph.target(a)] += fa;
 
   757         for (NodeIt n(_graph); n != INVALID; ++n) {
 
   758           excess[_node_id[n]] = sup[n];
 
   760         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
 
   762           int ra = _reverse[a];
 
   763           _res_cap[a] = -_sum_supply + 1;
 
   764           _res_cap[ra] = -excess[u];
 
   769         for (ArcIt a(_graph); a != INVALID; ++a) {
 
   771           _res_cap[_arc_idf[a]] = cap[a] - fa;
 
   772           _res_cap[_arc_idb[a]] = fa;
 
   774         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
 
   775           int ra = _reverse[a];
 
   786     // Check if the upper bound is greater than or equal to the lower bound
 
   787     // on each forward arc.
 
   788     bool checkBoundMaps() {
 
   789       for (int j = 0; j != _res_arc_num; ++j) {
 
   790         if (_forward[j] && _upper[j] < _lower[j]) return false;
 
   795     // Build a StaticDigraph structure containing the current
 
   797     void buildResidualNetwork() {
 
   801       for (int j = 0; j != _res_arc_num; ++j) {
 
   802         if (_res_cap[j] > 0) {
 
   803           _arc_vec.push_back(IntPair(_source[j], _target[j]));
 
   804           _cost_vec.push_back(_cost[j]);
 
   805           _id_vec.push_back(j);
 
   808       _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
 
   811     // Execute the algorithm and transform the results
 
   812     void start(Method method) {
 
   813       // Execute the algorithm
 
   815         case SIMPLE_CYCLE_CANCELING:
 
   816           startSimpleCycleCanceling();
 
   818         case MINIMUM_MEAN_CYCLE_CANCELING:
 
   819           startMinMeanCycleCanceling();
 
   821         case CANCEL_AND_TIGHTEN:
 
   822           startCancelAndTighten();
 
   826       // Compute node potentials
 
   827       if (method != SIMPLE_CYCLE_CANCELING) {
 
   828         buildResidualNetwork();
 
   829         typename BellmanFord<StaticDigraph, CostArcMap>
 
   830           ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
 
   836       // Handle non-zero lower bounds
 
   838         int limit = _first_out[_root];
 
   839         for (int j = 0; j != limit; ++j) {
 
   840           if (_forward[j]) _res_cap[_reverse[j]] += _lower[j];
 
   845     // Execute the "Simple Cycle Canceling" method
 
   846     void startSimpleCycleCanceling() {
 
   847       // Constants for computing the iteration limits
 
   848       const int BF_FIRST_LIMIT  = 2;
 
   849       const double BF_LIMIT_FACTOR = 1.5;
 
   851       typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
 
   852       typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
 
   853       typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
 
   854       typedef typename BellmanFord<ResDigraph, CostArcMap>
 
   855         ::template SetDistMap<CostNodeMap>
 
   856         ::template SetPredMap<PredMap>::Create BF;
 
   858       // Build the residual network
 
   861       for (int j = 0; j != _res_arc_num; ++j) {
 
   862         _arc_vec.push_back(IntPair(_source[j], _target[j]));
 
   863         _cost_vec.push_back(_cost[j]);
 
   865       _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
 
   867       FilterMap filter_map(_res_cap);
 
   868       ResDigraph rgr(_sgr, filter_map);
 
   869       std::vector<int> cycle;
 
   870       std::vector<StaticDigraph::Arc> pred(_res_arc_num);
 
   871       PredMap pred_map(pred);
 
   872       BF bf(rgr, _cost_map);
 
   873       bf.distMap(_pi_map).predMap(pred_map);
 
   875       int length_bound = BF_FIRST_LIMIT;
 
   876       bool optimal = false;
 
   880         bool cycle_found = false;
 
   881         while (!cycle_found) {
 
   882           // Perform some iterations of the Bellman-Ford algorithm
 
   883           int curr_iter_num = iter_num + length_bound <= _node_num ?
 
   884             length_bound : _node_num - iter_num;
 
   885           iter_num += curr_iter_num;
 
   886           int real_iter_num = curr_iter_num;
 
   887           for (int i = 0; i < curr_iter_num; ++i) {
 
   888             if (bf.processNextWeakRound()) {
 
   893           if (real_iter_num < curr_iter_num) {
 
   894             // Optimal flow is found
 
   898             // Search for node disjoint negative cycles
 
   899             std::vector<int> state(_res_node_num, 0);
 
   901             for (int u = 0; u != _res_node_num; ++u) {
 
   902               if (state[u] != 0) continue;
 
   905               for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
 
   906                    -1 : rgr.id(rgr.source(pred[v]))) {
 
   909               if (v != -1 && state[v] == id) {
 
   910                 // A negative cycle is found
 
   913                 StaticDigraph::Arc a = pred[v];
 
   914                 Value d, delta = _res_cap[rgr.id(a)];
 
   915                 cycle.push_back(rgr.id(a));
 
   916                 while (rgr.id(rgr.source(a)) != v) {
 
   917                   a = pred_map[rgr.source(a)];
 
   918                   d = _res_cap[rgr.id(a)];
 
   919                   if (d < delta) delta = d;
 
   920                   cycle.push_back(rgr.id(a));
 
   923                 // Augment along the cycle
 
   924                 for (int i = 0; i < int(cycle.size()); ++i) {
 
   926                   _res_cap[j] -= delta;
 
   927                   _res_cap[_reverse[j]] += delta;
 
   933           // Increase iteration limit if no cycle is found
 
   935             length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
 
   941     // Execute the "Minimum Mean Cycle Canceling" method
 
   942     void startMinMeanCycleCanceling() {
 
   943       typedef Path<StaticDigraph> SPath;
 
   944       typedef typename SPath::ArcIt SPathArcIt;
 
   945       typedef typename HowardMmc<StaticDigraph, CostArcMap>
 
   946         ::template SetPath<SPath>::Create HwMmc;
 
   947       typedef typename HartmannOrlinMmc<StaticDigraph, CostArcMap>
 
   948         ::template SetPath<SPath>::Create HoMmc;
 
   950       const double HW_ITER_LIMIT_FACTOR = 1.0;
 
   951       const int HW_ITER_LIMIT_MIN_VALUE = 5;
 
   953       const int hw_iter_limit =
 
   954           std::max(static_cast<int>(HW_ITER_LIMIT_FACTOR * _node_num),
 
   955                    HW_ITER_LIMIT_MIN_VALUE);
 
   958       HwMmc hw_mmc(_sgr, _cost_map);
 
   960       buildResidualNetwork();
 
   963         typename HwMmc::TerminationCause hw_tc =
 
   964             hw_mmc.findCycleMean(hw_iter_limit);
 
   965         if (hw_tc == HwMmc::ITERATION_LIMIT) {
 
   966           // Howard's algorithm reached the iteration limit, start a
 
   967           // strongly polynomial algorithm instead
 
   968           HoMmc ho_mmc(_sgr, _cost_map);
 
   970           // Find a minimum mean cycle (Hartmann-Orlin algorithm)
 
   971           if (!(ho_mmc.findCycleMean() && ho_mmc.cycleCost() < 0)) break;
 
   974           // Find a minimum mean cycle (Howard algorithm)
 
   975           if (!(hw_tc == HwMmc::OPTIMAL && hw_mmc.cycleCost() < 0)) break;
 
   979         // Compute delta value
 
   981         for (SPathArcIt a(cycle); a != INVALID; ++a) {
 
   982           Value d = _res_cap[_id_vec[_sgr.id(a)]];
 
   983           if (d < delta) delta = d;
 
   986         // Augment along the cycle
 
   987         for (SPathArcIt a(cycle); a != INVALID; ++a) {
 
   988           int j = _id_vec[_sgr.id(a)];
 
   989           _res_cap[j] -= delta;
 
   990           _res_cap[_reverse[j]] += delta;
 
   993         // Rebuild the residual network
 
   994         buildResidualNetwork();
 
   998     // Execute the "Cancel-and-Tighten" method
 
   999     void startCancelAndTighten() {
 
  1000       // Constants for the min mean cycle computations
 
  1001       const double LIMIT_FACTOR = 1.0;
 
  1002       const int MIN_LIMIT = 5;
 
  1003       const double HW_ITER_LIMIT_FACTOR = 1.0;
 
  1004       const int HW_ITER_LIMIT_MIN_VALUE = 5;
 
  1006       const int hw_iter_limit =
 
  1007           std::max(static_cast<int>(HW_ITER_LIMIT_FACTOR * _node_num),
 
  1008                    HW_ITER_LIMIT_MIN_VALUE);
 
  1010       // Contruct auxiliary data vectors
 
  1011       DoubleVector pi(_res_node_num, 0.0);
 
  1012       IntVector level(_res_node_num);
 
  1013       BoolVector reached(_res_node_num);
 
  1014       BoolVector processed(_res_node_num);
 
  1015       IntVector pred_node(_res_node_num);
 
  1016       IntVector pred_arc(_res_node_num);
 
  1017       std::vector<int> stack(_res_node_num);
 
  1018       std::vector<int> proc_vector(_res_node_num);
 
  1020       // Initialize epsilon
 
  1022       for (int a = 0; a != _res_arc_num; ++a) {
 
  1023         if (_res_cap[a] > 0 && -_cost[a] > epsilon)
 
  1024           epsilon = -_cost[a];
 
  1028       Tolerance<double> tol;
 
  1030       int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
 
  1031       if (limit < MIN_LIMIT) limit = MIN_LIMIT;
 
  1033       while (epsilon * _res_node_num >= 1) {
 
  1034         // Find and cancel cycles in the admissible network using DFS
 
  1035         for (int u = 0; u != _res_node_num; ++u) {
 
  1037           processed[u] = false;
 
  1039         int stack_head = -1;
 
  1041         for (int start = 0; start != _res_node_num; ++start) {
 
  1042           if (reached[start]) continue;
 
  1045           reached[start] = true;
 
  1046           pred_arc[start] = -1;
 
  1047           pred_node[start] = -1;
 
  1049           // Find the first admissible outgoing arc
 
  1050           double p = pi[start];
 
  1051           int a = _first_out[start];
 
  1052           int last_out = _first_out[start+1];
 
  1053           for (; a != last_out && (_res_cap[a] == 0 ||
 
  1054                !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
 
  1055           if (a == last_out) {
 
  1056             processed[start] = true;
 
  1057             proc_vector[++proc_head] = start;
 
  1060           stack[++stack_head] = a;
 
  1062           while (stack_head >= 0) {
 
  1063             int sa = stack[stack_head];
 
  1064             int u = _source[sa];
 
  1065             int v = _target[sa];
 
  1068               // A new node is reached
 
  1074               last_out = _first_out[v+1];
 
  1075               for (; a != last_out && (_res_cap[a] == 0 ||
 
  1076                    !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
 
  1077               stack[++stack_head] = a == last_out ? -1 : a;
 
  1079               if (!processed[v]) {
 
  1082                 Value d, delta = _res_cap[sa];
 
  1083                 for (n = u; n != v; n = pred_node[n]) {
 
  1084                   d = _res_cap[pred_arc[n]];
 
  1091                 // Augment along the cycle
 
  1092                 _res_cap[sa] -= delta;
 
  1093                 _res_cap[_reverse[sa]] += delta;
 
  1094                 for (n = u; n != v; n = pred_node[n]) {
 
  1095                   int pa = pred_arc[n];
 
  1096                   _res_cap[pa] -= delta;
 
  1097                   _res_cap[_reverse[pa]] += delta;
 
  1099                 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
 
  1107               // Find the next admissible outgoing arc
 
  1109               a = stack[stack_head] + 1;
 
  1110               last_out = _first_out[v+1];
 
  1111               for (; a != last_out && (_res_cap[a] == 0 ||
 
  1112                    !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
 
  1113               stack[stack_head] = a == last_out ? -1 : a;
 
  1116             while (stack_head >= 0 && stack[stack_head] == -1) {
 
  1117               processed[v] = true;
 
  1118               proc_vector[++proc_head] = v;
 
  1119               if (--stack_head >= 0) {
 
  1120                 // Find the next admissible outgoing arc
 
  1121                 v = _source[stack[stack_head]];
 
  1123                 a = stack[stack_head] + 1;
 
  1124                 last_out = _first_out[v+1];
 
  1125                 for (; a != last_out && (_res_cap[a] == 0 ||
 
  1126                      !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
 
  1127                 stack[stack_head] = a == last_out ? -1 : a;
 
  1133         // Tighten potentials and epsilon
 
  1135           for (int u = 0; u != _res_node_num; ++u) {
 
  1138           for (int i = proc_head; i > 0; --i) {
 
  1139             int u = proc_vector[i];
 
  1141             int l = level[u] + 1;
 
  1142             int last_out = _first_out[u+1];
 
  1143             for (int a = _first_out[u]; a != last_out; ++a) {
 
  1145               if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
 
  1146                   l > level[v]) level[v] = l;
 
  1150           // Modify potentials
 
  1151           double q = std::numeric_limits<double>::max();
 
  1152           for (int u = 0; u != _res_node_num; ++u) {
 
  1154             double p, pu = pi[u];
 
  1155             int last_out = _first_out[u+1];
 
  1156             for (int a = _first_out[u]; a != last_out; ++a) {
 
  1157               if (_res_cap[a] == 0) continue;
 
  1159               int ld = lu - level[v];
 
  1161                 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
 
  1166           for (int u = 0; u != _res_node_num; ++u) {
 
  1167             pi[u] -= q * level[u];
 
  1172           for (int u = 0; u != _res_node_num; ++u) {
 
  1173             double curr, pu = pi[u];
 
  1174             int last_out = _first_out[u+1];
 
  1175             for (int a = _first_out[u]; a != last_out; ++a) {
 
  1176               if (_res_cap[a] == 0) continue;
 
  1177               curr = _cost[a] + pu - pi[_target[a]];
 
  1178               if (-curr > epsilon) epsilon = -curr;
 
  1182           typedef HowardMmc<StaticDigraph, CostArcMap> HwMmc;
 
  1183           typedef HartmannOrlinMmc<StaticDigraph, CostArcMap> HoMmc;
 
  1184           typedef typename BellmanFord<StaticDigraph, CostArcMap>
 
  1185             ::template SetDistMap<CostNodeMap>::Create BF;
 
  1187           // Set epsilon to the minimum cycle mean
 
  1188           Cost cycle_cost = 0;
 
  1190           buildResidualNetwork();
 
  1191           HwMmc hw_mmc(_sgr, _cost_map);
 
  1192           if (hw_mmc.findCycleMean(hw_iter_limit) == HwMmc::ITERATION_LIMIT) {
 
  1193             // Howard's algorithm reached the iteration limit, start a
 
  1194             // strongly polynomial algorithm instead
 
  1195             HoMmc ho_mmc(_sgr, _cost_map);
 
  1196             ho_mmc.findCycleMean();
 
  1197             epsilon = -ho_mmc.cycleMean();
 
  1198             cycle_cost = ho_mmc.cycleCost();
 
  1199             cycle_size = ho_mmc.cycleSize();
 
  1202             epsilon = -hw_mmc.cycleMean();
 
  1203             cycle_cost = hw_mmc.cycleCost();
 
  1204             cycle_size = hw_mmc.cycleSize();
 
  1207           // Compute feasible potentials for the current epsilon
 
  1208           for (int i = 0; i != int(_cost_vec.size()); ++i) {
 
  1209             _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
 
  1211           BF bf(_sgr, _cost_map);
 
  1212           bf.distMap(_pi_map);
 
  1215           for (int u = 0; u != _res_node_num; ++u) {
 
  1216             pi[u] = static_cast<double>(_pi[u]) / cycle_size;
 
  1224   }; //class CycleCanceling
 
  1230 #endif //LEMON_CYCLE_CANCELING_H