lemon/capacity_scaling.h
author Peter Kovacs <kpeter@inf.elte.hu>
Mon, 19 Aug 2013 22:35:54 +0200
changeset 1117 b40c2bbb8da5
parent 863 a93f1a27d831
child 919 e0cef67fe565
child 921 140c953ad5d1
permissions -rw-r--r--
Fix division by zero error in case of empty graph (#474)
     1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library.
     4  *
     5  * Copyright (C) 2003-2010
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     9  * Permission to use, modify and distribute this software is granted
    10  * provided that this copyright notice appears in all copies. For
    11  * precise terms see the accompanying LICENSE file.
    12  *
    13  * This software is provided "AS IS" with no warranty of any kind,
    14  * express or implied, and with no claim as to its suitability for any
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_CAPACITY_SCALING_H
    20 #define LEMON_CAPACITY_SCALING_H
    21 
    22 /// \ingroup min_cost_flow_algs
    23 ///
    24 /// \file
    25 /// \brief Capacity Scaling algorithm for finding a minimum cost flow.
    26 
    27 #include <vector>
    28 #include <limits>
    29 #include <lemon/core.h>
    30 #include <lemon/bin_heap.h>
    31 
    32 namespace lemon {
    33 
    34   /// \brief Default traits class of CapacityScaling algorithm.
    35   ///
    36   /// Default traits class of CapacityScaling algorithm.
    37   /// \tparam GR Digraph type.
    38   /// \tparam V The number type used for flow amounts, capacity bounds
    39   /// and supply values. By default it is \c int.
    40   /// \tparam C The number type used for costs and potentials.
    41   /// By default it is the same as \c V.
    42   template <typename GR, typename V = int, typename C = V>
    43   struct CapacityScalingDefaultTraits
    44   {
    45     /// The type of the digraph
    46     typedef GR Digraph;
    47     /// The type of the flow amounts, capacity bounds and supply values
    48     typedef V Value;
    49     /// The type of the arc costs
    50     typedef C Cost;
    51 
    52     /// \brief The type of the heap used for internal Dijkstra computations.
    53     ///
    54     /// The type of the heap used for internal Dijkstra computations.
    55     /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
    56     /// its priority type must be \c Cost and its cross reference type
    57     /// must be \ref RangeMap "RangeMap<int>".
    58     typedef BinHeap<Cost, RangeMap<int> > Heap;
    59   };
    60 
    61   /// \addtogroup min_cost_flow_algs
    62   /// @{
    63 
    64   /// \brief Implementation of the Capacity Scaling algorithm for
    65   /// finding a \ref min_cost_flow "minimum cost flow".
    66   ///
    67   /// \ref CapacityScaling implements the capacity scaling version
    68   /// of the successive shortest path algorithm for finding a
    69   /// \ref min_cost_flow "minimum cost flow" \ref amo93networkflows,
    70   /// \ref edmondskarp72theoretical. It is an efficient dual
    71   /// solution method.
    72   ///
    73   /// Most of the parameters of the problem (except for the digraph)
    74   /// can be given using separate functions, and the algorithm can be
    75   /// executed using the \ref run() function. If some parameters are not
    76   /// specified, then default values will be used.
    77   ///
    78   /// \tparam GR The digraph type the algorithm runs on.
    79   /// \tparam V The number type used for flow amounts, capacity bounds
    80   /// and supply values in the algorithm. By default, it is \c int.
    81   /// \tparam C The number type used for costs and potentials in the
    82   /// algorithm. By default, it is the same as \c V.
    83   /// \tparam TR The traits class that defines various types used by the
    84   /// algorithm. By default, it is \ref CapacityScalingDefaultTraits
    85   /// "CapacityScalingDefaultTraits<GR, V, C>".
    86   /// In most cases, this parameter should not be set directly,
    87   /// consider to use the named template parameters instead.
    88   ///
    89   /// \warning Both number types must be signed and all input data must
    90   /// be integer.
    91   /// \warning This algorithm does not support negative costs for such
    92   /// arcs that have infinite upper bound.
    93 #ifdef DOXYGEN
    94   template <typename GR, typename V, typename C, typename TR>
    95 #else
    96   template < typename GR, typename V = int, typename C = V,
    97              typename TR = CapacityScalingDefaultTraits<GR, V, C> >
    98 #endif
    99   class CapacityScaling
   100   {
   101   public:
   102 
   103     /// The type of the digraph
   104     typedef typename TR::Digraph Digraph;
   105     /// The type of the flow amounts, capacity bounds and supply values
   106     typedef typename TR::Value Value;
   107     /// The type of the arc costs
   108     typedef typename TR::Cost Cost;
   109 
   110     /// The type of the heap used for internal Dijkstra computations
   111     typedef typename TR::Heap Heap;
   112 
   113     /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
   114     typedef TR Traits;
   115 
   116   public:
   117 
   118     /// \brief Problem type constants for the \c run() function.
   119     ///
   120     /// Enum type containing the problem type constants that can be
   121     /// returned by the \ref run() function of the algorithm.
   122     enum ProblemType {
   123       /// The problem has no feasible solution (flow).
   124       INFEASIBLE,
   125       /// The problem has optimal solution (i.e. it is feasible and
   126       /// bounded), and the algorithm has found optimal flow and node
   127       /// potentials (primal and dual solutions).
   128       OPTIMAL,
   129       /// The digraph contains an arc of negative cost and infinite
   130       /// upper bound. It means that the objective function is unbounded
   131       /// on that arc, however, note that it could actually be bounded
   132       /// over the feasible flows, but this algroithm cannot handle
   133       /// these cases.
   134       UNBOUNDED
   135     };
   136 
   137   private:
   138 
   139     TEMPLATE_DIGRAPH_TYPEDEFS(GR);
   140 
   141     typedef std::vector<int> IntVector;
   142     typedef std::vector<Value> ValueVector;
   143     typedef std::vector<Cost> CostVector;
   144     typedef std::vector<char> BoolVector;
   145     // Note: vector<char> is used instead of vector<bool> for efficiency reasons
   146 
   147   private:
   148 
   149     // Data related to the underlying digraph
   150     const GR &_graph;
   151     int _node_num;
   152     int _arc_num;
   153     int _res_arc_num;
   154     int _root;
   155 
   156     // Parameters of the problem
   157     bool _have_lower;
   158     Value _sum_supply;
   159 
   160     // Data structures for storing the digraph
   161     IntNodeMap _node_id;
   162     IntArcMap _arc_idf;
   163     IntArcMap _arc_idb;
   164     IntVector _first_out;
   165     BoolVector _forward;
   166     IntVector _source;
   167     IntVector _target;
   168     IntVector _reverse;
   169 
   170     // Node and arc data
   171     ValueVector _lower;
   172     ValueVector _upper;
   173     CostVector _cost;
   174     ValueVector _supply;
   175 
   176     ValueVector _res_cap;
   177     CostVector _pi;
   178     ValueVector _excess;
   179     IntVector _excess_nodes;
   180     IntVector _deficit_nodes;
   181 
   182     Value _delta;
   183     int _factor;
   184     IntVector _pred;
   185 
   186   public:
   187 
   188     /// \brief Constant for infinite upper bounds (capacities).
   189     ///
   190     /// Constant for infinite upper bounds (capacities).
   191     /// It is \c std::numeric_limits<Value>::infinity() if available,
   192     /// \c std::numeric_limits<Value>::max() otherwise.
   193     const Value INF;
   194 
   195   private:
   196 
   197     // Special implementation of the Dijkstra algorithm for finding
   198     // shortest paths in the residual network of the digraph with
   199     // respect to the reduced arc costs and modifying the node
   200     // potentials according to the found distance labels.
   201     class ResidualDijkstra
   202     {
   203     private:
   204 
   205       int _node_num;
   206       bool _geq;
   207       const IntVector &_first_out;
   208       const IntVector &_target;
   209       const CostVector &_cost;
   210       const ValueVector &_res_cap;
   211       const ValueVector &_excess;
   212       CostVector &_pi;
   213       IntVector &_pred;
   214 
   215       IntVector _proc_nodes;
   216       CostVector _dist;
   217 
   218     public:
   219 
   220       ResidualDijkstra(CapacityScaling& cs) :
   221         _node_num(cs._node_num), _geq(cs._sum_supply < 0),
   222         _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
   223         _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
   224         _pred(cs._pred), _dist(cs._node_num)
   225       {}
   226 
   227       int run(int s, Value delta = 1) {
   228         RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
   229         Heap heap(heap_cross_ref);
   230         heap.push(s, 0);
   231         _pred[s] = -1;
   232         _proc_nodes.clear();
   233 
   234         // Process nodes
   235         while (!heap.empty() && _excess[heap.top()] > -delta) {
   236           int u = heap.top(), v;
   237           Cost d = heap.prio() + _pi[u], dn;
   238           _dist[u] = heap.prio();
   239           _proc_nodes.push_back(u);
   240           heap.pop();
   241 
   242           // Traverse outgoing residual arcs
   243           int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1;
   244           for (int a = _first_out[u]; a != last_out; ++a) {
   245             if (_res_cap[a] < delta) continue;
   246             v = _target[a];
   247             switch (heap.state(v)) {
   248               case Heap::PRE_HEAP:
   249                 heap.push(v, d + _cost[a] - _pi[v]);
   250                 _pred[v] = a;
   251                 break;
   252               case Heap::IN_HEAP:
   253                 dn = d + _cost[a] - _pi[v];
   254                 if (dn < heap[v]) {
   255                   heap.decrease(v, dn);
   256                   _pred[v] = a;
   257                 }
   258                 break;
   259               case Heap::POST_HEAP:
   260                 break;
   261             }
   262           }
   263         }
   264         if (heap.empty()) return -1;
   265 
   266         // Update potentials of processed nodes
   267         int t = heap.top();
   268         Cost dt = heap.prio();
   269         for (int i = 0; i < int(_proc_nodes.size()); ++i) {
   270           _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
   271         }
   272 
   273         return t;
   274       }
   275 
   276     }; //class ResidualDijkstra
   277 
   278   public:
   279 
   280     /// \name Named Template Parameters
   281     /// @{
   282 
   283     template <typename T>
   284     struct SetHeapTraits : public Traits {
   285       typedef T Heap;
   286     };
   287 
   288     /// \brief \ref named-templ-param "Named parameter" for setting
   289     /// \c Heap type.
   290     ///
   291     /// \ref named-templ-param "Named parameter" for setting \c Heap
   292     /// type, which is used for internal Dijkstra computations.
   293     /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
   294     /// its priority type must be \c Cost and its cross reference type
   295     /// must be \ref RangeMap "RangeMap<int>".
   296     template <typename T>
   297     struct SetHeap
   298       : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
   299       typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
   300     };
   301 
   302     /// @}
   303 
   304   protected:
   305 
   306     CapacityScaling() {}
   307 
   308   public:
   309 
   310     /// \brief Constructor.
   311     ///
   312     /// The constructor of the class.
   313     ///
   314     /// \param graph The digraph the algorithm runs on.
   315     CapacityScaling(const GR& graph) :
   316       _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
   317       INF(std::numeric_limits<Value>::has_infinity ?
   318           std::numeric_limits<Value>::infinity() :
   319           std::numeric_limits<Value>::max())
   320     {
   321       // Check the number types
   322       LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
   323         "The flow type of CapacityScaling must be signed");
   324       LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
   325         "The cost type of CapacityScaling must be signed");
   326 
   327       // Reset data structures
   328       reset();
   329     }
   330 
   331     /// \name Parameters
   332     /// The parameters of the algorithm can be specified using these
   333     /// functions.
   334 
   335     /// @{
   336 
   337     /// \brief Set the lower bounds on the arcs.
   338     ///
   339     /// This function sets the lower bounds on the arcs.
   340     /// If it is not used before calling \ref run(), the lower bounds
   341     /// will be set to zero on all arcs.
   342     ///
   343     /// \param map An arc map storing the lower bounds.
   344     /// Its \c Value type must be convertible to the \c Value type
   345     /// of the algorithm.
   346     ///
   347     /// \return <tt>(*this)</tt>
   348     template <typename LowerMap>
   349     CapacityScaling& lowerMap(const LowerMap& map) {
   350       _have_lower = true;
   351       for (ArcIt a(_graph); a != INVALID; ++a) {
   352         _lower[_arc_idf[a]] = map[a];
   353         _lower[_arc_idb[a]] = map[a];
   354       }
   355       return *this;
   356     }
   357 
   358     /// \brief Set the upper bounds (capacities) on the arcs.
   359     ///
   360     /// This function sets the upper bounds (capacities) on the arcs.
   361     /// If it is not used before calling \ref run(), the upper bounds
   362     /// will be set to \ref INF on all arcs (i.e. the flow value will be
   363     /// unbounded from above).
   364     ///
   365     /// \param map An arc map storing the upper bounds.
   366     /// Its \c Value type must be convertible to the \c Value type
   367     /// of the algorithm.
   368     ///
   369     /// \return <tt>(*this)</tt>
   370     template<typename UpperMap>
   371     CapacityScaling& upperMap(const UpperMap& map) {
   372       for (ArcIt a(_graph); a != INVALID; ++a) {
   373         _upper[_arc_idf[a]] = map[a];
   374       }
   375       return *this;
   376     }
   377 
   378     /// \brief Set the costs of the arcs.
   379     ///
   380     /// This function sets the costs of the arcs.
   381     /// If it is not used before calling \ref run(), the costs
   382     /// will be set to \c 1 on all arcs.
   383     ///
   384     /// \param map An arc map storing the costs.
   385     /// Its \c Value type must be convertible to the \c Cost type
   386     /// of the algorithm.
   387     ///
   388     /// \return <tt>(*this)</tt>
   389     template<typename CostMap>
   390     CapacityScaling& costMap(const CostMap& map) {
   391       for (ArcIt a(_graph); a != INVALID; ++a) {
   392         _cost[_arc_idf[a]] =  map[a];
   393         _cost[_arc_idb[a]] = -map[a];
   394       }
   395       return *this;
   396     }
   397 
   398     /// \brief Set the supply values of the nodes.
   399     ///
   400     /// This function sets the supply values of the nodes.
   401     /// If neither this function nor \ref stSupply() is used before
   402     /// calling \ref run(), the supply of each node will be set to zero.
   403     ///
   404     /// \param map A node map storing the supply values.
   405     /// Its \c Value type must be convertible to the \c Value type
   406     /// of the algorithm.
   407     ///
   408     /// \return <tt>(*this)</tt>
   409     template<typename SupplyMap>
   410     CapacityScaling& supplyMap(const SupplyMap& map) {
   411       for (NodeIt n(_graph); n != INVALID; ++n) {
   412         _supply[_node_id[n]] = map[n];
   413       }
   414       return *this;
   415     }
   416 
   417     /// \brief Set single source and target nodes and a supply value.
   418     ///
   419     /// This function sets a single source node and a single target node
   420     /// and the required flow value.
   421     /// If neither this function nor \ref supplyMap() is used before
   422     /// calling \ref run(), the supply of each node will be set to zero.
   423     ///
   424     /// Using this function has the same effect as using \ref supplyMap()
   425     /// with such a map in which \c k is assigned to \c s, \c -k is
   426     /// assigned to \c t and all other nodes have zero supply value.
   427     ///
   428     /// \param s The source node.
   429     /// \param t The target node.
   430     /// \param k The required amount of flow from node \c s to node \c t
   431     /// (i.e. the supply of \c s and the demand of \c t).
   432     ///
   433     /// \return <tt>(*this)</tt>
   434     CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
   435       for (int i = 0; i != _node_num; ++i) {
   436         _supply[i] = 0;
   437       }
   438       _supply[_node_id[s]] =  k;
   439       _supply[_node_id[t]] = -k;
   440       return *this;
   441     }
   442 
   443     /// @}
   444 
   445     /// \name Execution control
   446     /// The algorithm can be executed using \ref run().
   447 
   448     /// @{
   449 
   450     /// \brief Run the algorithm.
   451     ///
   452     /// This function runs the algorithm.
   453     /// The paramters can be specified using functions \ref lowerMap(),
   454     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
   455     /// For example,
   456     /// \code
   457     ///   CapacityScaling<ListDigraph> cs(graph);
   458     ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
   459     ///     .supplyMap(sup).run();
   460     /// \endcode
   461     ///
   462     /// This function can be called more than once. All the given parameters
   463     /// are kept for the next call, unless \ref resetParams() or \ref reset()
   464     /// is used, thus only the modified parameters have to be set again.
   465     /// If the underlying digraph was also modified after the construction
   466     /// of the class (or the last \ref reset() call), then the \ref reset()
   467     /// function must be called.
   468     ///
   469     /// \param factor The capacity scaling factor. It must be larger than
   470     /// one to use scaling. If it is less or equal to one, then scaling
   471     /// will be disabled.
   472     ///
   473     /// \return \c INFEASIBLE if no feasible flow exists,
   474     /// \n \c OPTIMAL if the problem has optimal solution
   475     /// (i.e. it is feasible and bounded), and the algorithm has found
   476     /// optimal flow and node potentials (primal and dual solutions),
   477     /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
   478     /// and infinite upper bound. It means that the objective function
   479     /// is unbounded on that arc, however, note that it could actually be
   480     /// bounded over the feasible flows, but this algroithm cannot handle
   481     /// these cases.
   482     ///
   483     /// \see ProblemType
   484     /// \see resetParams(), reset()
   485     ProblemType run(int factor = 4) {
   486       _factor = factor;
   487       ProblemType pt = init();
   488       if (pt != OPTIMAL) return pt;
   489       return start();
   490     }
   491 
   492     /// \brief Reset all the parameters that have been given before.
   493     ///
   494     /// This function resets all the paramaters that have been given
   495     /// before using functions \ref lowerMap(), \ref upperMap(),
   496     /// \ref costMap(), \ref supplyMap(), \ref stSupply().
   497     ///
   498     /// It is useful for multiple \ref run() calls. Basically, all the given
   499     /// parameters are kept for the next \ref run() call, unless
   500     /// \ref resetParams() or \ref reset() is used.
   501     /// If the underlying digraph was also modified after the construction
   502     /// of the class or the last \ref reset() call, then the \ref reset()
   503     /// function must be used, otherwise \ref resetParams() is sufficient.
   504     ///
   505     /// For example,
   506     /// \code
   507     ///   CapacityScaling<ListDigraph> cs(graph);
   508     ///
   509     ///   // First run
   510     ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
   511     ///     .supplyMap(sup).run();
   512     ///
   513     ///   // Run again with modified cost map (resetParams() is not called,
   514     ///   // so only the cost map have to be set again)
   515     ///   cost[e] += 100;
   516     ///   cs.costMap(cost).run();
   517     ///
   518     ///   // Run again from scratch using resetParams()
   519     ///   // (the lower bounds will be set to zero on all arcs)
   520     ///   cs.resetParams();
   521     ///   cs.upperMap(capacity).costMap(cost)
   522     ///     .supplyMap(sup).run();
   523     /// \endcode
   524     ///
   525     /// \return <tt>(*this)</tt>
   526     ///
   527     /// \see reset(), run()
   528     CapacityScaling& resetParams() {
   529       for (int i = 0; i != _node_num; ++i) {
   530         _supply[i] = 0;
   531       }
   532       for (int j = 0; j != _res_arc_num; ++j) {
   533         _lower[j] = 0;
   534         _upper[j] = INF;
   535         _cost[j] = _forward[j] ? 1 : -1;
   536       }
   537       _have_lower = false;
   538       return *this;
   539     }
   540 
   541     /// \brief Reset the internal data structures and all the parameters
   542     /// that have been given before.
   543     ///
   544     /// This function resets the internal data structures and all the
   545     /// paramaters that have been given before using functions \ref lowerMap(),
   546     /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
   547     ///
   548     /// It is useful for multiple \ref run() calls. Basically, all the given
   549     /// parameters are kept for the next \ref run() call, unless
   550     /// \ref resetParams() or \ref reset() is used.
   551     /// If the underlying digraph was also modified after the construction
   552     /// of the class or the last \ref reset() call, then the \ref reset()
   553     /// function must be used, otherwise \ref resetParams() is sufficient.
   554     ///
   555     /// See \ref resetParams() for examples.
   556     ///
   557     /// \return <tt>(*this)</tt>
   558     ///
   559     /// \see resetParams(), run()
   560     CapacityScaling& reset() {
   561       // Resize vectors
   562       _node_num = countNodes(_graph);
   563       _arc_num = countArcs(_graph);
   564       _res_arc_num = 2 * (_arc_num + _node_num);
   565       _root = _node_num;
   566       ++_node_num;
   567 
   568       _first_out.resize(_node_num + 1);
   569       _forward.resize(_res_arc_num);
   570       _source.resize(_res_arc_num);
   571       _target.resize(_res_arc_num);
   572       _reverse.resize(_res_arc_num);
   573 
   574       _lower.resize(_res_arc_num);
   575       _upper.resize(_res_arc_num);
   576       _cost.resize(_res_arc_num);
   577       _supply.resize(_node_num);
   578 
   579       _res_cap.resize(_res_arc_num);
   580       _pi.resize(_node_num);
   581       _excess.resize(_node_num);
   582       _pred.resize(_node_num);
   583 
   584       // Copy the graph
   585       int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
   586       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   587         _node_id[n] = i;
   588       }
   589       i = 0;
   590       for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   591         _first_out[i] = j;
   592         for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
   593           _arc_idf[a] = j;
   594           _forward[j] = true;
   595           _source[j] = i;
   596           _target[j] = _node_id[_graph.runningNode(a)];
   597         }
   598         for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
   599           _arc_idb[a] = j;
   600           _forward[j] = false;
   601           _source[j] = i;
   602           _target[j] = _node_id[_graph.runningNode(a)];
   603         }
   604         _forward[j] = false;
   605         _source[j] = i;
   606         _target[j] = _root;
   607         _reverse[j] = k;
   608         _forward[k] = true;
   609         _source[k] = _root;
   610         _target[k] = i;
   611         _reverse[k] = j;
   612         ++j; ++k;
   613       }
   614       _first_out[i] = j;
   615       _first_out[_node_num] = k;
   616       for (ArcIt a(_graph); a != INVALID; ++a) {
   617         int fi = _arc_idf[a];
   618         int bi = _arc_idb[a];
   619         _reverse[fi] = bi;
   620         _reverse[bi] = fi;
   621       }
   622 
   623       // Reset parameters
   624       resetParams();
   625       return *this;
   626     }
   627 
   628     /// @}
   629 
   630     /// \name Query Functions
   631     /// The results of the algorithm can be obtained using these
   632     /// functions.\n
   633     /// The \ref run() function must be called before using them.
   634 
   635     /// @{
   636 
   637     /// \brief Return the total cost of the found flow.
   638     ///
   639     /// This function returns the total cost of the found flow.
   640     /// Its complexity is O(e).
   641     ///
   642     /// \note The return type of the function can be specified as a
   643     /// template parameter. For example,
   644     /// \code
   645     ///   cs.totalCost<double>();
   646     /// \endcode
   647     /// It is useful if the total cost cannot be stored in the \c Cost
   648     /// type of the algorithm, which is the default return type of the
   649     /// function.
   650     ///
   651     /// \pre \ref run() must be called before using this function.
   652     template <typename Number>
   653     Number totalCost() const {
   654       Number c = 0;
   655       for (ArcIt a(_graph); a != INVALID; ++a) {
   656         int i = _arc_idb[a];
   657         c += static_cast<Number>(_res_cap[i]) *
   658              (-static_cast<Number>(_cost[i]));
   659       }
   660       return c;
   661     }
   662 
   663 #ifndef DOXYGEN
   664     Cost totalCost() const {
   665       return totalCost<Cost>();
   666     }
   667 #endif
   668 
   669     /// \brief Return the flow on the given arc.
   670     ///
   671     /// This function returns the flow on the given arc.
   672     ///
   673     /// \pre \ref run() must be called before using this function.
   674     Value flow(const Arc& a) const {
   675       return _res_cap[_arc_idb[a]];
   676     }
   677 
   678     /// \brief Return the flow map (the primal solution).
   679     ///
   680     /// This function copies the flow value on each arc into the given
   681     /// map. The \c Value type of the algorithm must be convertible to
   682     /// the \c Value type of the map.
   683     ///
   684     /// \pre \ref run() must be called before using this function.
   685     template <typename FlowMap>
   686     void flowMap(FlowMap &map) const {
   687       for (ArcIt a(_graph); a != INVALID; ++a) {
   688         map.set(a, _res_cap[_arc_idb[a]]);
   689       }
   690     }
   691 
   692     /// \brief Return the potential (dual value) of the given node.
   693     ///
   694     /// This function returns the potential (dual value) of the
   695     /// given node.
   696     ///
   697     /// \pre \ref run() must be called before using this function.
   698     Cost potential(const Node& n) const {
   699       return _pi[_node_id[n]];
   700     }
   701 
   702     /// \brief Return the potential map (the dual solution).
   703     ///
   704     /// This function copies the potential (dual value) of each node
   705     /// into the given map.
   706     /// The \c Cost type of the algorithm must be convertible to the
   707     /// \c Value type of the map.
   708     ///
   709     /// \pre \ref run() must be called before using this function.
   710     template <typename PotentialMap>
   711     void potentialMap(PotentialMap &map) const {
   712       for (NodeIt n(_graph); n != INVALID; ++n) {
   713         map.set(n, _pi[_node_id[n]]);
   714       }
   715     }
   716 
   717     /// @}
   718 
   719   private:
   720 
   721     // Initialize the algorithm
   722     ProblemType init() {
   723       if (_node_num <= 1) return INFEASIBLE;
   724 
   725       // Check the sum of supply values
   726       _sum_supply = 0;
   727       for (int i = 0; i != _root; ++i) {
   728         _sum_supply += _supply[i];
   729       }
   730       if (_sum_supply > 0) return INFEASIBLE;
   731 
   732       // Initialize vectors
   733       for (int i = 0; i != _root; ++i) {
   734         _pi[i] = 0;
   735         _excess[i] = _supply[i];
   736       }
   737 
   738       // Remove non-zero lower bounds
   739       const Value MAX = std::numeric_limits<Value>::max();
   740       int last_out;
   741       if (_have_lower) {
   742         for (int i = 0; i != _root; ++i) {
   743           last_out = _first_out[i+1];
   744           for (int j = _first_out[i]; j != last_out; ++j) {
   745             if (_forward[j]) {
   746               Value c = _lower[j];
   747               if (c >= 0) {
   748                 _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
   749               } else {
   750                 _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
   751               }
   752               _excess[i] -= c;
   753               _excess[_target[j]] += c;
   754             } else {
   755               _res_cap[j] = 0;
   756             }
   757           }
   758         }
   759       } else {
   760         for (int j = 0; j != _res_arc_num; ++j) {
   761           _res_cap[j] = _forward[j] ? _upper[j] : 0;
   762         }
   763       }
   764 
   765       // Handle negative costs
   766       for (int i = 0; i != _root; ++i) {
   767         last_out = _first_out[i+1] - 1;
   768         for (int j = _first_out[i]; j != last_out; ++j) {
   769           Value rc = _res_cap[j];
   770           if (_cost[j] < 0 && rc > 0) {
   771             if (rc >= MAX) return UNBOUNDED;
   772             _excess[i] -= rc;
   773             _excess[_target[j]] += rc;
   774             _res_cap[j] = 0;
   775             _res_cap[_reverse[j]] += rc;
   776           }
   777         }
   778       }
   779 
   780       // Handle GEQ supply type
   781       if (_sum_supply < 0) {
   782         _pi[_root] = 0;
   783         _excess[_root] = -_sum_supply;
   784         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   785           int ra = _reverse[a];
   786           _res_cap[a] = -_sum_supply + 1;
   787           _res_cap[ra] = 0;
   788           _cost[a] = 0;
   789           _cost[ra] = 0;
   790         }
   791       } else {
   792         _pi[_root] = 0;
   793         _excess[_root] = 0;
   794         for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   795           int ra = _reverse[a];
   796           _res_cap[a] = 1;
   797           _res_cap[ra] = 0;
   798           _cost[a] = 0;
   799           _cost[ra] = 0;
   800         }
   801       }
   802 
   803       // Initialize delta value
   804       if (_factor > 1) {
   805         // With scaling
   806         Value max_sup = 0, max_dem = 0, max_cap = 0;
   807         for (int i = 0; i != _root; ++i) {
   808           Value ex = _excess[i];
   809           if ( ex > max_sup) max_sup =  ex;
   810           if (-ex > max_dem) max_dem = -ex;
   811           int last_out = _first_out[i+1] - 1;
   812           for (int j = _first_out[i]; j != last_out; ++j) {
   813             if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
   814           }
   815         }
   816         max_sup = std::min(std::min(max_sup, max_dem), max_cap);
   817         for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
   818       } else {
   819         // Without scaling
   820         _delta = 1;
   821       }
   822 
   823       return OPTIMAL;
   824     }
   825 
   826     ProblemType start() {
   827       // Execute the algorithm
   828       ProblemType pt;
   829       if (_delta > 1)
   830         pt = startWithScaling();
   831       else
   832         pt = startWithoutScaling();
   833 
   834       // Handle non-zero lower bounds
   835       if (_have_lower) {
   836         int limit = _first_out[_root];
   837         for (int j = 0; j != limit; ++j) {
   838           if (!_forward[j]) _res_cap[j] += _lower[j];
   839         }
   840       }
   841 
   842       // Shift potentials if necessary
   843       Cost pr = _pi[_root];
   844       if (_sum_supply < 0 || pr > 0) {
   845         for (int i = 0; i != _node_num; ++i) {
   846           _pi[i] -= pr;
   847         }
   848       }
   849 
   850       return pt;
   851     }
   852 
   853     // Execute the capacity scaling algorithm
   854     ProblemType startWithScaling() {
   855       // Perform capacity scaling phases
   856       int s, t;
   857       ResidualDijkstra _dijkstra(*this);
   858       while (true) {
   859         // Saturate all arcs not satisfying the optimality condition
   860         int last_out;
   861         for (int u = 0; u != _node_num; ++u) {
   862           last_out = _sum_supply < 0 ?
   863             _first_out[u+1] : _first_out[u+1] - 1;
   864           for (int a = _first_out[u]; a != last_out; ++a) {
   865             int v = _target[a];
   866             Cost c = _cost[a] + _pi[u] - _pi[v];
   867             Value rc = _res_cap[a];
   868             if (c < 0 && rc >= _delta) {
   869               _excess[u] -= rc;
   870               _excess[v] += rc;
   871               _res_cap[a] = 0;
   872               _res_cap[_reverse[a]] += rc;
   873             }
   874           }
   875         }
   876 
   877         // Find excess nodes and deficit nodes
   878         _excess_nodes.clear();
   879         _deficit_nodes.clear();
   880         for (int u = 0; u != _node_num; ++u) {
   881           Value ex = _excess[u];
   882           if (ex >=  _delta) _excess_nodes.push_back(u);
   883           if (ex <= -_delta) _deficit_nodes.push_back(u);
   884         }
   885         int next_node = 0, next_def_node = 0;
   886 
   887         // Find augmenting shortest paths
   888         while (next_node < int(_excess_nodes.size())) {
   889           // Check deficit nodes
   890           if (_delta > 1) {
   891             bool delta_deficit = false;
   892             for ( ; next_def_node < int(_deficit_nodes.size());
   893                     ++next_def_node ) {
   894               if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
   895                 delta_deficit = true;
   896                 break;
   897               }
   898             }
   899             if (!delta_deficit) break;
   900           }
   901 
   902           // Run Dijkstra in the residual network
   903           s = _excess_nodes[next_node];
   904           if ((t = _dijkstra.run(s, _delta)) == -1) {
   905             if (_delta > 1) {
   906               ++next_node;
   907               continue;
   908             }
   909             return INFEASIBLE;
   910           }
   911 
   912           // Augment along a shortest path from s to t
   913           Value d = std::min(_excess[s], -_excess[t]);
   914           int u = t;
   915           int a;
   916           if (d > _delta) {
   917             while ((a = _pred[u]) != -1) {
   918               if (_res_cap[a] < d) d = _res_cap[a];
   919               u = _source[a];
   920             }
   921           }
   922           u = t;
   923           while ((a = _pred[u]) != -1) {
   924             _res_cap[a] -= d;
   925             _res_cap[_reverse[a]] += d;
   926             u = _source[a];
   927           }
   928           _excess[s] -= d;
   929           _excess[t] += d;
   930 
   931           if (_excess[s] < _delta) ++next_node;
   932         }
   933 
   934         if (_delta == 1) break;
   935         _delta = _delta <= _factor ? 1 : _delta / _factor;
   936       }
   937 
   938       return OPTIMAL;
   939     }
   940 
   941     // Execute the successive shortest path algorithm
   942     ProblemType startWithoutScaling() {
   943       // Find excess nodes
   944       _excess_nodes.clear();
   945       for (int i = 0; i != _node_num; ++i) {
   946         if (_excess[i] > 0) _excess_nodes.push_back(i);
   947       }
   948       if (_excess_nodes.size() == 0) return OPTIMAL;
   949       int next_node = 0;
   950 
   951       // Find shortest paths
   952       int s, t;
   953       ResidualDijkstra _dijkstra(*this);
   954       while ( _excess[_excess_nodes[next_node]] > 0 ||
   955               ++next_node < int(_excess_nodes.size()) )
   956       {
   957         // Run Dijkstra in the residual network
   958         s = _excess_nodes[next_node];
   959         if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
   960 
   961         // Augment along a shortest path from s to t
   962         Value d = std::min(_excess[s], -_excess[t]);
   963         int u = t;
   964         int a;
   965         if (d > 1) {
   966           while ((a = _pred[u]) != -1) {
   967             if (_res_cap[a] < d) d = _res_cap[a];
   968             u = _source[a];
   969           }
   970         }
   971         u = t;
   972         while ((a = _pred[u]) != -1) {
   973           _res_cap[a] -= d;
   974           _res_cap[_reverse[a]] += d;
   975           u = _source[a];
   976         }
   977         _excess[s] -= d;
   978         _excess[t] += d;
   979       }
   980 
   981       return OPTIMAL;
   982     }
   983 
   984   }; //class CapacityScaling
   985 
   986   ///@}
   987 
   988 } //namespace lemon
   989 
   990 #endif //LEMON_CAPACITY_SCALING_H