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