lemon/cycle_canceling.h
author Alpar Juttner <alpar@cs.elte.hu>
Wed, 17 Oct 2018 18:56:32 +0200
changeset 1169 2e0c2c25d63e
parent 1092 dceba191c00d
parent 1110 c0c2f5c87aa6
permissions -rw-r--r--
Merge #1.3 related bugfix heads
     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-2013
     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 #include <lemon/hartmann_orlin_mmc.h>
    39 
    40 namespace lemon {
    41 
    42   /// \addtogroup min_cost_flow_algs
    43   /// @{
    44 
    45   /// \brief Implementation of cycle-canceling algorithms for
    46   /// finding a \ref min_cost_flow "minimum cost flow".
    47   ///
    48   /// \ref CycleCanceling implements three different cycle-canceling
    49   /// algorithms for finding a \ref min_cost_flow "minimum cost flow"
    50   /// \cite amo93networkflows, \cite klein67primal,
    51   /// \cite goldberg89cyclecanceling.
    52   /// The most efficent one is the \ref CANCEL_AND_TIGHTEN
    53   /// "Cancel-and-Tighten" algorithm, thus it is the default method.
    54   /// It runs in strongly polynomial time \f$O(n^2 m^2 \log n)\f$,
    55   /// but in practice, it is typically orders of magnitude slower than
    56   /// the scaling algorithms and \ref NetworkSimplex.
    57   /// (For more information, see \ref min_cost_flow_algs "the module page".)
    58   ///
    59   /// Most of the parameters of the problem (except for the digraph)
    60   /// can be given using separate functions, and the algorithm can be
    61   /// executed using the \ref run() function. If some parameters are not
    62   /// specified, then default values will be used.
    63   ///
    64   /// \tparam GR The digraph type the algorithm runs on.
    65   /// \tparam V The number type used for flow amounts, capacity bounds
    66   /// and supply values in the algorithm. By default, it is \c int.
    67   /// \tparam C The number type used for costs and potentials in the
    68   /// algorithm. By default, it is the same as \c V.
    69   ///
    70   /// \warning Both \c V and \c C must be signed number types.
    71   /// \warning All input data (capacities, supply values, and costs) must
    72   /// be integer.
    73   /// \warning This algorithm does not support negative costs for
    74   /// arcs having infinite upper bound.
    75   ///
    76   /// \note For more information about the three available methods,
    77   /// see \ref Method.
    78 #ifdef DOXYGEN
    79   template <typename GR, typename V, typename C>
    80 #else
    81   template <typename GR, typename V = int, typename C = V>
    82 #endif
    83   class CycleCanceling
    84   {
    85   public:
    86 
    87     /// The type of the digraph
    88     typedef GR Digraph;
    89     /// The type of the flow amounts, capacity bounds and supply values
    90     typedef V Value;
    91     /// The type of the arc costs
    92     typedef C Cost;
    93 
    94   public:
    95 
    96     /// \brief Problem type constants for the \c run() function.
    97     ///
    98     /// Enum type containing the problem type constants that can be
    99     /// returned by the \ref run() function of the algorithm.
   100     enum ProblemType {
   101       /// The problem has no feasible solution (flow).
   102       INFEASIBLE,
   103       /// The problem has optimal solution (i.e. it is feasible and
   104       /// bounded), and the algorithm has found optimal flow and node
   105       /// potentials (primal and dual solutions).
   106       OPTIMAL,
   107       /// The digraph contains an arc of negative cost and infinite
   108       /// upper bound. It means that the objective function is unbounded
   109       /// on that arc, however, note that it could actually be bounded
   110       /// over the feasible flows, but this algroithm cannot handle
   111       /// these cases.
   112       UNBOUNDED
   113     };
   114 
   115     /// \brief Constants for selecting the used method.
   116     ///
   117     /// Enum type containing constants for selecting the used method
   118     /// for the \ref run() function.
   119     ///
   120     /// \ref CycleCanceling provides three different cycle-canceling
   121     /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel-and-Tighten"
   122     /// is used, which is by far the most efficient and the most robust.
   123     /// However, the other methods can be selected using the \ref run()
   124     /// function with the proper parameter.
   125     enum Method {
   126       /// A simple cycle-canceling method, which uses the
   127       /// \ref BellmanFord "Bellman-Ford" algorithm for detecting negative
   128       /// cycles in the residual network.
   129       /// The number of Bellman-Ford iterations is bounded by a successively
   130       /// increased limit.
   131       SIMPLE_CYCLE_CANCELING,
   132       /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
   133       /// well-known strongly polynomial method
   134       /// \cite goldberg89cyclecanceling. It improves along a
   135       /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
   136       /// Its running time complexity is \f$O(n^2 m^3 \log n)\f$.
   137       MINIMUM_MEAN_CYCLE_CANCELING,
   138       /// The "Cancel-and-Tighten" algorithm, which can be viewed as an
   139       /// improved version of the previous method
   140       /// \cite goldberg89cyclecanceling.
   141       /// It is faster both in theory and in practice, its running time
   142       /// complexity is \f$O(n^2 m^2 \log n)\f$.
   143       CANCEL_AND_TIGHTEN
   144     };
   145 
   146   private:
   147 
   148     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
   149 
   150     typedef std::vector<int> IntVector;
   151     typedef std::vector<double> DoubleVector;
   152     typedef std::vector<Value> ValueVector;
   153     typedef std::vector<Cost> CostVector;
   154     typedef std::vector<char> BoolVector;
   155     // Note: vector<char> is used instead of vector<bool> for efficiency reasons
   156 
   157   private:
   158 
   159     template <typename KT, typename VT>
   160     class StaticVectorMap {
   161     public:
   162       typedef KT Key;
   163       typedef VT Value;
   164 
   165       StaticVectorMap(std::vector<Value>& v) : _v(v) {}
   166 
   167       const Value& operator[](const Key& key) const {
   168         return _v[StaticDigraph::id(key)];
   169       }
   170 
   171       Value& operator[](const Key& key) {
   172         return _v[StaticDigraph::id(key)];
   173       }
   174 
   175       void set(const Key& key, const Value& val) {
   176         _v[StaticDigraph::id(key)] = val;
   177       }
   178 
   179     private:
   180       std::vector<Value>& _v;
   181     };
   182 
   183     typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
   184     typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
   185 
   186   private:
   187 
   188 
   189     // Data related to the underlying digraph
   190     const GR &_graph;
   191     int _node_num;
   192     int _arc_num;
   193     int _res_node_num;
   194     int _res_arc_num;
   195     int _root;
   196 
   197     // Parameters of the problem
   198     bool _has_lower;
   199     Value _sum_supply;
   200 
   201     // Data structures for storing the digraph
   202     IntNodeMap _node_id;
   203     IntArcMap _arc_idf;
   204     IntArcMap _arc_idb;
   205     IntVector _first_out;
   206     BoolVector _forward;
   207     IntVector _source;
   208     IntVector _target;
   209     IntVector _reverse;
   210 
   211     // Node and arc data
   212     ValueVector _lower;
   213     ValueVector _upper;
   214     CostVector _cost;
   215     ValueVector _supply;
   216 
   217     ValueVector _res_cap;
   218     CostVector _pi;
   219 
   220     // Data for a StaticDigraph structure
   221     typedef std::pair<int, int> IntPair;
   222     StaticDigraph _sgr;
   223     std::vector<IntPair> _arc_vec;
   224     std::vector<Cost> _cost_vec;
   225     IntVector _id_vec;
   226     CostArcMap _cost_map;
   227     CostNodeMap _pi_map;
   228 
   229   public:
   230 
   231     /// \brief Constant for infinite upper bounds (capacities).
   232     ///
   233     /// Constant for infinite upper bounds (capacities).
   234     /// It is \c std::numeric_limits<Value>::infinity() if available,
   235     /// \c std::numeric_limits<Value>::max() otherwise.
   236     const Value INF;
   237 
   238   public:
   239 
   240     /// \brief Constructor.
   241     ///
   242     /// The constructor of the class.
   243     ///
   244     /// \param graph The digraph the algorithm runs on.
   245     CycleCanceling(const GR& graph) :
   246       _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
   247       _cost_map(_cost_vec), _pi_map(_pi),
   248       INF(std::numeric_limits<Value>::has_infinity ?
   249           std::numeric_limits<Value>::infinity() :
   250           std::numeric_limits<Value>::max())
   251     {
   252       // Check the number types
   253       LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
   254         "The flow type of CycleCanceling must be signed");
   255       LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
   256         "The cost type of CycleCanceling must be signed");
   257 
   258       // Reset data structures
   259       reset();
   260     }
   261 
   262     /// \name Parameters
   263     /// The parameters of the algorithm can be specified using these
   264     /// functions.
   265 
   266     /// @{
   267 
   268     /// \brief Set the lower bounds on the arcs.
   269     ///
   270     /// This function sets the lower bounds on the arcs.
   271     /// If it is not used before calling \ref run(), the lower bounds
   272     /// will be set to zero on all arcs.
   273     ///
   274     /// \param map An arc map storing the lower bounds.
   275     /// Its \c Value type must be convertible to the \c Value type
   276     /// of the algorithm.
   277     ///
   278     /// \return <tt>(*this)</tt>
   279     template <typename LowerMap>
   280     CycleCanceling& lowerMap(const LowerMap& map) {
   281       _has_lower = true;
   282       for (ArcIt a(_graph); a != INVALID; ++a) {
   283         _lower[_arc_idf[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       _has_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(m).
   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       // Check lower and upper bounds
   673       LEMON_DEBUG(checkBoundMaps(),
   674           "Upper bounds must be greater or equal to the lower bounds");
   675 
   676 
   677       // Initialize vectors
   678       for (int i = 0; i != _res_node_num; ++i) {
   679         _pi[i] = 0;
   680       }
   681       ValueVector excess(_supply);
   682 
   683       // Remove infinite upper bounds and check negative arcs
   684       const Value MAX = std::numeric_limits<Value>::max();
   685       int last_out;
   686       if (_has_lower) {
   687         for (int i = 0; i != _root; ++i) {
   688           last_out = _first_out[i+1];
   689           for (int j = _first_out[i]; j != last_out; ++j) {
   690             if (_forward[j]) {
   691               Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
   692               if (c >= MAX) return UNBOUNDED;
   693               excess[i] -= c;
   694               excess[_target[j]] += c;
   695             }
   696           }
   697         }
   698       } else {
   699         for (int i = 0; i != _root; ++i) {
   700           last_out = _first_out[i+1];
   701           for (int j = _first_out[i]; j != last_out; ++j) {
   702             if (_forward[j] && _cost[j] < 0) {
   703               Value c = _upper[j];
   704               if (c >= MAX) return UNBOUNDED;
   705               excess[i] -= c;
   706               excess[_target[j]] += c;
   707             }
   708           }
   709         }
   710       }
   711       Value ex, max_cap = 0;
   712       for (int i = 0; i != _res_node_num; ++i) {
   713         ex = excess[i];
   714         if (ex < 0) max_cap -= ex;
   715       }
   716       for (int j = 0; j != _res_arc_num; ++j) {
   717         if (_upper[j] >= MAX) _upper[j] = max_cap;
   718       }
   719 
   720       // Initialize maps for Circulation and remove non-zero lower bounds
   721       ConstMap<Arc, Value> low(0);
   722       typedef typename Digraph::template ArcMap<Value> ValueArcMap;
   723       typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
   724       ValueArcMap cap(_graph), flow(_graph);
   725       ValueNodeMap sup(_graph);
   726       for (NodeIt n(_graph); n != INVALID; ++n) {
   727         sup[n] = _supply[_node_id[n]];
   728       }
   729       if (_has_lower) {
   730         for (ArcIt a(_graph); a != INVALID; ++a) {
   731           int j = _arc_idf[a];
   732           Value c = _lower[j];
   733           cap[a] = _upper[j] - c;
   734           sup[_graph.source(a)] -= c;
   735           sup[_graph.target(a)] += c;
   736         }
   737       } else {
   738         for (ArcIt a(_graph); a != INVALID; ++a) {
   739           cap[a] = _upper[_arc_idf[a]];
   740         }
   741       }
   742 
   743       // Find a feasible flow using Circulation
   744       Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
   745         circ(_graph, low, cap, sup);
   746       if (!circ.flowMap(flow).run()) return INFEASIBLE;
   747 
   748       // Set residual capacities and handle GEQ supply type
   749       if (_sum_supply < 0) {
   750         for (ArcIt a(_graph); a != INVALID; ++a) {
   751           Value fa = flow[a];
   752           _res_cap[_arc_idf[a]] = cap[a] - fa;
   753           _res_cap[_arc_idb[a]] = fa;
   754           sup[_graph.source(a)] -= fa;
   755           sup[_graph.target(a)] += fa;
   756         }
   757         for (NodeIt n(_graph); n != INVALID; ++n) {
   758           excess[_node_id[n]] = sup[n];
   759         }
   760         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   761           int u = _target[a];
   762           int ra = _reverse[a];
   763           _res_cap[a] = -_sum_supply + 1;
   764           _res_cap[ra] = -excess[u];
   765           _cost[a] = 0;
   766           _cost[ra] = 0;
   767         }
   768       } else {
   769         for (ArcIt a(_graph); a != INVALID; ++a) {
   770           Value fa = flow[a];
   771           _res_cap[_arc_idf[a]] = cap[a] - fa;
   772           _res_cap[_arc_idb[a]] = fa;
   773         }
   774         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   775           int ra = _reverse[a];
   776           _res_cap[a] = 1;
   777           _res_cap[ra] = 0;
   778           _cost[a] = 0;
   779           _cost[ra] = 0;
   780         }
   781       }
   782 
   783       return OPTIMAL;
   784     }
   785 
   786     // Check if the upper bound is greater than or equal to the lower bound
   787     // on each forward arc.
   788     bool checkBoundMaps() {
   789       for (int j = 0; j != _res_arc_num; ++j) {
   790         if (_forward[j] && _upper[j] < _lower[j]) return false;
   791       }
   792       return true;
   793     }
   794 
   795     // Build a StaticDigraph structure containing the current
   796     // residual network
   797     void buildResidualNetwork() {
   798       _arc_vec.clear();
   799       _cost_vec.clear();
   800       _id_vec.clear();
   801       for (int j = 0; j != _res_arc_num; ++j) {
   802         if (_res_cap[j] > 0) {
   803           _arc_vec.push_back(IntPair(_source[j], _target[j]));
   804           _cost_vec.push_back(_cost[j]);
   805           _id_vec.push_back(j);
   806         }
   807       }
   808       _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
   809     }
   810 
   811     // Execute the algorithm and transform the results
   812     void start(Method method) {
   813       // Execute the algorithm
   814       switch (method) {
   815         case SIMPLE_CYCLE_CANCELING:
   816           startSimpleCycleCanceling();
   817           break;
   818         case MINIMUM_MEAN_CYCLE_CANCELING:
   819           startMinMeanCycleCanceling();
   820           break;
   821         case CANCEL_AND_TIGHTEN:
   822           startCancelAndTighten();
   823           break;
   824       }
   825 
   826       // Compute node potentials
   827       if (method != SIMPLE_CYCLE_CANCELING) {
   828         buildResidualNetwork();
   829         typename BellmanFord<StaticDigraph, CostArcMap>
   830           ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
   831         bf.distMap(_pi_map);
   832         bf.init(0);
   833         bf.start();
   834       }
   835 
   836       // Handle non-zero lower bounds
   837       if (_has_lower) {
   838         int limit = _first_out[_root];
   839         for (int j = 0; j != limit; ++j) {
   840           if (_forward[j]) _res_cap[_reverse[j]] += _lower[j];
   841         }
   842       }
   843     }
   844 
   845     // Execute the "Simple Cycle Canceling" method
   846     void startSimpleCycleCanceling() {
   847       // Constants for computing the iteration limits
   848       const int BF_FIRST_LIMIT  = 2;
   849       const double BF_LIMIT_FACTOR = 1.5;
   850 
   851       typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
   852       typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
   853       typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
   854       typedef typename BellmanFord<ResDigraph, CostArcMap>
   855         ::template SetDistMap<CostNodeMap>
   856         ::template SetPredMap<PredMap>::Create BF;
   857 
   858       // Build the residual network
   859       _arc_vec.clear();
   860       _cost_vec.clear();
   861       for (int j = 0; j != _res_arc_num; ++j) {
   862         _arc_vec.push_back(IntPair(_source[j], _target[j]));
   863         _cost_vec.push_back(_cost[j]);
   864       }
   865       _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
   866 
   867       FilterMap filter_map(_res_cap);
   868       ResDigraph rgr(_sgr, filter_map);
   869       std::vector<int> cycle;
   870       std::vector<StaticDigraph::Arc> pred(_res_arc_num);
   871       PredMap pred_map(pred);
   872       BF bf(rgr, _cost_map);
   873       bf.distMap(_pi_map).predMap(pred_map);
   874 
   875       int length_bound = BF_FIRST_LIMIT;
   876       bool optimal = false;
   877       while (!optimal) {
   878         bf.init(0);
   879         int iter_num = 0;
   880         bool cycle_found = false;
   881         while (!cycle_found) {
   882           // Perform some iterations of the Bellman-Ford algorithm
   883           int curr_iter_num = iter_num + length_bound <= _node_num ?
   884             length_bound : _node_num - iter_num;
   885           iter_num += curr_iter_num;
   886           int real_iter_num = curr_iter_num;
   887           for (int i = 0; i < curr_iter_num; ++i) {
   888             if (bf.processNextWeakRound()) {
   889               real_iter_num = i;
   890               break;
   891             }
   892           }
   893           if (real_iter_num < curr_iter_num) {
   894             // Optimal flow is found
   895             optimal = true;
   896             break;
   897           } else {
   898             // Search for node disjoint negative cycles
   899             std::vector<int> state(_res_node_num, 0);
   900             int id = 0;
   901             for (int u = 0; u != _res_node_num; ++u) {
   902               if (state[u] != 0) continue;
   903               ++id;
   904               int v = u;
   905               for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
   906                    -1 : rgr.id(rgr.source(pred[v]))) {
   907                 state[v] = id;
   908               }
   909               if (v != -1 && state[v] == id) {
   910                 // A negative cycle is found
   911                 cycle_found = true;
   912                 cycle.clear();
   913                 StaticDigraph::Arc a = pred[v];
   914                 Value d, delta = _res_cap[rgr.id(a)];
   915                 cycle.push_back(rgr.id(a));
   916                 while (rgr.id(rgr.source(a)) != v) {
   917                   a = pred_map[rgr.source(a)];
   918                   d = _res_cap[rgr.id(a)];
   919                   if (d < delta) delta = d;
   920                   cycle.push_back(rgr.id(a));
   921                 }
   922 
   923                 // Augment along the cycle
   924                 for (int i = 0; i < int(cycle.size()); ++i) {
   925                   int j = cycle[i];
   926                   _res_cap[j] -= delta;
   927                   _res_cap[_reverse[j]] += delta;
   928                 }
   929               }
   930             }
   931           }
   932 
   933           // Increase iteration limit if no cycle is found
   934           if (!cycle_found) {
   935             length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
   936           }
   937         }
   938       }
   939     }
   940 
   941     // Execute the "Minimum Mean Cycle Canceling" method
   942     void startMinMeanCycleCanceling() {
   943       typedef Path<StaticDigraph> SPath;
   944       typedef typename SPath::ArcIt SPathArcIt;
   945       typedef typename HowardMmc<StaticDigraph, CostArcMap>
   946         ::template SetPath<SPath>::Create HwMmc;
   947       typedef typename HartmannOrlinMmc<StaticDigraph, CostArcMap>
   948         ::template SetPath<SPath>::Create HoMmc;
   949 
   950       const double HW_ITER_LIMIT_FACTOR = 1.0;
   951       const int HW_ITER_LIMIT_MIN_VALUE = 5;
   952 
   953       const int hw_iter_limit =
   954           std::max(static_cast<int>(HW_ITER_LIMIT_FACTOR * _node_num),
   955                    HW_ITER_LIMIT_MIN_VALUE);
   956 
   957       SPath cycle;
   958       HwMmc hw_mmc(_sgr, _cost_map);
   959       hw_mmc.cycle(cycle);
   960       buildResidualNetwork();
   961       while (true) {
   962 
   963         typename HwMmc::TerminationCause hw_tc =
   964             hw_mmc.findCycleMean(hw_iter_limit);
   965         if (hw_tc == HwMmc::ITERATION_LIMIT) {
   966           // Howard's algorithm reached the iteration limit, start a
   967           // strongly polynomial algorithm instead
   968           HoMmc ho_mmc(_sgr, _cost_map);
   969           ho_mmc.cycle(cycle);
   970           // Find a minimum mean cycle (Hartmann-Orlin algorithm)
   971           if (!(ho_mmc.findCycleMean() && ho_mmc.cycleCost() < 0)) break;
   972           ho_mmc.findCycle();
   973         } else {
   974           // Find a minimum mean cycle (Howard algorithm)
   975           if (!(hw_tc == HwMmc::OPTIMAL && hw_mmc.cycleCost() < 0)) break;
   976           hw_mmc.findCycle();
   977         }
   978 
   979         // Compute delta value
   980         Value delta = INF;
   981         for (SPathArcIt a(cycle); a != INVALID; ++a) {
   982           Value d = _res_cap[_id_vec[_sgr.id(a)]];
   983           if (d < delta) delta = d;
   984         }
   985 
   986         // Augment along the cycle
   987         for (SPathArcIt a(cycle); a != INVALID; ++a) {
   988           int j = _id_vec[_sgr.id(a)];
   989           _res_cap[j] -= delta;
   990           _res_cap[_reverse[j]] += delta;
   991         }
   992 
   993         // Rebuild the residual network
   994         buildResidualNetwork();
   995       }
   996     }
   997 
   998     // Execute the "Cancel-and-Tighten" method
   999     void startCancelAndTighten() {
  1000       // Constants for the min mean cycle computations
  1001       const double LIMIT_FACTOR = 1.0;
  1002       const int MIN_LIMIT = 5;
  1003       const double HW_ITER_LIMIT_FACTOR = 1.0;
  1004       const int HW_ITER_LIMIT_MIN_VALUE = 5;
  1005 
  1006       const int hw_iter_limit =
  1007           std::max(static_cast<int>(HW_ITER_LIMIT_FACTOR * _node_num),
  1008                    HW_ITER_LIMIT_MIN_VALUE);
  1009 
  1010       // Contruct auxiliary data vectors
  1011       DoubleVector pi(_res_node_num, 0.0);
  1012       IntVector level(_res_node_num);
  1013       BoolVector reached(_res_node_num);
  1014       BoolVector processed(_res_node_num);
  1015       IntVector pred_node(_res_node_num);
  1016       IntVector pred_arc(_res_node_num);
  1017       std::vector<int> stack(_res_node_num);
  1018       std::vector<int> proc_vector(_res_node_num);
  1019 
  1020       // Initialize epsilon
  1021       double epsilon = 0;
  1022       for (int a = 0; a != _res_arc_num; ++a) {
  1023         if (_res_cap[a] > 0 && -_cost[a] > epsilon)
  1024           epsilon = -_cost[a];
  1025       }
  1026 
  1027       // Start phases
  1028       Tolerance<double> tol;
  1029       tol.epsilon(1e-6);
  1030       int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
  1031       if (limit < MIN_LIMIT) limit = MIN_LIMIT;
  1032       int iter = limit;
  1033       while (epsilon * _res_node_num >= 1) {
  1034         // Find and cancel cycles in the admissible network using DFS
  1035         for (int u = 0; u != _res_node_num; ++u) {
  1036           reached[u] = false;
  1037           processed[u] = false;
  1038         }
  1039         int stack_head = -1;
  1040         int proc_head = -1;
  1041         for (int start = 0; start != _res_node_num; ++start) {
  1042           if (reached[start]) continue;
  1043 
  1044           // New start node
  1045           reached[start] = true;
  1046           pred_arc[start] = -1;
  1047           pred_node[start] = -1;
  1048 
  1049           // Find the first admissible outgoing arc
  1050           double p = pi[start];
  1051           int a = _first_out[start];
  1052           int last_out = _first_out[start+1];
  1053           for (; a != last_out && (_res_cap[a] == 0 ||
  1054                !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1055           if (a == last_out) {
  1056             processed[start] = true;
  1057             proc_vector[++proc_head] = start;
  1058             continue;
  1059           }
  1060           stack[++stack_head] = a;
  1061 
  1062           while (stack_head >= 0) {
  1063             int sa = stack[stack_head];
  1064             int u = _source[sa];
  1065             int v = _target[sa];
  1066 
  1067             if (!reached[v]) {
  1068               // A new node is reached
  1069               reached[v] = true;
  1070               pred_node[v] = u;
  1071               pred_arc[v] = sa;
  1072               p = pi[v];
  1073               a = _first_out[v];
  1074               last_out = _first_out[v+1];
  1075               for (; a != last_out && (_res_cap[a] == 0 ||
  1076                    !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1077               stack[++stack_head] = a == last_out ? -1 : a;
  1078             } else {
  1079               if (!processed[v]) {
  1080                 // A cycle is found
  1081                 int n, w = u;
  1082                 Value d, delta = _res_cap[sa];
  1083                 for (n = u; n != v; n = pred_node[n]) {
  1084                   d = _res_cap[pred_arc[n]];
  1085                   if (d <= delta) {
  1086                     delta = d;
  1087                     w = pred_node[n];
  1088                   }
  1089                 }
  1090 
  1091                 // Augment along the cycle
  1092                 _res_cap[sa] -= delta;
  1093                 _res_cap[_reverse[sa]] += delta;
  1094                 for (n = u; n != v; n = pred_node[n]) {
  1095                   int pa = pred_arc[n];
  1096                   _res_cap[pa] -= delta;
  1097                   _res_cap[_reverse[pa]] += delta;
  1098                 }
  1099                 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
  1100                   --stack_head;
  1101                   reached[n] = false;
  1102                 }
  1103                 u = w;
  1104               }
  1105               v = u;
  1106 
  1107               // Find the next admissible outgoing arc
  1108               p = pi[v];
  1109               a = stack[stack_head] + 1;
  1110               last_out = _first_out[v+1];
  1111               for (; a != last_out && (_res_cap[a] == 0 ||
  1112                    !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1113               stack[stack_head] = a == last_out ? -1 : a;
  1114             }
  1115 
  1116             while (stack_head >= 0 && stack[stack_head] == -1) {
  1117               processed[v] = true;
  1118               proc_vector[++proc_head] = v;
  1119               if (--stack_head >= 0) {
  1120                 // Find the next admissible outgoing arc
  1121                 v = _source[stack[stack_head]];
  1122                 p = pi[v];
  1123                 a = stack[stack_head] + 1;
  1124                 last_out = _first_out[v+1];
  1125                 for (; a != last_out && (_res_cap[a] == 0 ||
  1126                      !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
  1127                 stack[stack_head] = a == last_out ? -1 : a;
  1128               }
  1129             }
  1130           }
  1131         }
  1132 
  1133         // Tighten potentials and epsilon
  1134         if (--iter > 0) {
  1135           for (int u = 0; u != _res_node_num; ++u) {
  1136             level[u] = 0;
  1137           }
  1138           for (int i = proc_head; i > 0; --i) {
  1139             int u = proc_vector[i];
  1140             double p = pi[u];
  1141             int l = level[u] + 1;
  1142             int last_out = _first_out[u+1];
  1143             for (int a = _first_out[u]; a != last_out; ++a) {
  1144               int v = _target[a];
  1145               if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
  1146                   l > level[v]) level[v] = l;
  1147             }
  1148           }
  1149 
  1150           // Modify potentials
  1151           double q = std::numeric_limits<double>::max();
  1152           for (int u = 0; u != _res_node_num; ++u) {
  1153             int lu = level[u];
  1154             double p, pu = pi[u];
  1155             int last_out = _first_out[u+1];
  1156             for (int a = _first_out[u]; a != last_out; ++a) {
  1157               if (_res_cap[a] == 0) continue;
  1158               int v = _target[a];
  1159               int ld = lu - level[v];
  1160               if (ld > 0) {
  1161                 p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
  1162                 if (p < q) q = p;
  1163               }
  1164             }
  1165           }
  1166           for (int u = 0; u != _res_node_num; ++u) {
  1167             pi[u] -= q * level[u];
  1168           }
  1169 
  1170           // Modify epsilon
  1171           epsilon = 0;
  1172           for (int u = 0; u != _res_node_num; ++u) {
  1173             double curr, pu = pi[u];
  1174             int last_out = _first_out[u+1];
  1175             for (int a = _first_out[u]; a != last_out; ++a) {
  1176               if (_res_cap[a] == 0) continue;
  1177               curr = _cost[a] + pu - pi[_target[a]];
  1178               if (-curr > epsilon) epsilon = -curr;
  1179             }
  1180           }
  1181         } else {
  1182           typedef HowardMmc<StaticDigraph, CostArcMap> HwMmc;
  1183           typedef HartmannOrlinMmc<StaticDigraph, CostArcMap> HoMmc;
  1184           typedef typename BellmanFord<StaticDigraph, CostArcMap>
  1185             ::template SetDistMap<CostNodeMap>::Create BF;
  1186 
  1187           // Set epsilon to the minimum cycle mean
  1188           Cost cycle_cost = 0;
  1189           int cycle_size = 1;
  1190           buildResidualNetwork();
  1191           HwMmc hw_mmc(_sgr, _cost_map);
  1192           if (hw_mmc.findCycleMean(hw_iter_limit) == HwMmc::ITERATION_LIMIT) {
  1193             // Howard's algorithm reached the iteration limit, start a
  1194             // strongly polynomial algorithm instead
  1195             HoMmc ho_mmc(_sgr, _cost_map);
  1196             ho_mmc.findCycleMean();
  1197             epsilon = -ho_mmc.cycleMean();
  1198             cycle_cost = ho_mmc.cycleCost();
  1199             cycle_size = ho_mmc.cycleSize();
  1200           } else {
  1201             // Set epsilon
  1202             epsilon = -hw_mmc.cycleMean();
  1203             cycle_cost = hw_mmc.cycleCost();
  1204             cycle_size = hw_mmc.cycleSize();
  1205           }
  1206 
  1207           // Compute feasible potentials for the current epsilon
  1208           for (int i = 0; i != int(_cost_vec.size()); ++i) {
  1209             _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
  1210           }
  1211           BF bf(_sgr, _cost_map);
  1212           bf.distMap(_pi_map);
  1213           bf.init(0);
  1214           bf.start();
  1215           for (int u = 0; u != _res_node_num; ++u) {
  1216             pi[u] = static_cast<double>(_pi[u]) / cycle_size;
  1217           }
  1218 
  1219           iter = limit;
  1220         }
  1221       }
  1222     }
  1223 
  1224   }; //class CycleCanceling
  1225 
  1226   ///@}
  1227 
  1228 } //namespace lemon
  1229 
  1230 #endif //LEMON_CYCLE_CANCELING_H