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