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