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