lemon/cycle_canceling.h
author Alpar Juttner <alpar@cs.elte.hu>
Fri, 12 Feb 2010 22:17:20 +0100
changeset 829 7762cab7f372
parent 816 277ef0218f0c
child 830 75c97c3786d6
child 839 f3bc4e9b5f3a
permissions -rw-r--r--
Merge
     1 /* -*- C++ -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library
     4  *
     5  * Copyright (C) 2003-2008
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     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.
    12  *
    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
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_CYCLE_CANCELING_H
    20 #define LEMON_CYCLE_CANCELING_H
    21 
    22 /// \ingroup min_cost_flow_algs
    23 /// \file
    24 /// \brief Cycle-canceling algorithms for finding a minimum cost flow.
    25 
    26 #include <vector>
    27 #include <limits>
    28 
    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.h>
    38 
    39 namespace lemon {
    40 
    41   /// \addtogroup min_cost_flow_algs
    42   /// @{
    43 
    44   /// \brief Implementation of cycle-canceling algorithms for
    45   /// finding a \ref min_cost_flow "minimum cost flow".
    46   ///
    47   /// \ref CycleCanceling implements three different cycle-canceling
    48   /// algorithms for finding a \ref min_cost_flow "minimum cost flow"
    49   /// \ref amo93networkflows, \ref klein67primal,
    50   /// \ref goldberg89cyclecanceling.
    51   /// The most efficent one (both theoretically and practically)
    52   /// is the \ref CANCEL_AND_TIGHTEN "Cancel and Tighten" algorithm,
    53   /// thus it is the default method.
    54   /// It is strongly polynomial, but in practice, it is typically much
    55   /// slower than the scaling algorithms and NetworkSimplex.
    56   ///
    57   /// Most of the parameters of the problem (except for the digraph)
    58   /// can be given using separate functions, and the algorithm can be
    59   /// executed using the \ref run() function. If some parameters are not
    60   /// specified, then default values will be used.
    61   ///
    62   /// \tparam GR The digraph type the algorithm runs on.
    63   /// \tparam V The number type used for flow amounts, capacity bounds
    64   /// and supply values in the algorithm. By default, it is \c int.
    65   /// \tparam C The number type used for costs and potentials in the
    66   /// algorithm. By default, it is the same as \c V.
    67   ///
    68   /// \warning Both number types must be signed and all input data must
    69   /// be integer.
    70   /// \warning This algorithm does not support negative costs for such
    71   /// arcs that have infinite upper bound.
    72   ///
    73   /// \note For more information about the three available methods,
    74   /// see \ref Method.
    75 #ifdef DOXYGEN
    76   template <typename GR, typename V, typename C>
    77 #else
    78   template <typename GR, typename V = int, typename C = V>
    79 #endif
    80   class CycleCanceling
    81   {
    82   public:
    83 
    84     /// The type of the digraph
    85     typedef GR Digraph;
    86     /// The type of the flow amounts, capacity bounds and supply values
    87     typedef V Value;
    88     /// The type of the arc costs
    89     typedef C Cost;
    90 
    91   public:
    92 
    93     /// \brief Problem type constants for the \c run() function.
    94     ///
    95     /// Enum type containing the problem type constants that can be
    96     /// returned by the \ref run() function of the algorithm.
    97     enum ProblemType {
    98       /// The problem has no feasible solution (flow).
    99       INFEASIBLE,
   100       /// The problem has optimal solution (i.e. it is feasible and
   101       /// bounded), and the algorithm has found optimal flow and node
   102       /// potentials (primal and dual solutions).
   103       OPTIMAL,
   104       /// The digraph contains an arc of negative cost and infinite
   105       /// upper bound. It means that the objective function is unbounded
   106       /// on that arc, however, note that it could actually be bounded
   107       /// over the feasible flows, but this algroithm cannot handle
   108       /// these cases.
   109       UNBOUNDED
   110     };
   111 
   112     /// \brief Constants for selecting the used method.
   113     ///
   114     /// Enum type containing constants for selecting the used method
   115     /// for the \ref run() function.
   116     ///
   117     /// \ref CycleCanceling provides three different cycle-canceling
   118     /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel and Tighten"
   119     /// is used, which proved to be the most efficient and the most robust
   120     /// on various test inputs.
   121     /// However, the other methods can be selected using the \ref run()
   122     /// function with the proper parameter.
   123     enum Method {
   124       /// A simple cycle-canceling method, which uses the
   125       /// \ref BellmanFord "Bellman-Ford" algorithm with limited iteration
   126       /// number for detecting negative cycles in the residual network.
   127       SIMPLE_CYCLE_CANCELING,
   128       /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
   129       /// well-known strongly polynomial method
   130       /// \ref goldberg89cyclecanceling. It improves along a
   131       /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
   132       /// Its running time complexity is O(n<sup>2</sup>m<sup>3</sup>log(n)).
   133       MINIMUM_MEAN_CYCLE_CANCELING,
   134       /// The "Cancel And Tighten" algorithm, which can be viewed as an
   135       /// improved version of the previous method
   136       /// \ref goldberg89cyclecanceling.
   137       /// It is faster both in theory and in practice, its running time
   138       /// complexity is O(n<sup>2</sup>m<sup>2</sup>log(n)).
   139       CANCEL_AND_TIGHTEN
   140     };
   141 
   142   private:
   143 
   144     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
   145     
   146     typedef std::vector<int> IntVector;
   147     typedef std::vector<char> CharVector;
   148     typedef std::vector<double> DoubleVector;
   149     typedef std::vector<Value> ValueVector;
   150     typedef std::vector<Cost> CostVector;
   151 
   152   private:
   153   
   154     template <typename KT, typename VT>
   155     class StaticVectorMap {
   156     public:
   157       typedef KT Key;
   158       typedef VT Value;
   159       
   160       StaticVectorMap(std::vector<Value>& v) : _v(v) {}
   161       
   162       const Value& operator[](const Key& key) const {
   163         return _v[StaticDigraph::id(key)];
   164       }
   165 
   166       Value& operator[](const Key& key) {
   167         return _v[StaticDigraph::id(key)];
   168       }
   169       
   170       void set(const Key& key, const Value& val) {
   171         _v[StaticDigraph::id(key)] = val;
   172       }
   173 
   174     private:
   175       std::vector<Value>& _v;
   176     };
   177 
   178     typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
   179     typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
   180 
   181   private:
   182 
   183 
   184     // Data related to the underlying digraph
   185     const GR &_graph;
   186     int _node_num;
   187     int _arc_num;
   188     int _res_node_num;
   189     int _res_arc_num;
   190     int _root;
   191 
   192     // Parameters of the problem
   193     bool _have_lower;
   194     Value _sum_supply;
   195 
   196     // Data structures for storing the digraph
   197     IntNodeMap _node_id;
   198     IntArcMap _arc_idf;
   199     IntArcMap _arc_idb;
   200     IntVector _first_out;
   201     CharVector _forward;
   202     IntVector _source;
   203     IntVector _target;
   204     IntVector _reverse;
   205 
   206     // Node and arc data
   207     ValueVector _lower;
   208     ValueVector _upper;
   209     CostVector _cost;
   210     ValueVector _supply;
   211 
   212     ValueVector _res_cap;
   213     CostVector _pi;
   214 
   215     // Data for a StaticDigraph structure
   216     typedef std::pair<int, int> IntPair;
   217     StaticDigraph _sgr;
   218     std::vector<IntPair> _arc_vec;
   219     std::vector<Cost> _cost_vec;
   220     IntVector _id_vec;
   221     CostArcMap _cost_map;
   222     CostNodeMap _pi_map;
   223   
   224   public:
   225   
   226     /// \brief Constant for infinite upper bounds (capacities).
   227     ///
   228     /// Constant for infinite upper bounds (capacities).
   229     /// It is \c std::numeric_limits<Value>::infinity() if available,
   230     /// \c std::numeric_limits<Value>::max() otherwise.
   231     const Value INF;
   232 
   233   public:
   234 
   235     /// \brief Constructor.
   236     ///
   237     /// The constructor of the class.
   238     ///
   239     /// \param graph The digraph the algorithm runs on.
   240     CycleCanceling(const GR& graph) :
   241       _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
   242       _cost_map(_cost_vec), _pi_map(_pi),
   243       INF(std::numeric_limits<Value>::has_infinity ?
   244           std::numeric_limits<Value>::infinity() :
   245           std::numeric_limits<Value>::max())
   246     {
   247       // Check the number types
   248       LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
   249         "The flow type of CycleCanceling must be signed");
   250       LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
   251         "The cost type of CycleCanceling must be signed");
   252 
   253       // Resize vectors
   254       _node_num = countNodes(_graph);
   255       _arc_num = countArcs(_graph);
   256       _res_node_num = _node_num + 1;
   257       _res_arc_num = 2 * (_arc_num + _node_num);
   258       _root = _node_num;
   259 
   260       _first_out.resize(_res_node_num + 1);
   261       _forward.resize(_res_arc_num);
   262       _source.resize(_res_arc_num);
   263       _target.resize(_res_arc_num);
   264       _reverse.resize(_res_arc_num);
   265 
   266       _lower.resize(_res_arc_num);
   267       _upper.resize(_res_arc_num);
   268       _cost.resize(_res_arc_num);
   269       _supply.resize(_res_node_num);
   270       
   271       _res_cap.resize(_res_arc_num);
   272       _pi.resize(_res_node_num);
   273 
   274       _arc_vec.reserve(_res_arc_num);
   275       _cost_vec.reserve(_res_arc_num);
   276       _id_vec.reserve(_res_arc_num);
   277 
   278       // Copy the graph
   279       int i = 0, j = 0, k = 2 * _arc_num + _node_num;
   280       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   281         _node_id[n] = i;
   282       }
   283       i = 0;
   284       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   285         _first_out[i] = j;
   286         for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
   287           _arc_idf[a] = j;
   288           _forward[j] = true;
   289           _source[j] = i;
   290           _target[j] = _node_id[_graph.runningNode(a)];
   291         }
   292         for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
   293           _arc_idb[a] = j;
   294           _forward[j] = false;
   295           _source[j] = i;
   296           _target[j] = _node_id[_graph.runningNode(a)];
   297         }
   298         _forward[j] = false;
   299         _source[j] = i;
   300         _target[j] = _root;
   301         _reverse[j] = k;
   302         _forward[k] = true;
   303         _source[k] = _root;
   304         _target[k] = i;
   305         _reverse[k] = j;
   306         ++j; ++k;
   307       }
   308       _first_out[i] = j;
   309       _first_out[_res_node_num] = k;
   310       for (ArcIt a(_graph); a != INVALID; ++a) {
   311         int fi = _arc_idf[a];
   312         int bi = _arc_idb[a];
   313         _reverse[fi] = bi;
   314         _reverse[bi] = fi;
   315       }
   316       
   317       // Reset parameters
   318       reset();
   319     }
   320 
   321     /// \name Parameters
   322     /// The parameters of the algorithm can be specified using these
   323     /// functions.
   324 
   325     /// @{
   326 
   327     /// \brief Set the lower bounds on the arcs.
   328     ///
   329     /// This function sets the lower bounds on the arcs.
   330     /// If it is not used before calling \ref run(), the lower bounds
   331     /// will be set to zero on all arcs.
   332     ///
   333     /// \param map An arc map storing the lower bounds.
   334     /// Its \c Value type must be convertible to the \c Value type
   335     /// of the algorithm.
   336     ///
   337     /// \return <tt>(*this)</tt>
   338     template <typename LowerMap>
   339     CycleCanceling& lowerMap(const LowerMap& map) {
   340       _have_lower = true;
   341       for (ArcIt a(_graph); a != INVALID; ++a) {
   342         _lower[_arc_idf[a]] = map[a];
   343         _lower[_arc_idb[a]] = map[a];
   344       }
   345       return *this;
   346     }
   347 
   348     /// \brief Set the upper bounds (capacities) on the arcs.
   349     ///
   350     /// This function sets the upper bounds (capacities) on the arcs.
   351     /// If it is not used before calling \ref run(), the upper bounds
   352     /// will be set to \ref INF on all arcs (i.e. the flow value will be
   353     /// unbounded from above).
   354     ///
   355     /// \param map An arc map storing the upper bounds.
   356     /// Its \c Value type must be convertible to the \c Value type
   357     /// of the algorithm.
   358     ///
   359     /// \return <tt>(*this)</tt>
   360     template<typename UpperMap>
   361     CycleCanceling& upperMap(const UpperMap& map) {
   362       for (ArcIt a(_graph); a != INVALID; ++a) {
   363         _upper[_arc_idf[a]] = map[a];
   364       }
   365       return *this;
   366     }
   367 
   368     /// \brief Set the costs of the arcs.
   369     ///
   370     /// This function sets the costs of the arcs.
   371     /// If it is not used before calling \ref run(), the costs
   372     /// will be set to \c 1 on all arcs.
   373     ///
   374     /// \param map An arc map storing the costs.
   375     /// Its \c Value type must be convertible to the \c Cost type
   376     /// of the algorithm.
   377     ///
   378     /// \return <tt>(*this)</tt>
   379     template<typename CostMap>
   380     CycleCanceling& costMap(const CostMap& map) {
   381       for (ArcIt a(_graph); a != INVALID; ++a) {
   382         _cost[_arc_idf[a]] =  map[a];
   383         _cost[_arc_idb[a]] = -map[a];
   384       }
   385       return *this;
   386     }
   387 
   388     /// \brief Set the supply values of the nodes.
   389     ///
   390     /// This function sets the supply values of the nodes.
   391     /// If neither this function nor \ref stSupply() is used before
   392     /// calling \ref run(), the supply of each node will be set to zero.
   393     ///
   394     /// \param map A node map storing the supply values.
   395     /// Its \c Value type must be convertible to the \c Value type
   396     /// of the algorithm.
   397     ///
   398     /// \return <tt>(*this)</tt>
   399     template<typename SupplyMap>
   400     CycleCanceling& supplyMap(const SupplyMap& map) {
   401       for (NodeIt n(_graph); n != INVALID; ++n) {
   402         _supply[_node_id[n]] = map[n];
   403       }
   404       return *this;
   405     }
   406 
   407     /// \brief Set single source and target nodes and a supply value.
   408     ///
   409     /// This function sets a single source node and a single target node
   410     /// and the required flow value.
   411     /// If neither this function nor \ref supplyMap() is used before
   412     /// calling \ref run(), the supply of each node will be set to zero.
   413     ///
   414     /// Using this function has the same effect as using \ref supplyMap()
   415     /// with such a map in which \c k is assigned to \c s, \c -k is
   416     /// assigned to \c t and all other nodes have zero supply value.
   417     ///
   418     /// \param s The source node.
   419     /// \param t The target node.
   420     /// \param k The required amount of flow from node \c s to node \c t
   421     /// (i.e. the supply of \c s and the demand of \c t).
   422     ///
   423     /// \return <tt>(*this)</tt>
   424     CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
   425       for (int i = 0; i != _res_node_num; ++i) {
   426         _supply[i] = 0;
   427       }
   428       _supply[_node_id[s]] =  k;
   429       _supply[_node_id[t]] = -k;
   430       return *this;
   431     }
   432     
   433     /// @}
   434 
   435     /// \name Execution control
   436     /// The algorithm can be executed using \ref run().
   437 
   438     /// @{
   439 
   440     /// \brief Run the algorithm.
   441     ///
   442     /// This function runs the algorithm.
   443     /// The paramters can be specified using functions \ref lowerMap(),
   444     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
   445     /// For example,
   446     /// \code
   447     ///   CycleCanceling<ListDigraph> cc(graph);
   448     ///   cc.lowerMap(lower).upperMap(upper).costMap(cost)
   449     ///     .supplyMap(sup).run();
   450     /// \endcode
   451     ///
   452     /// This function can be called more than once. All the parameters
   453     /// that have been given are kept for the next call, unless
   454     /// \ref reset() is called, thus only the modified parameters
   455     /// have to be set again. See \ref reset() for examples.
   456     /// However, the underlying digraph must not be modified after this
   457     /// class have been constructed, since it copies and extends the graph.
   458     ///
   459     /// \param method The cycle-canceling method that will be used.
   460     /// For more information, see \ref Method.
   461     ///
   462     /// \return \c INFEASIBLE if no feasible flow exists,
   463     /// \n \c OPTIMAL if the problem has optimal solution
   464     /// (i.e. it is feasible and bounded), and the algorithm has found
   465     /// optimal flow and node potentials (primal and dual solutions),
   466     /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
   467     /// and infinite upper bound. It means that the objective function
   468     /// is unbounded on that arc, however, note that it could actually be
   469     /// bounded over the feasible flows, but this algroithm cannot handle
   470     /// these cases.
   471     ///
   472     /// \see ProblemType, Method
   473     ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
   474       ProblemType pt = init();
   475       if (pt != OPTIMAL) return pt;
   476       start(method);
   477       return OPTIMAL;
   478     }
   479 
   480     /// \brief Reset all the parameters that have been given before.
   481     ///
   482     /// This function resets all the paramaters that have been given
   483     /// before using functions \ref lowerMap(), \ref upperMap(),
   484     /// \ref costMap(), \ref supplyMap(), \ref stSupply().
   485     ///
   486     /// It is useful for multiple run() calls. If this function is not
   487     /// used, all the parameters given before are kept for the next
   488     /// \ref run() call.
   489     /// However, the underlying digraph must not be modified after this
   490     /// class have been constructed, since it copies and extends the graph.
   491     ///
   492     /// For example,
   493     /// \code
   494     ///   CycleCanceling<ListDigraph> cs(graph);
   495     ///
   496     ///   // First run
   497     ///   cc.lowerMap(lower).upperMap(upper).costMap(cost)
   498     ///     .supplyMap(sup).run();
   499     ///
   500     ///   // Run again with modified cost map (reset() is not called,
   501     ///   // so only the cost map have to be set again)
   502     ///   cost[e] += 100;
   503     ///   cc.costMap(cost).run();
   504     ///
   505     ///   // Run again from scratch using reset()
   506     ///   // (the lower bounds will be set to zero on all arcs)
   507     ///   cc.reset();
   508     ///   cc.upperMap(capacity).costMap(cost)
   509     ///     .supplyMap(sup).run();
   510     /// \endcode
   511     ///
   512     /// \return <tt>(*this)</tt>
   513     CycleCanceling& reset() {
   514       for (int i = 0; i != _res_node_num; ++i) {
   515         _supply[i] = 0;
   516       }
   517       int limit = _first_out[_root];
   518       for (int j = 0; j != limit; ++j) {
   519         _lower[j] = 0;
   520         _upper[j] = INF;
   521         _cost[j] = _forward[j] ? 1 : -1;
   522       }
   523       for (int j = limit; j != _res_arc_num; ++j) {
   524         _lower[j] = 0;
   525         _upper[j] = INF;
   526         _cost[j] = 0;
   527         _cost[_reverse[j]] = 0;
   528       }      
   529       _have_lower = false;
   530       return *this;
   531     }
   532 
   533     /// @}
   534 
   535     /// \name Query Functions
   536     /// The results of the algorithm can be obtained using these
   537     /// functions.\n
   538     /// The \ref run() function must be called before using them.
   539 
   540     /// @{
   541 
   542     /// \brief Return the total cost of the found flow.
   543     ///
   544     /// This function returns the total cost of the found flow.
   545     /// Its complexity is O(e).
   546     ///
   547     /// \note The return type of the function can be specified as a
   548     /// template parameter. For example,
   549     /// \code
   550     ///   cc.totalCost<double>();
   551     /// \endcode
   552     /// It is useful if the total cost cannot be stored in the \c Cost
   553     /// type of the algorithm, which is the default return type of the
   554     /// function.
   555     ///
   556     /// \pre \ref run() must be called before using this function.
   557     template <typename Number>
   558     Number totalCost() const {
   559       Number c = 0;
   560       for (ArcIt a(_graph); a != INVALID; ++a) {
   561         int i = _arc_idb[a];
   562         c += static_cast<Number>(_res_cap[i]) *
   563              (-static_cast<Number>(_cost[i]));
   564       }
   565       return c;
   566     }
   567 
   568 #ifndef DOXYGEN
   569     Cost totalCost() const {
   570       return totalCost<Cost>();
   571     }
   572 #endif
   573 
   574     /// \brief Return the flow on the given arc.
   575     ///
   576     /// This function returns the flow on the given arc.
   577     ///
   578     /// \pre \ref run() must be called before using this function.
   579     Value flow(const Arc& a) const {
   580       return _res_cap[_arc_idb[a]];
   581     }
   582 
   583     /// \brief Return the flow map (the primal solution).
   584     ///
   585     /// This function copies the flow value on each arc into the given
   586     /// map. The \c Value type of the algorithm must be convertible to
   587     /// the \c Value type of the map.
   588     ///
   589     /// \pre \ref run() must be called before using this function.
   590     template <typename FlowMap>
   591     void flowMap(FlowMap &map) const {
   592       for (ArcIt a(_graph); a != INVALID; ++a) {
   593         map.set(a, _res_cap[_arc_idb[a]]);
   594       }
   595     }
   596 
   597     /// \brief Return the potential (dual value) of the given node.
   598     ///
   599     /// This function returns the potential (dual value) of the
   600     /// given node.
   601     ///
   602     /// \pre \ref run() must be called before using this function.
   603     Cost potential(const Node& n) const {
   604       return static_cast<Cost>(_pi[_node_id[n]]);
   605     }
   606 
   607     /// \brief Return the potential map (the dual solution).
   608     ///
   609     /// This function copies the potential (dual value) of each node
   610     /// into the given map.
   611     /// The \c Cost type of the algorithm must be convertible to the
   612     /// \c Value type of the map.
   613     ///
   614     /// \pre \ref run() must be called before using this function.
   615     template <typename PotentialMap>
   616     void potentialMap(PotentialMap &map) const {
   617       for (NodeIt n(_graph); n != INVALID; ++n) {
   618         map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
   619       }
   620     }
   621 
   622     /// @}
   623 
   624   private:
   625 
   626     // Initialize the algorithm
   627     ProblemType init() {
   628       if (_res_node_num <= 1) return INFEASIBLE;
   629 
   630       // Check the sum of supply values
   631       _sum_supply = 0;
   632       for (int i = 0; i != _root; ++i) {
   633         _sum_supply += _supply[i];
   634       }
   635       if (_sum_supply > 0) return INFEASIBLE;
   636       
   637 
   638       // Initialize vectors
   639       for (int i = 0; i != _res_node_num; ++i) {
   640         _pi[i] = 0;
   641       }
   642       ValueVector excess(_supply);
   643       
   644       // Remove infinite upper bounds and check negative arcs
   645       const Value MAX = std::numeric_limits<Value>::max();
   646       int last_out;
   647       if (_have_lower) {
   648         for (int i = 0; i != _root; ++i) {
   649           last_out = _first_out[i+1];
   650           for (int j = _first_out[i]; j != last_out; ++j) {
   651             if (_forward[j]) {
   652               Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
   653               if (c >= MAX) return UNBOUNDED;
   654               excess[i] -= c;
   655               excess[_target[j]] += c;
   656             }
   657           }
   658         }
   659       } else {
   660         for (int i = 0; i != _root; ++i) {
   661           last_out = _first_out[i+1];
   662           for (int j = _first_out[i]; j != last_out; ++j) {
   663             if (_forward[j] && _cost[j] < 0) {
   664               Value c = _upper[j];
   665               if (c >= MAX) return UNBOUNDED;
   666               excess[i] -= c;
   667               excess[_target[j]] += c;
   668             }
   669           }
   670         }
   671       }
   672       Value ex, max_cap = 0;
   673       for (int i = 0; i != _res_node_num; ++i) {
   674         ex = excess[i];
   675         if (ex < 0) max_cap -= ex;
   676       }
   677       for (int j = 0; j != _res_arc_num; ++j) {
   678         if (_upper[j] >= MAX) _upper[j] = max_cap;
   679       }
   680 
   681       // Initialize maps for Circulation and remove non-zero lower bounds
   682       ConstMap<Arc, Value> low(0);
   683       typedef typename Digraph::template ArcMap<Value> ValueArcMap;
   684       typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
   685       ValueArcMap cap(_graph), flow(_graph);
   686       ValueNodeMap sup(_graph);
   687       for (NodeIt n(_graph); n != INVALID; ++n) {
   688         sup[n] = _supply[_node_id[n]];
   689       }
   690       if (_have_lower) {
   691         for (ArcIt a(_graph); a != INVALID; ++a) {
   692           int j = _arc_idf[a];
   693           Value c = _lower[j];
   694           cap[a] = _upper[j] - c;
   695           sup[_graph.source(a)] -= c;
   696           sup[_graph.target(a)] += c;
   697         }
   698       } else {
   699         for (ArcIt a(_graph); a != INVALID; ++a) {
   700           cap[a] = _upper[_arc_idf[a]];
   701         }
   702       }
   703 
   704       // Find a feasible flow using Circulation
   705       Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
   706         circ(_graph, low, cap, sup);
   707       if (!circ.flowMap(flow).run()) return INFEASIBLE;
   708 
   709       // Set residual capacities and handle GEQ supply type
   710       if (_sum_supply < 0) {
   711         for (ArcIt a(_graph); a != INVALID; ++a) {
   712           Value fa = flow[a];
   713           _res_cap[_arc_idf[a]] = cap[a] - fa;
   714           _res_cap[_arc_idb[a]] = fa;
   715           sup[_graph.source(a)] -= fa;
   716           sup[_graph.target(a)] += fa;
   717         }
   718         for (NodeIt n(_graph); n != INVALID; ++n) {
   719           excess[_node_id[n]] = sup[n];
   720         }
   721         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   722           int u = _target[a];
   723           int ra = _reverse[a];
   724           _res_cap[a] = -_sum_supply + 1;
   725           _res_cap[ra] = -excess[u];
   726           _cost[a] = 0;
   727           _cost[ra] = 0;
   728         }
   729       } else {
   730         for (ArcIt a(_graph); a != INVALID; ++a) {
   731           Value fa = flow[a];
   732           _res_cap[_arc_idf[a]] = cap[a] - fa;
   733           _res_cap[_arc_idb[a]] = fa;
   734         }
   735         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   736           int ra = _reverse[a];
   737           _res_cap[a] = 1;
   738           _res_cap[ra] = 0;
   739           _cost[a] = 0;
   740           _cost[ra] = 0;
   741         }
   742       }
   743       
   744       return OPTIMAL;
   745     }
   746     
   747     // Build a StaticDigraph structure containing the current
   748     // residual network
   749     void buildResidualNetwork() {
   750       _arc_vec.clear();
   751       _cost_vec.clear();
   752       _id_vec.clear();
   753       for (int j = 0; j != _res_arc_num; ++j) {
   754         if (_res_cap[j] > 0) {
   755           _arc_vec.push_back(IntPair(_source[j], _target[j]));
   756           _cost_vec.push_back(_cost[j]);
   757           _id_vec.push_back(j);
   758         }
   759       }
   760       _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
   761     }
   762 
   763     // Execute the algorithm and transform the results
   764     void start(Method method) {
   765       // Execute the algorithm
   766       switch (method) {
   767         case SIMPLE_CYCLE_CANCELING:
   768           startSimpleCycleCanceling();
   769           break;
   770         case MINIMUM_MEAN_CYCLE_CANCELING:
   771           startMinMeanCycleCanceling();
   772           break;
   773         case CANCEL_AND_TIGHTEN:
   774           startCancelAndTighten();
   775           break;
   776       }
   777 
   778       // Compute node potentials
   779       if (method != SIMPLE_CYCLE_CANCELING) {
   780         buildResidualNetwork();
   781         typename BellmanFord<StaticDigraph, CostArcMap>
   782           ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
   783         bf.distMap(_pi_map);
   784         bf.init(0);
   785         bf.start();
   786       }
   787 
   788       // Handle non-zero lower bounds
   789       if (_have_lower) {
   790         int limit = _first_out[_root];
   791         for (int j = 0; j != limit; ++j) {
   792           if (!_forward[j]) _res_cap[j] += _lower[j];
   793         }
   794       }
   795     }
   796 
   797     // Execute the "Simple Cycle Canceling" method
   798     void startSimpleCycleCanceling() {
   799       // Constants for computing the iteration limits
   800       const int BF_FIRST_LIMIT  = 2;
   801       const double BF_LIMIT_FACTOR = 1.5;
   802       
   803       typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
   804       typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
   805       typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
   806       typedef typename BellmanFord<ResDigraph, CostArcMap>
   807         ::template SetDistMap<CostNodeMap>
   808         ::template SetPredMap<PredMap>::Create BF;
   809       
   810       // Build the residual network
   811       _arc_vec.clear();
   812       _cost_vec.clear();
   813       for (int j = 0; j != _res_arc_num; ++j) {
   814         _arc_vec.push_back(IntPair(_source[j], _target[j]));
   815         _cost_vec.push_back(_cost[j]);
   816       }
   817       _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
   818 
   819       FilterMap filter_map(_res_cap);
   820       ResDigraph rgr(_sgr, filter_map);
   821       std::vector<int> cycle;
   822       std::vector<StaticDigraph::Arc> pred(_res_arc_num);
   823       PredMap pred_map(pred);
   824       BF bf(rgr, _cost_map);
   825       bf.distMap(_pi_map).predMap(pred_map);
   826 
   827       int length_bound = BF_FIRST_LIMIT;
   828       bool optimal = false;
   829       while (!optimal) {
   830         bf.init(0);
   831         int iter_num = 0;
   832         bool cycle_found = false;
   833         while (!cycle_found) {
   834           // Perform some iterations of the Bellman-Ford algorithm
   835           int curr_iter_num = iter_num + length_bound <= _node_num ?
   836             length_bound : _node_num - iter_num;
   837           iter_num += curr_iter_num;
   838           int real_iter_num = curr_iter_num;
   839           for (int i = 0; i < curr_iter_num; ++i) {
   840             if (bf.processNextWeakRound()) {
   841               real_iter_num = i;
   842               break;
   843             }
   844           }
   845           if (real_iter_num < curr_iter_num) {
   846             // Optimal flow is found
   847             optimal = true;
   848             break;
   849           } else {
   850             // Search for node disjoint negative cycles
   851             std::vector<int> state(_res_node_num, 0);
   852             int id = 0;
   853             for (int u = 0; u != _res_node_num; ++u) {
   854               if (state[u] != 0) continue;
   855               ++id;
   856               int v = u;
   857               for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
   858                    -1 : rgr.id(rgr.source(pred[v]))) {
   859                 state[v] = id;
   860               }
   861               if (v != -1 && state[v] == id) {
   862                 // A negative cycle is found
   863                 cycle_found = true;
   864                 cycle.clear();
   865                 StaticDigraph::Arc a = pred[v];
   866                 Value d, delta = _res_cap[rgr.id(a)];
   867                 cycle.push_back(rgr.id(a));
   868                 while (rgr.id(rgr.source(a)) != v) {
   869                   a = pred_map[rgr.source(a)];
   870                   d = _res_cap[rgr.id(a)];
   871                   if (d < delta) delta = d;
   872                   cycle.push_back(rgr.id(a));
   873                 }
   874 
   875                 // Augment along the cycle
   876                 for (int i = 0; i < int(cycle.size()); ++i) {
   877                   int j = cycle[i];
   878                   _res_cap[j] -= delta;
   879                   _res_cap[_reverse[j]] += delta;
   880                 }
   881               }
   882             }
   883           }
   884 
   885           // Increase iteration limit if no cycle is found
   886           if (!cycle_found) {
   887             length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
   888           }
   889         }
   890       }
   891     }
   892 
   893     // Execute the "Minimum Mean Cycle Canceling" method
   894     void startMinMeanCycleCanceling() {
   895       typedef SimplePath<StaticDigraph> SPath;
   896       typedef typename SPath::ArcIt SPathArcIt;
   897       typedef typename Howard<StaticDigraph, CostArcMap>
   898         ::template SetPath<SPath>::Create MMC;
   899       
   900       SPath cycle;
   901       MMC mmc(_sgr, _cost_map);
   902       mmc.cycle(cycle);
   903       buildResidualNetwork();
   904       while (mmc.findMinMean() && mmc.cycleLength() < 0) {
   905         // Find the cycle
   906         mmc.findCycle();
   907 
   908         // Compute delta value
   909         Value delta = INF;
   910         for (SPathArcIt a(cycle); a != INVALID; ++a) {
   911           Value d = _res_cap[_id_vec[_sgr.id(a)]];
   912           if (d < delta) delta = d;
   913         }
   914 
   915         // Augment along the cycle
   916         for (SPathArcIt a(cycle); a != INVALID; ++a) {
   917           int j = _id_vec[_sgr.id(a)];
   918           _res_cap[j] -= delta;
   919           _res_cap[_reverse[j]] += delta;
   920         }
   921 
   922         // Rebuild the residual network        
   923         buildResidualNetwork();
   924       }
   925     }
   926 
   927     // Execute the "Cancel And Tighten" method
   928     void startCancelAndTighten() {
   929       // Constants for the min mean cycle computations
   930       const double LIMIT_FACTOR = 1.0;
   931       const int MIN_LIMIT = 5;
   932 
   933       // Contruct auxiliary data vectors
   934       DoubleVector pi(_res_node_num, 0.0);
   935       IntVector level(_res_node_num);
   936       CharVector reached(_res_node_num);
   937       CharVector processed(_res_node_num);
   938       IntVector pred_node(_res_node_num);
   939       IntVector pred_arc(_res_node_num);
   940       std::vector<int> stack(_res_node_num);
   941       std::vector<int> proc_vector(_res_node_num);
   942 
   943       // Initialize epsilon
   944       double epsilon = 0;
   945       for (int a = 0; a != _res_arc_num; ++a) {
   946         if (_res_cap[a] > 0 && -_cost[a] > epsilon)
   947           epsilon = -_cost[a];
   948       }
   949 
   950       // Start phases
   951       Tolerance<double> tol;
   952       tol.epsilon(1e-6);
   953       int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
   954       if (limit < MIN_LIMIT) limit = MIN_LIMIT;
   955       int iter = limit;
   956       while (epsilon * _res_node_num >= 1) {
   957         // Find and cancel cycles in the admissible network using DFS
   958         for (int u = 0; u != _res_node_num; ++u) {
   959           reached[u] = false;
   960           processed[u] = false;
   961         }
   962         int stack_head = -1;
   963         int proc_head = -1;
   964         for (int start = 0; start != _res_node_num; ++start) {
   965           if (reached[start]) continue;
   966 
   967           // New start node
   968           reached[start] = true;
   969           pred_arc[start] = -1;
   970           pred_node[start] = -1;
   971 
   972           // Find the first admissible outgoing arc
   973           double p = pi[start];
   974           int a = _first_out[start];
   975           int last_out = _first_out[start+1];
   976           for (; a != last_out && (_res_cap[a] == 0 ||
   977                !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
   978           if (a == last_out) {
   979             processed[start] = true;
   980             proc_vector[++proc_head] = start;
   981             continue;
   982           }
   983           stack[++stack_head] = a;
   984 
   985           while (stack_head >= 0) {
   986             int sa = stack[stack_head];
   987             int u = _source[sa];
   988             int v = _target[sa];
   989 
   990             if (!reached[v]) {
   991               // A new node is reached
   992               reached[v] = true;
   993               pred_node[v] = u;
   994               pred_arc[v] = sa;
   995               p = pi[v];
   996               a = _first_out[v];
   997               last_out = _first_out[v+1];
   998               for (; a != last_out && (_res_cap[a] == 0 ||
   999                    !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1000               stack[++stack_head] = a == last_out ? -1 : a;
  1001             } else {
  1002               if (!processed[v]) {
  1003                 // A cycle is found
  1004                 int n, w = u;
  1005                 Value d, delta = _res_cap[sa];
  1006                 for (n = u; n != v; n = pred_node[n]) {
  1007                   d = _res_cap[pred_arc[n]];
  1008                   if (d <= delta) {
  1009                     delta = d;
  1010                     w = pred_node[n];
  1011                   }
  1012                 }
  1013 
  1014                 // Augment along the cycle
  1015                 _res_cap[sa] -= delta;
  1016                 _res_cap[_reverse[sa]] += delta;
  1017                 for (n = u; n != v; n = pred_node[n]) {
  1018                   int pa = pred_arc[n];
  1019                   _res_cap[pa] -= delta;
  1020                   _res_cap[_reverse[pa]] += delta;
  1021                 }
  1022                 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
  1023                   --stack_head;
  1024                   reached[n] = false;
  1025                 }
  1026                 u = w;
  1027               }
  1028               v = u;
  1029 
  1030               // Find the next admissible outgoing arc
  1031               p = pi[v];
  1032               a = stack[stack_head] + 1;
  1033               last_out = _first_out[v+1];
  1034               for (; a != last_out && (_res_cap[a] == 0 ||
  1035                    !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1036               stack[stack_head] = a == last_out ? -1 : a;
  1037             }
  1038 
  1039             while (stack_head >= 0 && stack[stack_head] == -1) {
  1040               processed[v] = true;
  1041               proc_vector[++proc_head] = v;
  1042               if (--stack_head >= 0) {
  1043                 // Find the next admissible outgoing arc
  1044                 v = _source[stack[stack_head]];
  1045                 p = pi[v];
  1046                 a = stack[stack_head] + 1;
  1047                 last_out = _first_out[v+1];
  1048                 for (; a != last_out && (_res_cap[a] == 0 ||
  1049                      !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1050                 stack[stack_head] = a == last_out ? -1 : a;
  1051               }
  1052             }
  1053           }
  1054         }
  1055 
  1056         // Tighten potentials and epsilon
  1057         if (--iter > 0) {
  1058           for (int u = 0; u != _res_node_num; ++u) {
  1059             level[u] = 0;
  1060           }
  1061           for (int i = proc_head; i > 0; --i) {
  1062             int u = proc_vector[i];
  1063             double p = pi[u];
  1064             int l = level[u] + 1;
  1065             int last_out = _first_out[u+1];
  1066             for (int a = _first_out[u]; a != last_out; ++a) {
  1067               int v = _target[a];
  1068               if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
  1069                   l > level[v]) level[v] = l;
  1070             }
  1071           }
  1072 
  1073           // Modify potentials
  1074           double q = std::numeric_limits<double>::max();
  1075           for (int u = 0; u != _res_node_num; ++u) {
  1076             int lu = level[u];
  1077             double p, pu = pi[u];
  1078             int last_out = _first_out[u+1];
  1079             for (int a = _first_out[u]; a != last_out; ++a) {
  1080               if (_res_cap[a] == 0) continue;
  1081               int v = _target[a];
  1082               int ld = lu - level[v];
  1083               if (ld > 0) {
  1084                 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
  1085                 if (p < q) q = p;
  1086               }
  1087             }
  1088           }
  1089           for (int u = 0; u != _res_node_num; ++u) {
  1090             pi[u] -= q * level[u];
  1091           }
  1092 
  1093           // Modify epsilon
  1094           epsilon = 0;
  1095           for (int u = 0; u != _res_node_num; ++u) {
  1096             double curr, pu = pi[u];
  1097             int last_out = _first_out[u+1];
  1098             for (int a = _first_out[u]; a != last_out; ++a) {
  1099               if (_res_cap[a] == 0) continue;
  1100               curr = _cost[a] + pu - pi[_target[a]];
  1101               if (-curr > epsilon) epsilon = -curr;
  1102             }
  1103           }
  1104         } else {
  1105           typedef Howard<StaticDigraph, CostArcMap> MMC;
  1106           typedef typename BellmanFord<StaticDigraph, CostArcMap>
  1107             ::template SetDistMap<CostNodeMap>::Create BF;
  1108 
  1109           // Set epsilon to the minimum cycle mean
  1110           buildResidualNetwork();
  1111           MMC mmc(_sgr, _cost_map);
  1112           mmc.findMinMean();
  1113           epsilon = -mmc.cycleMean();
  1114           Cost cycle_cost = mmc.cycleLength();
  1115           int cycle_size = mmc.cycleArcNum();
  1116           
  1117           // Compute feasible potentials for the current epsilon
  1118           for (int i = 0; i != int(_cost_vec.size()); ++i) {
  1119             _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
  1120           }
  1121           BF bf(_sgr, _cost_map);
  1122           bf.distMap(_pi_map);
  1123           bf.init(0);
  1124           bf.start();
  1125           for (int u = 0; u != _res_node_num; ++u) {
  1126             pi[u] = static_cast<double>(_pi[u]) / cycle_size;
  1127           }
  1128         
  1129           iter = limit;
  1130         }
  1131       }
  1132     }
  1133 
  1134   }; //class CycleCanceling
  1135 
  1136   ///@}
  1137 
  1138 } //namespace lemon
  1139 
  1140 #endif //LEMON_CYCLE_CANCELING_H