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