lemon/capacity_scaling.h
author Peter Kovacs <kpeter@inf.elte.hu>
Sat, 20 Feb 2010 18:39:03 +0100
changeset 910 f3bc4e9b5f3a
parent 887 072ec8120958
child 911 2914b6f0fde0
permissions -rw-r--r--
New heuristics for MCF algorithms (#340)
and some implementation improvements.

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