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