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