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