lemon/capacity_scaling.h
changeset 1099 ad40f7d32846
parent 863 a93f1a27d831
child 919 e0cef67fe565
child 921 140c953ad5d1
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/lemon/capacity_scaling.h	Sun Aug 11 15:28:12 2013 +0200
     1.3 @@ -0,0 +1,990 @@
     1.4 +/* -*- mode: C++; indent-tabs-mode: nil; -*-
     1.5 + *
     1.6 + * This file is a part of LEMON, a generic C++ optimization library.
     1.7 + *
     1.8 + * Copyright (C) 2003-2010
     1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
    1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
    1.11 + *
    1.12 + * Permission to use, modify and distribute this software is granted
    1.13 + * provided that this copyright notice appears in all copies. For
    1.14 + * precise terms see the accompanying LICENSE file.
    1.15 + *
    1.16 + * This software is provided "AS IS" with no warranty of any kind,
    1.17 + * express or implied, and with no claim as to its suitability for any
    1.18 + * purpose.
    1.19 + *
    1.20 + */
    1.21 +
    1.22 +#ifndef LEMON_CAPACITY_SCALING_H
    1.23 +#define LEMON_CAPACITY_SCALING_H
    1.24 +
    1.25 +/// \ingroup min_cost_flow_algs
    1.26 +///
    1.27 +/// \file
    1.28 +/// \brief Capacity Scaling algorithm for finding a minimum cost flow.
    1.29 +
    1.30 +#include <vector>
    1.31 +#include <limits>
    1.32 +#include <lemon/core.h>
    1.33 +#include <lemon/bin_heap.h>
    1.34 +
    1.35 +namespace lemon {
    1.36 +
    1.37 +  /// \brief Default traits class of CapacityScaling algorithm.
    1.38 +  ///
    1.39 +  /// Default traits class of CapacityScaling algorithm.
    1.40 +  /// \tparam GR Digraph type.
    1.41 +  /// \tparam V The number type used for flow amounts, capacity bounds
    1.42 +  /// and supply values. By default it is \c int.
    1.43 +  /// \tparam C The number type used for costs and potentials.
    1.44 +  /// By default it is the same as \c V.
    1.45 +  template <typename GR, typename V = int, typename C = V>
    1.46 +  struct CapacityScalingDefaultTraits
    1.47 +  {
    1.48 +    /// The type of the digraph
    1.49 +    typedef GR Digraph;
    1.50 +    /// The type of the flow amounts, capacity bounds and supply values
    1.51 +    typedef V Value;
    1.52 +    /// The type of the arc costs
    1.53 +    typedef C Cost;
    1.54 +
    1.55 +    /// \brief The type of the heap used for internal Dijkstra computations.
    1.56 +    ///
    1.57 +    /// The type of the heap used for internal Dijkstra computations.
    1.58 +    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
    1.59 +    /// its priority type must be \c Cost and its cross reference type
    1.60 +    /// must be \ref RangeMap "RangeMap<int>".
    1.61 +    typedef BinHeap<Cost, RangeMap<int> > Heap;
    1.62 +  };
    1.63 +
    1.64 +  /// \addtogroup min_cost_flow_algs
    1.65 +  /// @{
    1.66 +
    1.67 +  /// \brief Implementation of the Capacity Scaling algorithm for
    1.68 +  /// finding a \ref min_cost_flow "minimum cost flow".
    1.69 +  ///
    1.70 +  /// \ref CapacityScaling implements the capacity scaling version
    1.71 +  /// of the successive shortest path algorithm for finding a
    1.72 +  /// \ref min_cost_flow "minimum cost flow" \ref amo93networkflows,
    1.73 +  /// \ref edmondskarp72theoretical. It is an efficient dual
    1.74 +  /// solution method.
    1.75 +  ///
    1.76 +  /// Most of the parameters of the problem (except for the digraph)
    1.77 +  /// can be given using separate functions, and the algorithm can be
    1.78 +  /// executed using the \ref run() function. If some parameters are not
    1.79 +  /// specified, then default values will be used.
    1.80 +  ///
    1.81 +  /// \tparam GR The digraph type the algorithm runs on.
    1.82 +  /// \tparam V The number type used for flow amounts, capacity bounds
    1.83 +  /// and supply values in the algorithm. By default, it is \c int.
    1.84 +  /// \tparam C The number type used for costs and potentials in the
    1.85 +  /// algorithm. By default, it is the same as \c V.
    1.86 +  /// \tparam TR The traits class that defines various types used by the
    1.87 +  /// algorithm. By default, it is \ref CapacityScalingDefaultTraits
    1.88 +  /// "CapacityScalingDefaultTraits<GR, V, C>".
    1.89 +  /// In most cases, this parameter should not be set directly,
    1.90 +  /// consider to use the named template parameters instead.
    1.91 +  ///
    1.92 +  /// \warning Both number types must be signed and all input data must
    1.93 +  /// be integer.
    1.94 +  /// \warning This algorithm does not support negative costs for such
    1.95 +  /// arcs that have infinite upper bound.
    1.96 +#ifdef DOXYGEN
    1.97 +  template <typename GR, typename V, typename C, typename TR>
    1.98 +#else
    1.99 +  template < typename GR, typename V = int, typename C = V,
   1.100 +             typename TR = CapacityScalingDefaultTraits<GR, V, C> >
   1.101 +#endif
   1.102 +  class CapacityScaling
   1.103 +  {
   1.104 +  public:
   1.105 +
   1.106 +    /// The type of the digraph
   1.107 +    typedef typename TR::Digraph Digraph;
   1.108 +    /// The type of the flow amounts, capacity bounds and supply values
   1.109 +    typedef typename TR::Value Value;
   1.110 +    /// The type of the arc costs
   1.111 +    typedef typename TR::Cost Cost;
   1.112 +
   1.113 +    /// The type of the heap used for internal Dijkstra computations
   1.114 +    typedef typename TR::Heap Heap;
   1.115 +
   1.116 +    /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
   1.117 +    typedef TR Traits;
   1.118 +
   1.119 +  public:
   1.120 +
   1.121 +    /// \brief Problem type constants for the \c run() function.
   1.122 +    ///
   1.123 +    /// Enum type containing the problem type constants that can be
   1.124 +    /// returned by the \ref run() function of the algorithm.
   1.125 +    enum ProblemType {
   1.126 +      /// The problem has no feasible solution (flow).
   1.127 +      INFEASIBLE,
   1.128 +      /// The problem has optimal solution (i.e. it is feasible and
   1.129 +      /// bounded), and the algorithm has found optimal flow and node
   1.130 +      /// potentials (primal and dual solutions).
   1.131 +      OPTIMAL,
   1.132 +      /// The digraph contains an arc of negative cost and infinite
   1.133 +      /// upper bound. It means that the objective function is unbounded
   1.134 +      /// on that arc, however, note that it could actually be bounded
   1.135 +      /// over the feasible flows, but this algroithm cannot handle
   1.136 +      /// these cases.
   1.137 +      UNBOUNDED
   1.138 +    };
   1.139 +
   1.140 +  private:
   1.141 +
   1.142 +    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
   1.143 +
   1.144 +    typedef std::vector<int> IntVector;
   1.145 +    typedef std::vector<Value> ValueVector;
   1.146 +    typedef std::vector<Cost> CostVector;
   1.147 +    typedef std::vector<char> BoolVector;
   1.148 +    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
   1.149 +
   1.150 +  private:
   1.151 +
   1.152 +    // Data related to the underlying digraph
   1.153 +    const GR &_graph;
   1.154 +    int _node_num;
   1.155 +    int _arc_num;
   1.156 +    int _res_arc_num;
   1.157 +    int _root;
   1.158 +
   1.159 +    // Parameters of the problem
   1.160 +    bool _have_lower;
   1.161 +    Value _sum_supply;
   1.162 +
   1.163 +    // Data structures for storing the digraph
   1.164 +    IntNodeMap _node_id;
   1.165 +    IntArcMap _arc_idf;
   1.166 +    IntArcMap _arc_idb;
   1.167 +    IntVector _first_out;
   1.168 +    BoolVector _forward;
   1.169 +    IntVector _source;
   1.170 +    IntVector _target;
   1.171 +    IntVector _reverse;
   1.172 +
   1.173 +    // Node and arc data
   1.174 +    ValueVector _lower;
   1.175 +    ValueVector _upper;
   1.176 +    CostVector _cost;
   1.177 +    ValueVector _supply;
   1.178 +
   1.179 +    ValueVector _res_cap;
   1.180 +    CostVector _pi;
   1.181 +    ValueVector _excess;
   1.182 +    IntVector _excess_nodes;
   1.183 +    IntVector _deficit_nodes;
   1.184 +
   1.185 +    Value _delta;
   1.186 +    int _factor;
   1.187 +    IntVector _pred;
   1.188 +
   1.189 +  public:
   1.190 +
   1.191 +    /// \brief Constant for infinite upper bounds (capacities).
   1.192 +    ///
   1.193 +    /// Constant for infinite upper bounds (capacities).
   1.194 +    /// It is \c std::numeric_limits<Value>::infinity() if available,
   1.195 +    /// \c std::numeric_limits<Value>::max() otherwise.
   1.196 +    const Value INF;
   1.197 +
   1.198 +  private:
   1.199 +
   1.200 +    // Special implementation of the Dijkstra algorithm for finding
   1.201 +    // shortest paths in the residual network of the digraph with
   1.202 +    // respect to the reduced arc costs and modifying the node
   1.203 +    // potentials according to the found distance labels.
   1.204 +    class ResidualDijkstra
   1.205 +    {
   1.206 +    private:
   1.207 +
   1.208 +      int _node_num;
   1.209 +      bool _geq;
   1.210 +      const IntVector &_first_out;
   1.211 +      const IntVector &_target;
   1.212 +      const CostVector &_cost;
   1.213 +      const ValueVector &_res_cap;
   1.214 +      const ValueVector &_excess;
   1.215 +      CostVector &_pi;
   1.216 +      IntVector &_pred;
   1.217 +
   1.218 +      IntVector _proc_nodes;
   1.219 +      CostVector _dist;
   1.220 +
   1.221 +    public:
   1.222 +
   1.223 +      ResidualDijkstra(CapacityScaling& cs) :
   1.224 +        _node_num(cs._node_num), _geq(cs._sum_supply < 0),
   1.225 +        _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
   1.226 +        _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
   1.227 +        _pred(cs._pred), _dist(cs._node_num)
   1.228 +      {}
   1.229 +
   1.230 +      int run(int s, Value delta = 1) {
   1.231 +        RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
   1.232 +        Heap heap(heap_cross_ref);
   1.233 +        heap.push(s, 0);
   1.234 +        _pred[s] = -1;
   1.235 +        _proc_nodes.clear();
   1.236 +
   1.237 +        // Process nodes
   1.238 +        while (!heap.empty() && _excess[heap.top()] > -delta) {
   1.239 +          int u = heap.top(), v;
   1.240 +          Cost d = heap.prio() + _pi[u], dn;
   1.241 +          _dist[u] = heap.prio();
   1.242 +          _proc_nodes.push_back(u);
   1.243 +          heap.pop();
   1.244 +
   1.245 +          // Traverse outgoing residual arcs
   1.246 +          int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1;
   1.247 +          for (int a = _first_out[u]; a != last_out; ++a) {
   1.248 +            if (_res_cap[a] < delta) continue;
   1.249 +            v = _target[a];
   1.250 +            switch (heap.state(v)) {
   1.251 +              case Heap::PRE_HEAP:
   1.252 +                heap.push(v, d + _cost[a] - _pi[v]);
   1.253 +                _pred[v] = a;
   1.254 +                break;
   1.255 +              case Heap::IN_HEAP:
   1.256 +                dn = d + _cost[a] - _pi[v];
   1.257 +                if (dn < heap[v]) {
   1.258 +                  heap.decrease(v, dn);
   1.259 +                  _pred[v] = a;
   1.260 +                }
   1.261 +                break;
   1.262 +              case Heap::POST_HEAP:
   1.263 +                break;
   1.264 +            }
   1.265 +          }
   1.266 +        }
   1.267 +        if (heap.empty()) return -1;
   1.268 +
   1.269 +        // Update potentials of processed nodes
   1.270 +        int t = heap.top();
   1.271 +        Cost dt = heap.prio();
   1.272 +        for (int i = 0; i < int(_proc_nodes.size()); ++i) {
   1.273 +          _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
   1.274 +        }
   1.275 +
   1.276 +        return t;
   1.277 +      }
   1.278 +
   1.279 +    }; //class ResidualDijkstra
   1.280 +
   1.281 +  public:
   1.282 +
   1.283 +    /// \name Named Template Parameters
   1.284 +    /// @{
   1.285 +
   1.286 +    template <typename T>
   1.287 +    struct SetHeapTraits : public Traits {
   1.288 +      typedef T Heap;
   1.289 +    };
   1.290 +
   1.291 +    /// \brief \ref named-templ-param "Named parameter" for setting
   1.292 +    /// \c Heap type.
   1.293 +    ///
   1.294 +    /// \ref named-templ-param "Named parameter" for setting \c Heap
   1.295 +    /// type, which is used for internal Dijkstra computations.
   1.296 +    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
   1.297 +    /// its priority type must be \c Cost and its cross reference type
   1.298 +    /// must be \ref RangeMap "RangeMap<int>".
   1.299 +    template <typename T>
   1.300 +    struct SetHeap
   1.301 +      : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
   1.302 +      typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
   1.303 +    };
   1.304 +
   1.305 +    /// @}
   1.306 +
   1.307 +  protected:
   1.308 +
   1.309 +    CapacityScaling() {}
   1.310 +
   1.311 +  public:
   1.312 +
   1.313 +    /// \brief Constructor.
   1.314 +    ///
   1.315 +    /// The constructor of the class.
   1.316 +    ///
   1.317 +    /// \param graph The digraph the algorithm runs on.
   1.318 +    CapacityScaling(const GR& graph) :
   1.319 +      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
   1.320 +      INF(std::numeric_limits<Value>::has_infinity ?
   1.321 +          std::numeric_limits<Value>::infinity() :
   1.322 +          std::numeric_limits<Value>::max())
   1.323 +    {
   1.324 +      // Check the number types
   1.325 +      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
   1.326 +        "The flow type of CapacityScaling must be signed");
   1.327 +      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
   1.328 +        "The cost type of CapacityScaling must be signed");
   1.329 +
   1.330 +      // Reset data structures
   1.331 +      reset();
   1.332 +    }
   1.333 +
   1.334 +    /// \name Parameters
   1.335 +    /// The parameters of the algorithm can be specified using these
   1.336 +    /// functions.
   1.337 +
   1.338 +    /// @{
   1.339 +
   1.340 +    /// \brief Set the lower bounds on the arcs.
   1.341 +    ///
   1.342 +    /// This function sets the lower bounds on the arcs.
   1.343 +    /// If it is not used before calling \ref run(), the lower bounds
   1.344 +    /// will be set to zero on all arcs.
   1.345 +    ///
   1.346 +    /// \param map An arc map storing the lower bounds.
   1.347 +    /// Its \c Value type must be convertible to the \c Value type
   1.348 +    /// of the algorithm.
   1.349 +    ///
   1.350 +    /// \return <tt>(*this)</tt>
   1.351 +    template <typename LowerMap>
   1.352 +    CapacityScaling& lowerMap(const LowerMap& map) {
   1.353 +      _have_lower = true;
   1.354 +      for (ArcIt a(_graph); a != INVALID; ++a) {
   1.355 +        _lower[_arc_idf[a]] = map[a];
   1.356 +        _lower[_arc_idb[a]] = map[a];
   1.357 +      }
   1.358 +      return *this;
   1.359 +    }
   1.360 +
   1.361 +    /// \brief Set the upper bounds (capacities) on the arcs.
   1.362 +    ///
   1.363 +    /// This function sets the upper bounds (capacities) on the arcs.
   1.364 +    /// If it is not used before calling \ref run(), the upper bounds
   1.365 +    /// will be set to \ref INF on all arcs (i.e. the flow value will be
   1.366 +    /// unbounded from above).
   1.367 +    ///
   1.368 +    /// \param map An arc map storing the upper bounds.
   1.369 +    /// Its \c Value type must be convertible to the \c Value type
   1.370 +    /// of the algorithm.
   1.371 +    ///
   1.372 +    /// \return <tt>(*this)</tt>
   1.373 +    template<typename UpperMap>
   1.374 +    CapacityScaling& upperMap(const UpperMap& map) {
   1.375 +      for (ArcIt a(_graph); a != INVALID; ++a) {
   1.376 +        _upper[_arc_idf[a]] = map[a];
   1.377 +      }
   1.378 +      return *this;
   1.379 +    }
   1.380 +
   1.381 +    /// \brief Set the costs of the arcs.
   1.382 +    ///
   1.383 +    /// This function sets the costs of the arcs.
   1.384 +    /// If it is not used before calling \ref run(), the costs
   1.385 +    /// will be set to \c 1 on all arcs.
   1.386 +    ///
   1.387 +    /// \param map An arc map storing the costs.
   1.388 +    /// Its \c Value type must be convertible to the \c Cost type
   1.389 +    /// of the algorithm.
   1.390 +    ///
   1.391 +    /// \return <tt>(*this)</tt>
   1.392 +    template<typename CostMap>
   1.393 +    CapacityScaling& costMap(const CostMap& map) {
   1.394 +      for (ArcIt a(_graph); a != INVALID; ++a) {
   1.395 +        _cost[_arc_idf[a]] =  map[a];
   1.396 +        _cost[_arc_idb[a]] = -map[a];
   1.397 +      }
   1.398 +      return *this;
   1.399 +    }
   1.400 +
   1.401 +    /// \brief Set the supply values of the nodes.
   1.402 +    ///
   1.403 +    /// This function sets the supply values of the nodes.
   1.404 +    /// If neither this function nor \ref stSupply() is used before
   1.405 +    /// calling \ref run(), the supply of each node will be set to zero.
   1.406 +    ///
   1.407 +    /// \param map A node map storing the supply values.
   1.408 +    /// Its \c Value type must be convertible to the \c Value type
   1.409 +    /// of the algorithm.
   1.410 +    ///
   1.411 +    /// \return <tt>(*this)</tt>
   1.412 +    template<typename SupplyMap>
   1.413 +    CapacityScaling& supplyMap(const SupplyMap& map) {
   1.414 +      for (NodeIt n(_graph); n != INVALID; ++n) {
   1.415 +        _supply[_node_id[n]] = map[n];
   1.416 +      }
   1.417 +      return *this;
   1.418 +    }
   1.419 +
   1.420 +    /// \brief Set single source and target nodes and a supply value.
   1.421 +    ///
   1.422 +    /// This function sets a single source node and a single target node
   1.423 +    /// and the required flow value.
   1.424 +    /// If neither this function nor \ref supplyMap() is used before
   1.425 +    /// calling \ref run(), the supply of each node will be set to zero.
   1.426 +    ///
   1.427 +    /// Using this function has the same effect as using \ref supplyMap()
   1.428 +    /// with such a map in which \c k is assigned to \c s, \c -k is
   1.429 +    /// assigned to \c t and all other nodes have zero supply value.
   1.430 +    ///
   1.431 +    /// \param s The source node.
   1.432 +    /// \param t The target node.
   1.433 +    /// \param k The required amount of flow from node \c s to node \c t
   1.434 +    /// (i.e. the supply of \c s and the demand of \c t).
   1.435 +    ///
   1.436 +    /// \return <tt>(*this)</tt>
   1.437 +    CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
   1.438 +      for (int i = 0; i != _node_num; ++i) {
   1.439 +        _supply[i] = 0;
   1.440 +      }
   1.441 +      _supply[_node_id[s]] =  k;
   1.442 +      _supply[_node_id[t]] = -k;
   1.443 +      return *this;
   1.444 +    }
   1.445 +
   1.446 +    /// @}
   1.447 +
   1.448 +    /// \name Execution control
   1.449 +    /// The algorithm can be executed using \ref run().
   1.450 +
   1.451 +    /// @{
   1.452 +
   1.453 +    /// \brief Run the algorithm.
   1.454 +    ///
   1.455 +    /// This function runs the algorithm.
   1.456 +    /// The paramters can be specified using functions \ref lowerMap(),
   1.457 +    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
   1.458 +    /// For example,
   1.459 +    /// \code
   1.460 +    ///   CapacityScaling<ListDigraph> cs(graph);
   1.461 +    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
   1.462 +    ///     .supplyMap(sup).run();
   1.463 +    /// \endcode
   1.464 +    ///
   1.465 +    /// This function can be called more than once. All the given parameters
   1.466 +    /// are kept for the next call, unless \ref resetParams() or \ref reset()
   1.467 +    /// is used, thus only the modified parameters have to be set again.
   1.468 +    /// If the underlying digraph was also modified after the construction
   1.469 +    /// of the class (or the last \ref reset() call), then the \ref reset()
   1.470 +    /// function must be called.
   1.471 +    ///
   1.472 +    /// \param factor The capacity scaling factor. It must be larger than
   1.473 +    /// one to use scaling. If it is less or equal to one, then scaling
   1.474 +    /// will be disabled.
   1.475 +    ///
   1.476 +    /// \return \c INFEASIBLE if no feasible flow exists,
   1.477 +    /// \n \c OPTIMAL if the problem has optimal solution
   1.478 +    /// (i.e. it is feasible and bounded), and the algorithm has found
   1.479 +    /// optimal flow and node potentials (primal and dual solutions),
   1.480 +    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
   1.481 +    /// and infinite upper bound. It means that the objective function
   1.482 +    /// is unbounded on that arc, however, note that it could actually be
   1.483 +    /// bounded over the feasible flows, but this algroithm cannot handle
   1.484 +    /// these cases.
   1.485 +    ///
   1.486 +    /// \see ProblemType
   1.487 +    /// \see resetParams(), reset()
   1.488 +    ProblemType run(int factor = 4) {
   1.489 +      _factor = factor;
   1.490 +      ProblemType pt = init();
   1.491 +      if (pt != OPTIMAL) return pt;
   1.492 +      return start();
   1.493 +    }
   1.494 +
   1.495 +    /// \brief Reset all the parameters that have been given before.
   1.496 +    ///
   1.497 +    /// This function resets all the paramaters that have been given
   1.498 +    /// before using functions \ref lowerMap(), \ref upperMap(),
   1.499 +    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
   1.500 +    ///
   1.501 +    /// It is useful for multiple \ref run() calls. Basically, all the given
   1.502 +    /// parameters are kept for the next \ref run() call, unless
   1.503 +    /// \ref resetParams() or \ref reset() is used.
   1.504 +    /// If the underlying digraph was also modified after the construction
   1.505 +    /// of the class or the last \ref reset() call, then the \ref reset()
   1.506 +    /// function must be used, otherwise \ref resetParams() is sufficient.
   1.507 +    ///
   1.508 +    /// For example,
   1.509 +    /// \code
   1.510 +    ///   CapacityScaling<ListDigraph> cs(graph);
   1.511 +    ///
   1.512 +    ///   // First run
   1.513 +    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
   1.514 +    ///     .supplyMap(sup).run();
   1.515 +    ///
   1.516 +    ///   // Run again with modified cost map (resetParams() is not called,
   1.517 +    ///   // so only the cost map have to be set again)
   1.518 +    ///   cost[e] += 100;
   1.519 +    ///   cs.costMap(cost).run();
   1.520 +    ///
   1.521 +    ///   // Run again from scratch using resetParams()
   1.522 +    ///   // (the lower bounds will be set to zero on all arcs)
   1.523 +    ///   cs.resetParams();
   1.524 +    ///   cs.upperMap(capacity).costMap(cost)
   1.525 +    ///     .supplyMap(sup).run();
   1.526 +    /// \endcode
   1.527 +    ///
   1.528 +    /// \return <tt>(*this)</tt>
   1.529 +    ///
   1.530 +    /// \see reset(), run()
   1.531 +    CapacityScaling& resetParams() {
   1.532 +      for (int i = 0; i != _node_num; ++i) {
   1.533 +        _supply[i] = 0;
   1.534 +      }
   1.535 +      for (int j = 0; j != _res_arc_num; ++j) {
   1.536 +        _lower[j] = 0;
   1.537 +        _upper[j] = INF;
   1.538 +        _cost[j] = _forward[j] ? 1 : -1;
   1.539 +      }
   1.540 +      _have_lower = false;
   1.541 +      return *this;
   1.542 +    }
   1.543 +
   1.544 +    /// \brief Reset the internal data structures and all the parameters
   1.545 +    /// that have been given before.
   1.546 +    ///
   1.547 +    /// This function resets the internal data structures and all the
   1.548 +    /// paramaters that have been given before using functions \ref lowerMap(),
   1.549 +    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
   1.550 +    ///
   1.551 +    /// It is useful for multiple \ref run() calls. Basically, all the given
   1.552 +    /// parameters are kept for the next \ref run() call, unless
   1.553 +    /// \ref resetParams() or \ref reset() is used.
   1.554 +    /// If the underlying digraph was also modified after the construction
   1.555 +    /// of the class or the last \ref reset() call, then the \ref reset()
   1.556 +    /// function must be used, otherwise \ref resetParams() is sufficient.
   1.557 +    ///
   1.558 +    /// See \ref resetParams() for examples.
   1.559 +    ///
   1.560 +    /// \return <tt>(*this)</tt>
   1.561 +    ///
   1.562 +    /// \see resetParams(), run()
   1.563 +    CapacityScaling& reset() {
   1.564 +      // Resize vectors
   1.565 +      _node_num = countNodes(_graph);
   1.566 +      _arc_num = countArcs(_graph);
   1.567 +      _res_arc_num = 2 * (_arc_num + _node_num);
   1.568 +      _root = _node_num;
   1.569 +      ++_node_num;
   1.570 +
   1.571 +      _first_out.resize(_node_num + 1);
   1.572 +      _forward.resize(_res_arc_num);
   1.573 +      _source.resize(_res_arc_num);
   1.574 +      _target.resize(_res_arc_num);
   1.575 +      _reverse.resize(_res_arc_num);
   1.576 +
   1.577 +      _lower.resize(_res_arc_num);
   1.578 +      _upper.resize(_res_arc_num);
   1.579 +      _cost.resize(_res_arc_num);
   1.580 +      _supply.resize(_node_num);
   1.581 +
   1.582 +      _res_cap.resize(_res_arc_num);
   1.583 +      _pi.resize(_node_num);
   1.584 +      _excess.resize(_node_num);
   1.585 +      _pred.resize(_node_num);
   1.586 +
   1.587 +      // Copy the graph
   1.588 +      int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
   1.589 +      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   1.590 +        _node_id[n] = i;
   1.591 +      }
   1.592 +      i = 0;
   1.593 +      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
   1.594 +        _first_out[i] = j;
   1.595 +        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
   1.596 +          _arc_idf[a] = j;
   1.597 +          _forward[j] = true;
   1.598 +          _source[j] = i;
   1.599 +          _target[j] = _node_id[_graph.runningNode(a)];
   1.600 +        }
   1.601 +        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
   1.602 +          _arc_idb[a] = j;
   1.603 +          _forward[j] = false;
   1.604 +          _source[j] = i;
   1.605 +          _target[j] = _node_id[_graph.runningNode(a)];
   1.606 +        }
   1.607 +        _forward[j] = false;
   1.608 +        _source[j] = i;
   1.609 +        _target[j] = _root;
   1.610 +        _reverse[j] = k;
   1.611 +        _forward[k] = true;
   1.612 +        _source[k] = _root;
   1.613 +        _target[k] = i;
   1.614 +        _reverse[k] = j;
   1.615 +        ++j; ++k;
   1.616 +      }
   1.617 +      _first_out[i] = j;
   1.618 +      _first_out[_node_num] = k;
   1.619 +      for (ArcIt a(_graph); a != INVALID; ++a) {
   1.620 +        int fi = _arc_idf[a];
   1.621 +        int bi = _arc_idb[a];
   1.622 +        _reverse[fi] = bi;
   1.623 +        _reverse[bi] = fi;
   1.624 +      }
   1.625 +
   1.626 +      // Reset parameters
   1.627 +      resetParams();
   1.628 +      return *this;
   1.629 +    }
   1.630 +
   1.631 +    /// @}
   1.632 +
   1.633 +    /// \name Query Functions
   1.634 +    /// The results of the algorithm can be obtained using these
   1.635 +    /// functions.\n
   1.636 +    /// The \ref run() function must be called before using them.
   1.637 +
   1.638 +    /// @{
   1.639 +
   1.640 +    /// \brief Return the total cost of the found flow.
   1.641 +    ///
   1.642 +    /// This function returns the total cost of the found flow.
   1.643 +    /// Its complexity is O(e).
   1.644 +    ///
   1.645 +    /// \note The return type of the function can be specified as a
   1.646 +    /// template parameter. For example,
   1.647 +    /// \code
   1.648 +    ///   cs.totalCost<double>();
   1.649 +    /// \endcode
   1.650 +    /// It is useful if the total cost cannot be stored in the \c Cost
   1.651 +    /// type of the algorithm, which is the default return type of the
   1.652 +    /// function.
   1.653 +    ///
   1.654 +    /// \pre \ref run() must be called before using this function.
   1.655 +    template <typename Number>
   1.656 +    Number totalCost() const {
   1.657 +      Number c = 0;
   1.658 +      for (ArcIt a(_graph); a != INVALID; ++a) {
   1.659 +        int i = _arc_idb[a];
   1.660 +        c += static_cast<Number>(_res_cap[i]) *
   1.661 +             (-static_cast<Number>(_cost[i]));
   1.662 +      }
   1.663 +      return c;
   1.664 +    }
   1.665 +
   1.666 +#ifndef DOXYGEN
   1.667 +    Cost totalCost() const {
   1.668 +      return totalCost<Cost>();
   1.669 +    }
   1.670 +#endif
   1.671 +
   1.672 +    /// \brief Return the flow on the given arc.
   1.673 +    ///
   1.674 +    /// This function returns the flow on the given arc.
   1.675 +    ///
   1.676 +    /// \pre \ref run() must be called before using this function.
   1.677 +    Value flow(const Arc& a) const {
   1.678 +      return _res_cap[_arc_idb[a]];
   1.679 +    }
   1.680 +
   1.681 +    /// \brief Return the flow map (the primal solution).
   1.682 +    ///
   1.683 +    /// This function copies the flow value on each arc into the given
   1.684 +    /// map. The \c Value type of the algorithm must be convertible to
   1.685 +    /// the \c Value type of the map.
   1.686 +    ///
   1.687 +    /// \pre \ref run() must be called before using this function.
   1.688 +    template <typename FlowMap>
   1.689 +    void flowMap(FlowMap &map) const {
   1.690 +      for (ArcIt a(_graph); a != INVALID; ++a) {
   1.691 +        map.set(a, _res_cap[_arc_idb[a]]);
   1.692 +      }
   1.693 +    }
   1.694 +
   1.695 +    /// \brief Return the potential (dual value) of the given node.
   1.696 +    ///
   1.697 +    /// This function returns the potential (dual value) of the
   1.698 +    /// given node.
   1.699 +    ///
   1.700 +    /// \pre \ref run() must be called before using this function.
   1.701 +    Cost potential(const Node& n) const {
   1.702 +      return _pi[_node_id[n]];
   1.703 +    }
   1.704 +
   1.705 +    /// \brief Return the potential map (the dual solution).
   1.706 +    ///
   1.707 +    /// This function copies the potential (dual value) of each node
   1.708 +    /// into the given map.
   1.709 +    /// The \c Cost type of the algorithm must be convertible to the
   1.710 +    /// \c Value type of the map.
   1.711 +    ///
   1.712 +    /// \pre \ref run() must be called before using this function.
   1.713 +    template <typename PotentialMap>
   1.714 +    void potentialMap(PotentialMap &map) const {
   1.715 +      for (NodeIt n(_graph); n != INVALID; ++n) {
   1.716 +        map.set(n, _pi[_node_id[n]]);
   1.717 +      }
   1.718 +    }
   1.719 +
   1.720 +    /// @}
   1.721 +
   1.722 +  private:
   1.723 +
   1.724 +    // Initialize the algorithm
   1.725 +    ProblemType init() {
   1.726 +      if (_node_num <= 1) return INFEASIBLE;
   1.727 +
   1.728 +      // Check the sum of supply values
   1.729 +      _sum_supply = 0;
   1.730 +      for (int i = 0; i != _root; ++i) {
   1.731 +        _sum_supply += _supply[i];
   1.732 +      }
   1.733 +      if (_sum_supply > 0) return INFEASIBLE;
   1.734 +
   1.735 +      // Initialize vectors
   1.736 +      for (int i = 0; i != _root; ++i) {
   1.737 +        _pi[i] = 0;
   1.738 +        _excess[i] = _supply[i];
   1.739 +      }
   1.740 +
   1.741 +      // Remove non-zero lower bounds
   1.742 +      const Value MAX = std::numeric_limits<Value>::max();
   1.743 +      int last_out;
   1.744 +      if (_have_lower) {
   1.745 +        for (int i = 0; i != _root; ++i) {
   1.746 +          last_out = _first_out[i+1];
   1.747 +          for (int j = _first_out[i]; j != last_out; ++j) {
   1.748 +            if (_forward[j]) {
   1.749 +              Value c = _lower[j];
   1.750 +              if (c >= 0) {
   1.751 +                _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
   1.752 +              } else {
   1.753 +                _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
   1.754 +              }
   1.755 +              _excess[i] -= c;
   1.756 +              _excess[_target[j]] += c;
   1.757 +            } else {
   1.758 +              _res_cap[j] = 0;
   1.759 +            }
   1.760 +          }
   1.761 +        }
   1.762 +      } else {
   1.763 +        for (int j = 0; j != _res_arc_num; ++j) {
   1.764 +          _res_cap[j] = _forward[j] ? _upper[j] : 0;
   1.765 +        }
   1.766 +      }
   1.767 +
   1.768 +      // Handle negative costs
   1.769 +      for (int i = 0; i != _root; ++i) {
   1.770 +        last_out = _first_out[i+1] - 1;
   1.771 +        for (int j = _first_out[i]; j != last_out; ++j) {
   1.772 +          Value rc = _res_cap[j];
   1.773 +          if (_cost[j] < 0 && rc > 0) {
   1.774 +            if (rc >= MAX) return UNBOUNDED;
   1.775 +            _excess[i] -= rc;
   1.776 +            _excess[_target[j]] += rc;
   1.777 +            _res_cap[j] = 0;
   1.778 +            _res_cap[_reverse[j]] += rc;
   1.779 +          }
   1.780 +        }
   1.781 +      }
   1.782 +
   1.783 +      // Handle GEQ supply type
   1.784 +      if (_sum_supply < 0) {
   1.785 +        _pi[_root] = 0;
   1.786 +        _excess[_root] = -_sum_supply;
   1.787 +        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   1.788 +          int ra = _reverse[a];
   1.789 +          _res_cap[a] = -_sum_supply + 1;
   1.790 +          _res_cap[ra] = 0;
   1.791 +          _cost[a] = 0;
   1.792 +          _cost[ra] = 0;
   1.793 +        }
   1.794 +      } else {
   1.795 +        _pi[_root] = 0;
   1.796 +        _excess[_root] = 0;
   1.797 +        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
   1.798 +          int ra = _reverse[a];
   1.799 +          _res_cap[a] = 1;
   1.800 +          _res_cap[ra] = 0;
   1.801 +          _cost[a] = 0;
   1.802 +          _cost[ra] = 0;
   1.803 +        }
   1.804 +      }
   1.805 +
   1.806 +      // Initialize delta value
   1.807 +      if (_factor > 1) {
   1.808 +        // With scaling
   1.809 +        Value max_sup = 0, max_dem = 0, max_cap = 0;
   1.810 +        for (int i = 0; i != _root; ++i) {
   1.811 +          Value ex = _excess[i];
   1.812 +          if ( ex > max_sup) max_sup =  ex;
   1.813 +          if (-ex > max_dem) max_dem = -ex;
   1.814 +          int last_out = _first_out[i+1] - 1;
   1.815 +          for (int j = _first_out[i]; j != last_out; ++j) {
   1.816 +            if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
   1.817 +          }
   1.818 +        }
   1.819 +        max_sup = std::min(std::min(max_sup, max_dem), max_cap);
   1.820 +        for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
   1.821 +      } else {
   1.822 +        // Without scaling
   1.823 +        _delta = 1;
   1.824 +      }
   1.825 +
   1.826 +      return OPTIMAL;
   1.827 +    }
   1.828 +
   1.829 +    ProblemType start() {
   1.830 +      // Execute the algorithm
   1.831 +      ProblemType pt;
   1.832 +      if (_delta > 1)
   1.833 +        pt = startWithScaling();
   1.834 +      else
   1.835 +        pt = startWithoutScaling();
   1.836 +
   1.837 +      // Handle non-zero lower bounds
   1.838 +      if (_have_lower) {
   1.839 +        int limit = _first_out[_root];
   1.840 +        for (int j = 0; j != limit; ++j) {
   1.841 +          if (!_forward[j]) _res_cap[j] += _lower[j];
   1.842 +        }
   1.843 +      }
   1.844 +
   1.845 +      // Shift potentials if necessary
   1.846 +      Cost pr = _pi[_root];
   1.847 +      if (_sum_supply < 0 || pr > 0) {
   1.848 +        for (int i = 0; i != _node_num; ++i) {
   1.849 +          _pi[i] -= pr;
   1.850 +        }
   1.851 +      }
   1.852 +
   1.853 +      return pt;
   1.854 +    }
   1.855 +
   1.856 +    // Execute the capacity scaling algorithm
   1.857 +    ProblemType startWithScaling() {
   1.858 +      // Perform capacity scaling phases
   1.859 +      int s, t;
   1.860 +      ResidualDijkstra _dijkstra(*this);
   1.861 +      while (true) {
   1.862 +        // Saturate all arcs not satisfying the optimality condition
   1.863 +        int last_out;
   1.864 +        for (int u = 0; u != _node_num; ++u) {
   1.865 +          last_out = _sum_supply < 0 ?
   1.866 +            _first_out[u+1] : _first_out[u+1] - 1;
   1.867 +          for (int a = _first_out[u]; a != last_out; ++a) {
   1.868 +            int v = _target[a];
   1.869 +            Cost c = _cost[a] + _pi[u] - _pi[v];
   1.870 +            Value rc = _res_cap[a];
   1.871 +            if (c < 0 && rc >= _delta) {
   1.872 +              _excess[u] -= rc;
   1.873 +              _excess[v] += rc;
   1.874 +              _res_cap[a] = 0;
   1.875 +              _res_cap[_reverse[a]] += rc;
   1.876 +            }
   1.877 +          }
   1.878 +        }
   1.879 +
   1.880 +        // Find excess nodes and deficit nodes
   1.881 +        _excess_nodes.clear();
   1.882 +        _deficit_nodes.clear();
   1.883 +        for (int u = 0; u != _node_num; ++u) {
   1.884 +          Value ex = _excess[u];
   1.885 +          if (ex >=  _delta) _excess_nodes.push_back(u);
   1.886 +          if (ex <= -_delta) _deficit_nodes.push_back(u);
   1.887 +        }
   1.888 +        int next_node = 0, next_def_node = 0;
   1.889 +
   1.890 +        // Find augmenting shortest paths
   1.891 +        while (next_node < int(_excess_nodes.size())) {
   1.892 +          // Check deficit nodes
   1.893 +          if (_delta > 1) {
   1.894 +            bool delta_deficit = false;
   1.895 +            for ( ; next_def_node < int(_deficit_nodes.size());
   1.896 +                    ++next_def_node ) {
   1.897 +              if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
   1.898 +                delta_deficit = true;
   1.899 +                break;
   1.900 +              }
   1.901 +            }
   1.902 +            if (!delta_deficit) break;
   1.903 +          }
   1.904 +
   1.905 +          // Run Dijkstra in the residual network
   1.906 +          s = _excess_nodes[next_node];
   1.907 +          if ((t = _dijkstra.run(s, _delta)) == -1) {
   1.908 +            if (_delta > 1) {
   1.909 +              ++next_node;
   1.910 +              continue;
   1.911 +            }
   1.912 +            return INFEASIBLE;
   1.913 +          }
   1.914 +
   1.915 +          // Augment along a shortest path from s to t
   1.916 +          Value d = std::min(_excess[s], -_excess[t]);
   1.917 +          int u = t;
   1.918 +          int a;
   1.919 +          if (d > _delta) {
   1.920 +            while ((a = _pred[u]) != -1) {
   1.921 +              if (_res_cap[a] < d) d = _res_cap[a];
   1.922 +              u = _source[a];
   1.923 +            }
   1.924 +          }
   1.925 +          u = t;
   1.926 +          while ((a = _pred[u]) != -1) {
   1.927 +            _res_cap[a] -= d;
   1.928 +            _res_cap[_reverse[a]] += d;
   1.929 +            u = _source[a];
   1.930 +          }
   1.931 +          _excess[s] -= d;
   1.932 +          _excess[t] += d;
   1.933 +
   1.934 +          if (_excess[s] < _delta) ++next_node;
   1.935 +        }
   1.936 +
   1.937 +        if (_delta == 1) break;
   1.938 +        _delta = _delta <= _factor ? 1 : _delta / _factor;
   1.939 +      }
   1.940 +
   1.941 +      return OPTIMAL;
   1.942 +    }
   1.943 +
   1.944 +    // Execute the successive shortest path algorithm
   1.945 +    ProblemType startWithoutScaling() {
   1.946 +      // Find excess nodes
   1.947 +      _excess_nodes.clear();
   1.948 +      for (int i = 0; i != _node_num; ++i) {
   1.949 +        if (_excess[i] > 0) _excess_nodes.push_back(i);
   1.950 +      }
   1.951 +      if (_excess_nodes.size() == 0) return OPTIMAL;
   1.952 +      int next_node = 0;
   1.953 +
   1.954 +      // Find shortest paths
   1.955 +      int s, t;
   1.956 +      ResidualDijkstra _dijkstra(*this);
   1.957 +      while ( _excess[_excess_nodes[next_node]] > 0 ||
   1.958 +              ++next_node < int(_excess_nodes.size()) )
   1.959 +      {
   1.960 +        // Run Dijkstra in the residual network
   1.961 +        s = _excess_nodes[next_node];
   1.962 +        if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
   1.963 +
   1.964 +        // Augment along a shortest path from s to t
   1.965 +        Value d = std::min(_excess[s], -_excess[t]);
   1.966 +        int u = t;
   1.967 +        int a;
   1.968 +        if (d > 1) {
   1.969 +          while ((a = _pred[u]) != -1) {
   1.970 +            if (_res_cap[a] < d) d = _res_cap[a];
   1.971 +            u = _source[a];
   1.972 +          }
   1.973 +        }
   1.974 +        u = t;
   1.975 +        while ((a = _pred[u]) != -1) {
   1.976 +          _res_cap[a] -= d;
   1.977 +          _res_cap[_reverse[a]] += d;
   1.978 +          u = _source[a];
   1.979 +        }
   1.980 +        _excess[s] -= d;
   1.981 +        _excess[t] += d;
   1.982 +      }
   1.983 +
   1.984 +      return OPTIMAL;
   1.985 +    }
   1.986 +
   1.987 +  }; //class CapacityScaling
   1.988 +
   1.989 +  ///@}
   1.990 +
   1.991 +} //namespace lemon
   1.992 +
   1.993 +#endif //LEMON_CAPACITY_SCALING_H