lemon/cost_scaling.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 12 Nov 2009 23:49:05 +0100
changeset 878 4b1b378823dc
parent 876 3b53491bf643
child 879 25804ef35064
permissions -rw-r--r--
Small doc improvements + unifications in MCF classes (#180)
kpeter@874
     1
/* -*- C++ -*-
kpeter@874
     2
 *
kpeter@874
     3
 * This file is a part of LEMON, a generic C++ optimization library
kpeter@874
     4
 *
kpeter@874
     5
 * Copyright (C) 2003-2008
kpeter@874
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@874
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@874
     8
 *
kpeter@874
     9
 * Permission to use, modify and distribute this software is granted
kpeter@874
    10
 * provided that this copyright notice appears in all copies. For
kpeter@874
    11
 * precise terms see the accompanying LICENSE file.
kpeter@874
    12
 *
kpeter@874
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@874
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@874
    15
 * purpose.
kpeter@874
    16
 *
kpeter@874
    17
 */
kpeter@874
    18
kpeter@874
    19
#ifndef LEMON_COST_SCALING_H
kpeter@874
    20
#define LEMON_COST_SCALING_H
kpeter@874
    21
kpeter@874
    22
/// \ingroup min_cost_flow_algs
kpeter@874
    23
/// \file
kpeter@874
    24
/// \brief Cost scaling algorithm for finding a minimum cost flow.
kpeter@874
    25
kpeter@874
    26
#include <vector>
kpeter@874
    27
#include <deque>
kpeter@874
    28
#include <limits>
kpeter@874
    29
kpeter@874
    30
#include <lemon/core.h>
kpeter@874
    31
#include <lemon/maps.h>
kpeter@874
    32
#include <lemon/math.h>
kpeter@875
    33
#include <lemon/static_graph.h>
kpeter@874
    34
#include <lemon/circulation.h>
kpeter@874
    35
#include <lemon/bellman_ford.h>
kpeter@874
    36
kpeter@874
    37
namespace lemon {
kpeter@874
    38
kpeter@875
    39
  /// \brief Default traits class of CostScaling algorithm.
kpeter@875
    40
  ///
kpeter@875
    41
  /// Default traits class of CostScaling algorithm.
kpeter@875
    42
  /// \tparam GR Digraph type.
kpeter@878
    43
  /// \tparam V The number type used for flow amounts, capacity bounds
kpeter@875
    44
  /// and supply values. By default it is \c int.
kpeter@878
    45
  /// \tparam C The number type used for costs and potentials.
kpeter@875
    46
  /// By default it is the same as \c V.
kpeter@875
    47
#ifdef DOXYGEN
kpeter@875
    48
  template <typename GR, typename V = int, typename C = V>
kpeter@875
    49
#else
kpeter@875
    50
  template < typename GR, typename V = int, typename C = V,
kpeter@875
    51
             bool integer = std::numeric_limits<C>::is_integer >
kpeter@875
    52
#endif
kpeter@875
    53
  struct CostScalingDefaultTraits
kpeter@875
    54
  {
kpeter@875
    55
    /// The type of the digraph
kpeter@875
    56
    typedef GR Digraph;
kpeter@875
    57
    /// The type of the flow amounts, capacity bounds and supply values
kpeter@875
    58
    typedef V Value;
kpeter@875
    59
    /// The type of the arc costs
kpeter@875
    60
    typedef C Cost;
kpeter@875
    61
kpeter@875
    62
    /// \brief The large cost type used for internal computations
kpeter@875
    63
    ///
kpeter@875
    64
    /// The large cost type used for internal computations.
kpeter@875
    65
    /// It is \c long \c long if the \c Cost type is integer,
kpeter@875
    66
    /// otherwise it is \c double.
kpeter@875
    67
    /// \c Cost must be convertible to \c LargeCost.
kpeter@875
    68
    typedef double LargeCost;
kpeter@875
    69
  };
kpeter@875
    70
kpeter@875
    71
  // Default traits class for integer cost types
kpeter@875
    72
  template <typename GR, typename V, typename C>
kpeter@875
    73
  struct CostScalingDefaultTraits<GR, V, C, true>
kpeter@875
    74
  {
kpeter@875
    75
    typedef GR Digraph;
kpeter@875
    76
    typedef V Value;
kpeter@875
    77
    typedef C Cost;
kpeter@875
    78
#ifdef LEMON_HAVE_LONG_LONG
kpeter@875
    79
    typedef long long LargeCost;
kpeter@875
    80
#else
kpeter@875
    81
    typedef long LargeCost;
kpeter@875
    82
#endif
kpeter@875
    83
  };
kpeter@875
    84
kpeter@875
    85
kpeter@874
    86
  /// \addtogroup min_cost_flow_algs
kpeter@874
    87
  /// @{
kpeter@874
    88
kpeter@875
    89
  /// \brief Implementation of the Cost Scaling algorithm for
kpeter@875
    90
  /// finding a \ref min_cost_flow "minimum cost flow".
kpeter@874
    91
  ///
kpeter@875
    92
  /// \ref CostScaling implements a cost scaling algorithm that performs
kpeter@875
    93
  /// push/augment and relabel operations for finding a minimum cost
kpeter@875
    94
  /// flow. It is an efficient primal-dual solution method, which
kpeter@875
    95
  /// can be viewed as the generalization of the \ref Preflow
kpeter@875
    96
  /// "preflow push-relabel" algorithm for the maximum flow problem.
kpeter@874
    97
  ///
kpeter@875
    98
  /// Most of the parameters of the problem (except for the digraph)
kpeter@875
    99
  /// can be given using separate functions, and the algorithm can be
kpeter@875
   100
  /// executed using the \ref run() function. If some parameters are not
kpeter@875
   101
  /// specified, then default values will be used.
kpeter@874
   102
  ///
kpeter@875
   103
  /// \tparam GR The digraph type the algorithm runs on.
kpeter@878
   104
  /// \tparam V The number type used for flow amounts, capacity bounds
kpeter@875
   105
  /// and supply values in the algorithm. By default it is \c int.
kpeter@878
   106
  /// \tparam C The number type used for costs and potentials in the
kpeter@875
   107
  /// algorithm. By default it is the same as \c V.
kpeter@874
   108
  ///
kpeter@878
   109
  /// \warning Both number types must be signed and all input data must
kpeter@875
   110
  /// be integer.
kpeter@875
   111
  /// \warning This algorithm does not support negative costs for such
kpeter@875
   112
  /// arcs that have infinite upper bound.
kpeter@876
   113
  ///
kpeter@876
   114
  /// \note %CostScaling provides three different internal methods,
kpeter@876
   115
  /// from which the most efficient one is used by default.
kpeter@876
   116
  /// For more information, see \ref Method.
kpeter@875
   117
#ifdef DOXYGEN
kpeter@875
   118
  template <typename GR, typename V, typename C, typename TR>
kpeter@875
   119
#else
kpeter@875
   120
  template < typename GR, typename V = int, typename C = V,
kpeter@875
   121
             typename TR = CostScalingDefaultTraits<GR, V, C> >
kpeter@875
   122
#endif
kpeter@874
   123
  class CostScaling
kpeter@874
   124
  {
kpeter@875
   125
  public:
kpeter@874
   126
kpeter@875
   127
    /// The type of the digraph
kpeter@875
   128
    typedef typename TR::Digraph Digraph;
kpeter@875
   129
    /// The type of the flow amounts, capacity bounds and supply values
kpeter@875
   130
    typedef typename TR::Value Value;
kpeter@875
   131
    /// The type of the arc costs
kpeter@875
   132
    typedef typename TR::Cost Cost;
kpeter@874
   133
kpeter@875
   134
    /// \brief The large cost type
kpeter@875
   135
    ///
kpeter@875
   136
    /// The large cost type used for internal computations.
kpeter@875
   137
    /// Using the \ref CostScalingDefaultTraits "default traits class",
kpeter@875
   138
    /// it is \c long \c long if the \c Cost type is integer,
kpeter@875
   139
    /// otherwise it is \c double.
kpeter@875
   140
    typedef typename TR::LargeCost LargeCost;
kpeter@874
   141
kpeter@875
   142
    /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
kpeter@875
   143
    typedef TR Traits;
kpeter@874
   144
kpeter@874
   145
  public:
kpeter@874
   146
kpeter@875
   147
    /// \brief Problem type constants for the \c run() function.
kpeter@875
   148
    ///
kpeter@875
   149
    /// Enum type containing the problem type constants that can be
kpeter@875
   150
    /// returned by the \ref run() function of the algorithm.
kpeter@875
   151
    enum ProblemType {
kpeter@875
   152
      /// The problem has no feasible solution (flow).
kpeter@875
   153
      INFEASIBLE,
kpeter@875
   154
      /// The problem has optimal solution (i.e. it is feasible and
kpeter@875
   155
      /// bounded), and the algorithm has found optimal flow and node
kpeter@875
   156
      /// potentials (primal and dual solutions).
kpeter@875
   157
      OPTIMAL,
kpeter@875
   158
      /// The digraph contains an arc of negative cost and infinite
kpeter@875
   159
      /// upper bound. It means that the objective function is unbounded
kpeter@878
   160
      /// on that arc, however, note that it could actually be bounded
kpeter@875
   161
      /// over the feasible flows, but this algroithm cannot handle
kpeter@875
   162
      /// these cases.
kpeter@875
   163
      UNBOUNDED
kpeter@875
   164
    };
kpeter@874
   165
kpeter@876
   166
    /// \brief Constants for selecting the internal method.
kpeter@876
   167
    ///
kpeter@876
   168
    /// Enum type containing constants for selecting the internal method
kpeter@876
   169
    /// for the \ref run() function.
kpeter@876
   170
    ///
kpeter@876
   171
    /// \ref CostScaling provides three internal methods that differ mainly
kpeter@876
   172
    /// in their base operations, which are used in conjunction with the
kpeter@876
   173
    /// relabel operation.
kpeter@876
   174
    /// By default, the so called \ref PARTIAL_AUGMENT
kpeter@876
   175
    /// "Partial Augment-Relabel" method is used, which proved to be
kpeter@876
   176
    /// the most efficient and the most robust on various test inputs.
kpeter@876
   177
    /// However, the other methods can be selected using the \ref run()
kpeter@876
   178
    /// function with the proper parameter.
kpeter@876
   179
    enum Method {
kpeter@876
   180
      /// Local push operations are used, i.e. flow is moved only on one
kpeter@876
   181
      /// admissible arc at once.
kpeter@876
   182
      PUSH,
kpeter@876
   183
      /// Augment operations are used, i.e. flow is moved on admissible
kpeter@876
   184
      /// paths from a node with excess to a node with deficit.
kpeter@876
   185
      AUGMENT,
kpeter@876
   186
      /// Partial augment operations are used, i.e. flow is moved on 
kpeter@876
   187
      /// admissible paths started from a node with excess, but the
kpeter@876
   188
      /// lengths of these paths are limited. This method can be viewed
kpeter@876
   189
      /// as a combined version of the previous two operations.
kpeter@876
   190
      PARTIAL_AUGMENT
kpeter@876
   191
    };
kpeter@876
   192
kpeter@874
   193
  private:
kpeter@874
   194
kpeter@875
   195
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
kpeter@874
   196
kpeter@875
   197
    typedef std::vector<int> IntVector;
kpeter@875
   198
    typedef std::vector<char> BoolVector;
kpeter@875
   199
    typedef std::vector<Value> ValueVector;
kpeter@875
   200
    typedef std::vector<Cost> CostVector;
kpeter@875
   201
    typedef std::vector<LargeCost> LargeCostVector;
kpeter@874
   202
kpeter@875
   203
  private:
kpeter@875
   204
  
kpeter@875
   205
    template <typename KT, typename VT>
kpeter@875
   206
    class VectorMap {
kpeter@874
   207
    public:
kpeter@875
   208
      typedef KT Key;
kpeter@875
   209
      typedef VT Value;
kpeter@875
   210
      
kpeter@875
   211
      VectorMap(std::vector<Value>& v) : _v(v) {}
kpeter@875
   212
      
kpeter@875
   213
      const Value& operator[](const Key& key) const {
kpeter@875
   214
        return _v[StaticDigraph::id(key)];
kpeter@874
   215
      }
kpeter@874
   216
kpeter@875
   217
      Value& operator[](const Key& key) {
kpeter@875
   218
        return _v[StaticDigraph::id(key)];
kpeter@875
   219
      }
kpeter@875
   220
      
kpeter@875
   221
      void set(const Key& key, const Value& val) {
kpeter@875
   222
        _v[StaticDigraph::id(key)] = val;
kpeter@874
   223
      }
kpeter@874
   224
kpeter@875
   225
    private:
kpeter@875
   226
      std::vector<Value>& _v;
kpeter@875
   227
    };
kpeter@875
   228
kpeter@875
   229
    typedef VectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
kpeter@875
   230
    typedef VectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
kpeter@874
   231
kpeter@874
   232
  private:
kpeter@874
   233
kpeter@875
   234
    // Data related to the underlying digraph
kpeter@875
   235
    const GR &_graph;
kpeter@875
   236
    int _node_num;
kpeter@875
   237
    int _arc_num;
kpeter@875
   238
    int _res_node_num;
kpeter@875
   239
    int _res_arc_num;
kpeter@875
   240
    int _root;
kpeter@874
   241
kpeter@875
   242
    // Parameters of the problem
kpeter@875
   243
    bool _have_lower;
kpeter@875
   244
    Value _sum_supply;
kpeter@874
   245
kpeter@875
   246
    // Data structures for storing the digraph
kpeter@875
   247
    IntNodeMap _node_id;
kpeter@875
   248
    IntArcMap _arc_idf;
kpeter@875
   249
    IntArcMap _arc_idb;
kpeter@875
   250
    IntVector _first_out;
kpeter@875
   251
    BoolVector _forward;
kpeter@875
   252
    IntVector _source;
kpeter@875
   253
    IntVector _target;
kpeter@875
   254
    IntVector _reverse;
kpeter@875
   255
kpeter@875
   256
    // Node and arc data
kpeter@875
   257
    ValueVector _lower;
kpeter@875
   258
    ValueVector _upper;
kpeter@875
   259
    CostVector _scost;
kpeter@875
   260
    ValueVector _supply;
kpeter@875
   261
kpeter@875
   262
    ValueVector _res_cap;
kpeter@875
   263
    LargeCostVector _cost;
kpeter@875
   264
    LargeCostVector _pi;
kpeter@875
   265
    ValueVector _excess;
kpeter@875
   266
    IntVector _next_out;
kpeter@875
   267
    std::deque<int> _active_nodes;
kpeter@875
   268
kpeter@875
   269
    // Data for scaling
kpeter@875
   270
    LargeCost _epsilon;
kpeter@874
   271
    int _alpha;
kpeter@874
   272
kpeter@875
   273
    // Data for a StaticDigraph structure
kpeter@875
   274
    typedef std::pair<int, int> IntPair;
kpeter@875
   275
    StaticDigraph _sgr;
kpeter@875
   276
    std::vector<IntPair> _arc_vec;
kpeter@875
   277
    std::vector<LargeCost> _cost_vec;
kpeter@875
   278
    LargeCostArcMap _cost_map;
kpeter@875
   279
    LargeCostNodeMap _pi_map;
kpeter@875
   280
  
kpeter@875
   281
  public:
kpeter@875
   282
  
kpeter@875
   283
    /// \brief Constant for infinite upper bounds (capacities).
kpeter@875
   284
    ///
kpeter@875
   285
    /// Constant for infinite upper bounds (capacities).
kpeter@875
   286
    /// It is \c std::numeric_limits<Value>::infinity() if available,
kpeter@875
   287
    /// \c std::numeric_limits<Value>::max() otherwise.
kpeter@875
   288
    const Value INF;
kpeter@875
   289
kpeter@874
   290
  public:
kpeter@874
   291
kpeter@875
   292
    /// \name Named Template Parameters
kpeter@875
   293
    /// @{
kpeter@875
   294
kpeter@875
   295
    template <typename T>
kpeter@875
   296
    struct SetLargeCostTraits : public Traits {
kpeter@875
   297
      typedef T LargeCost;
kpeter@875
   298
    };
kpeter@875
   299
kpeter@875
   300
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@875
   301
    /// \c LargeCost type.
kpeter@874
   302
    ///
kpeter@875
   303
    /// \ref named-templ-param "Named parameter" for setting \c LargeCost
kpeter@875
   304
    /// type, which is used for internal computations in the algorithm.
kpeter@875
   305
    /// \c Cost must be convertible to \c LargeCost.
kpeter@875
   306
    template <typename T>
kpeter@875
   307
    struct SetLargeCost
kpeter@875
   308
      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
kpeter@875
   309
      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
kpeter@875
   310
    };
kpeter@875
   311
kpeter@875
   312
    /// @}
kpeter@875
   313
kpeter@875
   314
  public:
kpeter@875
   315
kpeter@875
   316
    /// \brief Constructor.
kpeter@874
   317
    ///
kpeter@875
   318
    /// The constructor of the class.
kpeter@875
   319
    ///
kpeter@875
   320
    /// \param graph The digraph the algorithm runs on.
kpeter@875
   321
    CostScaling(const GR& graph) :
kpeter@875
   322
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
kpeter@875
   323
      _cost_map(_cost_vec), _pi_map(_pi),
kpeter@875
   324
      INF(std::numeric_limits<Value>::has_infinity ?
kpeter@875
   325
          std::numeric_limits<Value>::infinity() :
kpeter@875
   326
          std::numeric_limits<Value>::max())
kpeter@874
   327
    {
kpeter@878
   328
      // Check the number types
kpeter@875
   329
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
kpeter@875
   330
        "The flow type of CostScaling must be signed");
kpeter@875
   331
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
kpeter@875
   332
        "The cost type of CostScaling must be signed");
kpeter@875
   333
kpeter@875
   334
      // Resize vectors
kpeter@875
   335
      _node_num = countNodes(_graph);
kpeter@875
   336
      _arc_num = countArcs(_graph);
kpeter@875
   337
      _res_node_num = _node_num + 1;
kpeter@875
   338
      _res_arc_num = 2 * (_arc_num + _node_num);
kpeter@875
   339
      _root = _node_num;
kpeter@875
   340
kpeter@875
   341
      _first_out.resize(_res_node_num + 1);
kpeter@875
   342
      _forward.resize(_res_arc_num);
kpeter@875
   343
      _source.resize(_res_arc_num);
kpeter@875
   344
      _target.resize(_res_arc_num);
kpeter@875
   345
      _reverse.resize(_res_arc_num);
kpeter@875
   346
kpeter@875
   347
      _lower.resize(_res_arc_num);
kpeter@875
   348
      _upper.resize(_res_arc_num);
kpeter@875
   349
      _scost.resize(_res_arc_num);
kpeter@875
   350
      _supply.resize(_res_node_num);
kpeter@874
   351
      
kpeter@875
   352
      _res_cap.resize(_res_arc_num);
kpeter@875
   353
      _cost.resize(_res_arc_num);
kpeter@875
   354
      _pi.resize(_res_node_num);
kpeter@875
   355
      _excess.resize(_res_node_num);
kpeter@875
   356
      _next_out.resize(_res_node_num);
kpeter@874
   357
kpeter@875
   358
      _arc_vec.reserve(_res_arc_num);
kpeter@875
   359
      _cost_vec.reserve(_res_arc_num);
kpeter@875
   360
kpeter@875
   361
      // Copy the graph
kpeter@875
   362
      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
kpeter@875
   363
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@875
   364
        _node_id[n] = i;
kpeter@875
   365
      }
kpeter@875
   366
      i = 0;
kpeter@875
   367
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@875
   368
        _first_out[i] = j;
kpeter@875
   369
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
kpeter@875
   370
          _arc_idf[a] = j;
kpeter@875
   371
          _forward[j] = true;
kpeter@875
   372
          _source[j] = i;
kpeter@875
   373
          _target[j] = _node_id[_graph.runningNode(a)];
kpeter@874
   374
        }
kpeter@875
   375
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
kpeter@875
   376
          _arc_idb[a] = j;
kpeter@875
   377
          _forward[j] = false;
kpeter@875
   378
          _source[j] = i;
kpeter@875
   379
          _target[j] = _node_id[_graph.runningNode(a)];
kpeter@875
   380
        }
kpeter@875
   381
        _forward[j] = false;
kpeter@875
   382
        _source[j] = i;
kpeter@875
   383
        _target[j] = _root;
kpeter@875
   384
        _reverse[j] = k;
kpeter@875
   385
        _forward[k] = true;
kpeter@875
   386
        _source[k] = _root;
kpeter@875
   387
        _target[k] = i;
kpeter@875
   388
        _reverse[k] = j;
kpeter@875
   389
        ++j; ++k;
kpeter@874
   390
      }
kpeter@875
   391
      _first_out[i] = j;
kpeter@875
   392
      _first_out[_res_node_num] = k;
kpeter@875
   393
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   394
        int fi = _arc_idf[a];
kpeter@875
   395
        int bi = _arc_idb[a];
kpeter@875
   396
        _reverse[fi] = bi;
kpeter@875
   397
        _reverse[bi] = fi;
kpeter@875
   398
      }
kpeter@875
   399
      
kpeter@875
   400
      // Reset parameters
kpeter@875
   401
      reset();
kpeter@874
   402
    }
kpeter@874
   403
kpeter@875
   404
    /// \name Parameters
kpeter@875
   405
    /// The parameters of the algorithm can be specified using these
kpeter@875
   406
    /// functions.
kpeter@875
   407
kpeter@875
   408
    /// @{
kpeter@875
   409
kpeter@875
   410
    /// \brief Set the lower bounds on the arcs.
kpeter@874
   411
    ///
kpeter@875
   412
    /// This function sets the lower bounds on the arcs.
kpeter@875
   413
    /// If it is not used before calling \ref run(), the lower bounds
kpeter@875
   414
    /// will be set to zero on all arcs.
kpeter@874
   415
    ///
kpeter@875
   416
    /// \param map An arc map storing the lower bounds.
kpeter@875
   417
    /// Its \c Value type must be convertible to the \c Value type
kpeter@875
   418
    /// of the algorithm.
kpeter@875
   419
    ///
kpeter@875
   420
    /// \return <tt>(*this)</tt>
kpeter@875
   421
    template <typename LowerMap>
kpeter@875
   422
    CostScaling& lowerMap(const LowerMap& map) {
kpeter@875
   423
      _have_lower = true;
kpeter@875
   424
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   425
        _lower[_arc_idf[a]] = map[a];
kpeter@875
   426
        _lower[_arc_idb[a]] = map[a];
kpeter@874
   427
      }
kpeter@874
   428
      return *this;
kpeter@874
   429
    }
kpeter@874
   430
kpeter@875
   431
    /// \brief Set the upper bounds (capacities) on the arcs.
kpeter@874
   432
    ///
kpeter@875
   433
    /// This function sets the upper bounds (capacities) on the arcs.
kpeter@875
   434
    /// If it is not used before calling \ref run(), the upper bounds
kpeter@875
   435
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
kpeter@878
   436
    /// unbounded from above).
kpeter@874
   437
    ///
kpeter@875
   438
    /// \param map An arc map storing the upper bounds.
kpeter@875
   439
    /// Its \c Value type must be convertible to the \c Value type
kpeter@875
   440
    /// of the algorithm.
kpeter@875
   441
    ///
kpeter@875
   442
    /// \return <tt>(*this)</tt>
kpeter@875
   443
    template<typename UpperMap>
kpeter@875
   444
    CostScaling& upperMap(const UpperMap& map) {
kpeter@875
   445
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   446
        _upper[_arc_idf[a]] = map[a];
kpeter@874
   447
      }
kpeter@874
   448
      return *this;
kpeter@874
   449
    }
kpeter@874
   450
kpeter@875
   451
    /// \brief Set the costs of the arcs.
kpeter@875
   452
    ///
kpeter@875
   453
    /// This function sets the costs of the arcs.
kpeter@875
   454
    /// If it is not used before calling \ref run(), the costs
kpeter@875
   455
    /// will be set to \c 1 on all arcs.
kpeter@875
   456
    ///
kpeter@875
   457
    /// \param map An arc map storing the costs.
kpeter@875
   458
    /// Its \c Value type must be convertible to the \c Cost type
kpeter@875
   459
    /// of the algorithm.
kpeter@875
   460
    ///
kpeter@875
   461
    /// \return <tt>(*this)</tt>
kpeter@875
   462
    template<typename CostMap>
kpeter@875
   463
    CostScaling& costMap(const CostMap& map) {
kpeter@875
   464
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   465
        _scost[_arc_idf[a]] =  map[a];
kpeter@875
   466
        _scost[_arc_idb[a]] = -map[a];
kpeter@875
   467
      }
kpeter@875
   468
      return *this;
kpeter@875
   469
    }
kpeter@875
   470
kpeter@875
   471
    /// \brief Set the supply values of the nodes.
kpeter@875
   472
    ///
kpeter@875
   473
    /// This function sets the supply values of the nodes.
kpeter@875
   474
    /// If neither this function nor \ref stSupply() is used before
kpeter@875
   475
    /// calling \ref run(), the supply of each node will be set to zero.
kpeter@875
   476
    ///
kpeter@875
   477
    /// \param map A node map storing the supply values.
kpeter@875
   478
    /// Its \c Value type must be convertible to the \c Value type
kpeter@875
   479
    /// of the algorithm.
kpeter@875
   480
    ///
kpeter@875
   481
    /// \return <tt>(*this)</tt>
kpeter@875
   482
    template<typename SupplyMap>
kpeter@875
   483
    CostScaling& supplyMap(const SupplyMap& map) {
kpeter@875
   484
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@875
   485
        _supply[_node_id[n]] = map[n];
kpeter@875
   486
      }
kpeter@875
   487
      return *this;
kpeter@875
   488
    }
kpeter@875
   489
kpeter@875
   490
    /// \brief Set single source and target nodes and a supply value.
kpeter@875
   491
    ///
kpeter@875
   492
    /// This function sets a single source node and a single target node
kpeter@875
   493
    /// and the required flow value.
kpeter@875
   494
    /// If neither this function nor \ref supplyMap() is used before
kpeter@875
   495
    /// calling \ref run(), the supply of each node will be set to zero.
kpeter@875
   496
    ///
kpeter@875
   497
    /// Using this function has the same effect as using \ref supplyMap()
kpeter@875
   498
    /// with such a map in which \c k is assigned to \c s, \c -k is
kpeter@875
   499
    /// assigned to \c t and all other nodes have zero supply value.
kpeter@875
   500
    ///
kpeter@875
   501
    /// \param s The source node.
kpeter@875
   502
    /// \param t The target node.
kpeter@875
   503
    /// \param k The required amount of flow from node \c s to node \c t
kpeter@875
   504
    /// (i.e. the supply of \c s and the demand of \c t).
kpeter@875
   505
    ///
kpeter@875
   506
    /// \return <tt>(*this)</tt>
kpeter@875
   507
    CostScaling& stSupply(const Node& s, const Node& t, Value k) {
kpeter@875
   508
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@875
   509
        _supply[i] = 0;
kpeter@875
   510
      }
kpeter@875
   511
      _supply[_node_id[s]] =  k;
kpeter@875
   512
      _supply[_node_id[t]] = -k;
kpeter@875
   513
      return *this;
kpeter@875
   514
    }
kpeter@875
   515
    
kpeter@875
   516
    /// @}
kpeter@875
   517
kpeter@874
   518
    /// \name Execution control
kpeter@875
   519
    /// The algorithm can be executed using \ref run().
kpeter@874
   520
kpeter@874
   521
    /// @{
kpeter@874
   522
kpeter@874
   523
    /// \brief Run the algorithm.
kpeter@874
   524
    ///
kpeter@875
   525
    /// This function runs the algorithm.
kpeter@875
   526
    /// The paramters can be specified using functions \ref lowerMap(),
kpeter@875
   527
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
kpeter@875
   528
    /// For example,
kpeter@875
   529
    /// \code
kpeter@875
   530
    ///   CostScaling<ListDigraph> cs(graph);
kpeter@875
   531
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
kpeter@875
   532
    ///     .supplyMap(sup).run();
kpeter@875
   533
    /// \endcode
kpeter@875
   534
    ///
kpeter@875
   535
    /// This function can be called more than once. All the parameters
kpeter@875
   536
    /// that have been given are kept for the next call, unless
kpeter@875
   537
    /// \ref reset() is called, thus only the modified parameters
kpeter@875
   538
    /// have to be set again. See \ref reset() for examples.
kpeter@876
   539
    /// However, the underlying digraph must not be modified after this
kpeter@876
   540
    /// class have been constructed, since it copies and extends the graph.
kpeter@874
   541
    ///
kpeter@876
   542
    /// \param method The internal method that will be used in the
kpeter@876
   543
    /// algorithm. For more information, see \ref Method.
kpeter@876
   544
    /// \param factor The cost scaling factor. It must be larger than one.
kpeter@874
   545
    ///
kpeter@875
   546
    /// \return \c INFEASIBLE if no feasible flow exists,
kpeter@875
   547
    /// \n \c OPTIMAL if the problem has optimal solution
kpeter@875
   548
    /// (i.e. it is feasible and bounded), and the algorithm has found
kpeter@875
   549
    /// optimal flow and node potentials (primal and dual solutions),
kpeter@875
   550
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
kpeter@875
   551
    /// and infinite upper bound. It means that the objective function
kpeter@878
   552
    /// is unbounded on that arc, however, note that it could actually be
kpeter@875
   553
    /// bounded over the feasible flows, but this algroithm cannot handle
kpeter@875
   554
    /// these cases.
kpeter@875
   555
    ///
kpeter@876
   556
    /// \see ProblemType, Method
kpeter@876
   557
    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
kpeter@876
   558
      _alpha = factor;
kpeter@875
   559
      ProblemType pt = init();
kpeter@875
   560
      if (pt != OPTIMAL) return pt;
kpeter@876
   561
      start(method);
kpeter@875
   562
      return OPTIMAL;
kpeter@875
   563
    }
kpeter@875
   564
kpeter@875
   565
    /// \brief Reset all the parameters that have been given before.
kpeter@875
   566
    ///
kpeter@875
   567
    /// This function resets all the paramaters that have been given
kpeter@875
   568
    /// before using functions \ref lowerMap(), \ref upperMap(),
kpeter@875
   569
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
kpeter@875
   570
    ///
kpeter@875
   571
    /// It is useful for multiple run() calls. If this function is not
kpeter@875
   572
    /// used, all the parameters given before are kept for the next
kpeter@875
   573
    /// \ref run() call.
kpeter@878
   574
    /// However, the underlying digraph must not be modified after this
kpeter@875
   575
    /// class have been constructed, since it copies and extends the graph.
kpeter@875
   576
    ///
kpeter@875
   577
    /// For example,
kpeter@875
   578
    /// \code
kpeter@875
   579
    ///   CostScaling<ListDigraph> cs(graph);
kpeter@875
   580
    ///
kpeter@875
   581
    ///   // First run
kpeter@875
   582
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
kpeter@875
   583
    ///     .supplyMap(sup).run();
kpeter@875
   584
    ///
kpeter@875
   585
    ///   // Run again with modified cost map (reset() is not called,
kpeter@875
   586
    ///   // so only the cost map have to be set again)
kpeter@875
   587
    ///   cost[e] += 100;
kpeter@875
   588
    ///   cs.costMap(cost).run();
kpeter@875
   589
    ///
kpeter@875
   590
    ///   // Run again from scratch using reset()
kpeter@875
   591
    ///   // (the lower bounds will be set to zero on all arcs)
kpeter@875
   592
    ///   cs.reset();
kpeter@875
   593
    ///   cs.upperMap(capacity).costMap(cost)
kpeter@875
   594
    ///     .supplyMap(sup).run();
kpeter@875
   595
    /// \endcode
kpeter@875
   596
    ///
kpeter@875
   597
    /// \return <tt>(*this)</tt>
kpeter@875
   598
    CostScaling& reset() {
kpeter@875
   599
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@875
   600
        _supply[i] = 0;
kpeter@874
   601
      }
kpeter@875
   602
      int limit = _first_out[_root];
kpeter@875
   603
      for (int j = 0; j != limit; ++j) {
kpeter@875
   604
        _lower[j] = 0;
kpeter@875
   605
        _upper[j] = INF;
kpeter@875
   606
        _scost[j] = _forward[j] ? 1 : -1;
kpeter@875
   607
      }
kpeter@875
   608
      for (int j = limit; j != _res_arc_num; ++j) {
kpeter@875
   609
        _lower[j] = 0;
kpeter@875
   610
        _upper[j] = INF;
kpeter@875
   611
        _scost[j] = 0;
kpeter@875
   612
        _scost[_reverse[j]] = 0;
kpeter@875
   613
      }      
kpeter@875
   614
      _have_lower = false;
kpeter@875
   615
      return *this;
kpeter@874
   616
    }
kpeter@874
   617
kpeter@874
   618
    /// @}
kpeter@874
   619
kpeter@874
   620
    /// \name Query Functions
kpeter@875
   621
    /// The results of the algorithm can be obtained using these
kpeter@874
   622
    /// functions.\n
kpeter@875
   623
    /// The \ref run() function must be called before using them.
kpeter@874
   624
kpeter@874
   625
    /// @{
kpeter@874
   626
kpeter@875
   627
    /// \brief Return the total cost of the found flow.
kpeter@874
   628
    ///
kpeter@875
   629
    /// This function returns the total cost of the found flow.
kpeter@875
   630
    /// Its complexity is O(e).
kpeter@875
   631
    ///
kpeter@875
   632
    /// \note The return type of the function can be specified as a
kpeter@875
   633
    /// template parameter. For example,
kpeter@875
   634
    /// \code
kpeter@875
   635
    ///   cs.totalCost<double>();
kpeter@875
   636
    /// \endcode
kpeter@875
   637
    /// It is useful if the total cost cannot be stored in the \c Cost
kpeter@875
   638
    /// type of the algorithm, which is the default return type of the
kpeter@875
   639
    /// function.
kpeter@874
   640
    ///
kpeter@874
   641
    /// \pre \ref run() must be called before using this function.
kpeter@875
   642
    template <typename Number>
kpeter@875
   643
    Number totalCost() const {
kpeter@875
   644
      Number c = 0;
kpeter@875
   645
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   646
        int i = _arc_idb[a];
kpeter@875
   647
        c += static_cast<Number>(_res_cap[i]) *
kpeter@875
   648
             (-static_cast<Number>(_scost[i]));
kpeter@875
   649
      }
kpeter@875
   650
      return c;
kpeter@874
   651
    }
kpeter@874
   652
kpeter@875
   653
#ifndef DOXYGEN
kpeter@875
   654
    Cost totalCost() const {
kpeter@875
   655
      return totalCost<Cost>();
kpeter@874
   656
    }
kpeter@875
   657
#endif
kpeter@874
   658
kpeter@874
   659
    /// \brief Return the flow on the given arc.
kpeter@874
   660
    ///
kpeter@875
   661
    /// This function returns the flow on the given arc.
kpeter@874
   662
    ///
kpeter@874
   663
    /// \pre \ref run() must be called before using this function.
kpeter@875
   664
    Value flow(const Arc& a) const {
kpeter@875
   665
      return _res_cap[_arc_idb[a]];
kpeter@874
   666
    }
kpeter@874
   667
kpeter@875
   668
    /// \brief Return the flow map (the primal solution).
kpeter@874
   669
    ///
kpeter@875
   670
    /// This function copies the flow value on each arc into the given
kpeter@875
   671
    /// map. The \c Value type of the algorithm must be convertible to
kpeter@875
   672
    /// the \c Value type of the map.
kpeter@874
   673
    ///
kpeter@874
   674
    /// \pre \ref run() must be called before using this function.
kpeter@875
   675
    template <typename FlowMap>
kpeter@875
   676
    void flowMap(FlowMap &map) const {
kpeter@875
   677
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   678
        map.set(a, _res_cap[_arc_idb[a]]);
kpeter@875
   679
      }
kpeter@874
   680
    }
kpeter@874
   681
kpeter@875
   682
    /// \brief Return the potential (dual value) of the given node.
kpeter@874
   683
    ///
kpeter@875
   684
    /// This function returns the potential (dual value) of the
kpeter@875
   685
    /// given node.
kpeter@874
   686
    ///
kpeter@874
   687
    /// \pre \ref run() must be called before using this function.
kpeter@875
   688
    Cost potential(const Node& n) const {
kpeter@875
   689
      return static_cast<Cost>(_pi[_node_id[n]]);
kpeter@875
   690
    }
kpeter@875
   691
kpeter@875
   692
    /// \brief Return the potential map (the dual solution).
kpeter@875
   693
    ///
kpeter@875
   694
    /// This function copies the potential (dual value) of each node
kpeter@875
   695
    /// into the given map.
kpeter@875
   696
    /// The \c Cost type of the algorithm must be convertible to the
kpeter@875
   697
    /// \c Value type of the map.
kpeter@875
   698
    ///
kpeter@875
   699
    /// \pre \ref run() must be called before using this function.
kpeter@875
   700
    template <typename PotentialMap>
kpeter@875
   701
    void potentialMap(PotentialMap &map) const {
kpeter@875
   702
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@875
   703
        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
kpeter@875
   704
      }
kpeter@874
   705
    }
kpeter@874
   706
kpeter@874
   707
    /// @}
kpeter@874
   708
kpeter@874
   709
  private:
kpeter@874
   710
kpeter@875
   711
    // Initialize the algorithm
kpeter@875
   712
    ProblemType init() {
kpeter@875
   713
      if (_res_node_num == 0) return INFEASIBLE;
kpeter@875
   714
kpeter@875
   715
      // Check the sum of supply values
kpeter@875
   716
      _sum_supply = 0;
kpeter@875
   717
      for (int i = 0; i != _root; ++i) {
kpeter@875
   718
        _sum_supply += _supply[i];
kpeter@874
   719
      }
kpeter@875
   720
      if (_sum_supply > 0) return INFEASIBLE;
kpeter@875
   721
      
kpeter@875
   722
kpeter@875
   723
      // Initialize vectors
kpeter@875
   724
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@875
   725
        _pi[i] = 0;
kpeter@875
   726
        _excess[i] = _supply[i];
kpeter@875
   727
      }
kpeter@875
   728
      
kpeter@875
   729
      // Remove infinite upper bounds and check negative arcs
kpeter@875
   730
      const Value MAX = std::numeric_limits<Value>::max();
kpeter@875
   731
      int last_out;
kpeter@875
   732
      if (_have_lower) {
kpeter@875
   733
        for (int i = 0; i != _root; ++i) {
kpeter@875
   734
          last_out = _first_out[i+1];
kpeter@875
   735
          for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@875
   736
            if (_forward[j]) {
kpeter@875
   737
              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
kpeter@875
   738
              if (c >= MAX) return UNBOUNDED;
kpeter@875
   739
              _excess[i] -= c;
kpeter@875
   740
              _excess[_target[j]] += c;
kpeter@875
   741
            }
kpeter@875
   742
          }
kpeter@875
   743
        }
kpeter@875
   744
      } else {
kpeter@875
   745
        for (int i = 0; i != _root; ++i) {
kpeter@875
   746
          last_out = _first_out[i+1];
kpeter@875
   747
          for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@875
   748
            if (_forward[j] && _scost[j] < 0) {
kpeter@875
   749
              Value c = _upper[j];
kpeter@875
   750
              if (c >= MAX) return UNBOUNDED;
kpeter@875
   751
              _excess[i] -= c;
kpeter@875
   752
              _excess[_target[j]] += c;
kpeter@875
   753
            }
kpeter@875
   754
          }
kpeter@875
   755
        }
kpeter@875
   756
      }
kpeter@875
   757
      Value ex, max_cap = 0;
kpeter@875
   758
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@875
   759
        ex = _excess[i];
kpeter@875
   760
        _excess[i] = 0;
kpeter@875
   761
        if (ex < 0) max_cap -= ex;
kpeter@875
   762
      }
kpeter@875
   763
      for (int j = 0; j != _res_arc_num; ++j) {
kpeter@875
   764
        if (_upper[j] >= MAX) _upper[j] = max_cap;
kpeter@874
   765
      }
kpeter@874
   766
kpeter@875
   767
      // Initialize the large cost vector and the epsilon parameter
kpeter@875
   768
      _epsilon = 0;
kpeter@875
   769
      LargeCost lc;
kpeter@875
   770
      for (int i = 0; i != _root; ++i) {
kpeter@875
   771
        last_out = _first_out[i+1];
kpeter@875
   772
        for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@875
   773
          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
kpeter@875
   774
          _cost[j] = lc;
kpeter@875
   775
          if (lc > _epsilon) _epsilon = lc;
kpeter@875
   776
        }
kpeter@875
   777
      }
kpeter@875
   778
      _epsilon /= _alpha;
kpeter@874
   779
kpeter@875
   780
      // Initialize maps for Circulation and remove non-zero lower bounds
kpeter@875
   781
      ConstMap<Arc, Value> low(0);
kpeter@875
   782
      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
kpeter@875
   783
      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
kpeter@875
   784
      ValueArcMap cap(_graph), flow(_graph);
kpeter@875
   785
      ValueNodeMap sup(_graph);
kpeter@875
   786
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@875
   787
        sup[n] = _supply[_node_id[n]];
kpeter@874
   788
      }
kpeter@875
   789
      if (_have_lower) {
kpeter@875
   790
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   791
          int j = _arc_idf[a];
kpeter@875
   792
          Value c = _lower[j];
kpeter@875
   793
          cap[a] = _upper[j] - c;
kpeter@875
   794
          sup[_graph.source(a)] -= c;
kpeter@875
   795
          sup[_graph.target(a)] += c;
kpeter@875
   796
        }
kpeter@875
   797
      } else {
kpeter@875
   798
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   799
          cap[a] = _upper[_arc_idf[a]];
kpeter@875
   800
        }
kpeter@875
   801
      }
kpeter@874
   802
kpeter@874
   803
      // Find a feasible flow using Circulation
kpeter@875
   804
      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
kpeter@875
   805
        circ(_graph, low, cap, sup);
kpeter@875
   806
      if (!circ.flowMap(flow).run()) return INFEASIBLE;
kpeter@875
   807
kpeter@875
   808
      // Set residual capacities and handle GEQ supply type
kpeter@875
   809
      if (_sum_supply < 0) {
kpeter@875
   810
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   811
          Value fa = flow[a];
kpeter@875
   812
          _res_cap[_arc_idf[a]] = cap[a] - fa;
kpeter@875
   813
          _res_cap[_arc_idb[a]] = fa;
kpeter@875
   814
          sup[_graph.source(a)] -= fa;
kpeter@875
   815
          sup[_graph.target(a)] += fa;
kpeter@875
   816
        }
kpeter@875
   817
        for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@875
   818
          _excess[_node_id[n]] = sup[n];
kpeter@875
   819
        }
kpeter@875
   820
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
kpeter@875
   821
          int u = _target[a];
kpeter@875
   822
          int ra = _reverse[a];
kpeter@875
   823
          _res_cap[a] = -_sum_supply + 1;
kpeter@875
   824
          _res_cap[ra] = -_excess[u];
kpeter@875
   825
          _cost[a] = 0;
kpeter@875
   826
          _cost[ra] = 0;
kpeter@875
   827
          _excess[u] = 0;
kpeter@875
   828
        }
kpeter@875
   829
      } else {
kpeter@875
   830
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@875
   831
          Value fa = flow[a];
kpeter@875
   832
          _res_cap[_arc_idf[a]] = cap[a] - fa;
kpeter@875
   833
          _res_cap[_arc_idb[a]] = fa;
kpeter@875
   834
        }
kpeter@875
   835
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
kpeter@875
   836
          int ra = _reverse[a];
kpeter@875
   837
          _res_cap[a] = 1;
kpeter@875
   838
          _res_cap[ra] = 0;
kpeter@875
   839
          _cost[a] = 0;
kpeter@875
   840
          _cost[ra] = 0;
kpeter@875
   841
        }
kpeter@875
   842
      }
kpeter@875
   843
      
kpeter@875
   844
      return OPTIMAL;
kpeter@875
   845
    }
kpeter@875
   846
kpeter@875
   847
    // Execute the algorithm and transform the results
kpeter@876
   848
    void start(Method method) {
kpeter@876
   849
      // Maximum path length for partial augment
kpeter@876
   850
      const int MAX_PATH_LENGTH = 4;
kpeter@876
   851
      
kpeter@875
   852
      // Execute the algorithm
kpeter@876
   853
      switch (method) {
kpeter@876
   854
        case PUSH:
kpeter@876
   855
          startPush();
kpeter@876
   856
          break;
kpeter@876
   857
        case AUGMENT:
kpeter@876
   858
          startAugment();
kpeter@876
   859
          break;
kpeter@876
   860
        case PARTIAL_AUGMENT:
kpeter@876
   861
          startAugment(MAX_PATH_LENGTH);
kpeter@876
   862
          break;
kpeter@875
   863
      }
kpeter@875
   864
kpeter@875
   865
      // Compute node potentials for the original costs
kpeter@875
   866
      _arc_vec.clear();
kpeter@875
   867
      _cost_vec.clear();
kpeter@875
   868
      for (int j = 0; j != _res_arc_num; ++j) {
kpeter@875
   869
        if (_res_cap[j] > 0) {
kpeter@875
   870
          _arc_vec.push_back(IntPair(_source[j], _target[j]));
kpeter@875
   871
          _cost_vec.push_back(_scost[j]);
kpeter@875
   872
        }
kpeter@875
   873
      }
kpeter@875
   874
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
kpeter@875
   875
kpeter@875
   876
      typename BellmanFord<StaticDigraph, LargeCostArcMap>
kpeter@875
   877
        ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
kpeter@875
   878
      bf.distMap(_pi_map);
kpeter@875
   879
      bf.init(0);
kpeter@875
   880
      bf.start();
kpeter@875
   881
kpeter@875
   882
      // Handle non-zero lower bounds
kpeter@875
   883
      if (_have_lower) {
kpeter@875
   884
        int limit = _first_out[_root];
kpeter@875
   885
        for (int j = 0; j != limit; ++j) {
kpeter@875
   886
          if (!_forward[j]) _res_cap[j] += _lower[j];
kpeter@875
   887
        }
kpeter@875
   888
      }
kpeter@874
   889
    }
kpeter@874
   890
kpeter@876
   891
    /// Execute the algorithm performing augment and relabel operations
kpeter@876
   892
    void startAugment(int max_length = std::numeric_limits<int>::max()) {
kpeter@874
   893
      // Paramters for heuristics
kpeter@875
   894
      const int BF_HEURISTIC_EPSILON_BOUND = 1000;
kpeter@875
   895
      const int BF_HEURISTIC_BOUND_FACTOR  = 3;
kpeter@874
   896
kpeter@875
   897
      // Perform cost scaling phases
kpeter@875
   898
      IntVector pred_arc(_res_node_num);
kpeter@875
   899
      std::vector<int> path_nodes;
kpeter@874
   900
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
kpeter@874
   901
                                        1 : _epsilon / _alpha )
kpeter@874
   902
      {
kpeter@874
   903
        // "Early Termination" heuristic: use Bellman-Ford algorithm
kpeter@874
   904
        // to check if the current flow is optimal
kpeter@874
   905
        if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
kpeter@875
   906
          _arc_vec.clear();
kpeter@875
   907
          _cost_vec.clear();
kpeter@875
   908
          for (int j = 0; j != _res_arc_num; ++j) {
kpeter@875
   909
            if (_res_cap[j] > 0) {
kpeter@875
   910
              _arc_vec.push_back(IntPair(_source[j], _target[j]));
kpeter@875
   911
              _cost_vec.push_back(_cost[j] + 1);
kpeter@875
   912
            }
kpeter@875
   913
          }
kpeter@875
   914
          _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
kpeter@875
   915
kpeter@875
   916
          BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
kpeter@874
   917
          bf.init(0);
kpeter@874
   918
          bool done = false;
kpeter@875
   919
          int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(_res_node_num));
kpeter@874
   920
          for (int i = 0; i < K && !done; ++i)
kpeter@874
   921
            done = bf.processNextWeakRound();
kpeter@874
   922
          if (done) break;
kpeter@874
   923
        }
kpeter@875
   924
kpeter@874
   925
        // Saturate arcs not satisfying the optimality condition
kpeter@875
   926
        for (int a = 0; a != _res_arc_num; ++a) {
kpeter@875
   927
          if (_res_cap[a] > 0 &&
kpeter@875
   928
              _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
kpeter@875
   929
            Value delta = _res_cap[a];
kpeter@875
   930
            _excess[_source[a]] -= delta;
kpeter@875
   931
            _excess[_target[a]] += delta;
kpeter@875
   932
            _res_cap[a] = 0;
kpeter@875
   933
            _res_cap[_reverse[a]] += delta;
kpeter@874
   934
          }
kpeter@874
   935
        }
kpeter@875
   936
        
kpeter@874
   937
        // Find active nodes (i.e. nodes with positive excess)
kpeter@875
   938
        for (int u = 0; u != _res_node_num; ++u) {
kpeter@875
   939
          if (_excess[u] > 0) _active_nodes.push_back(u);
kpeter@874
   940
        }
kpeter@874
   941
kpeter@875
   942
        // Initialize the next arcs
kpeter@875
   943
        for (int u = 0; u != _res_node_num; ++u) {
kpeter@875
   944
          _next_out[u] = _first_out[u];
kpeter@874
   945
        }
kpeter@874
   946
kpeter@874
   947
        // Perform partial augment and relabel operations
kpeter@875
   948
        while (true) {
kpeter@874
   949
          // Select an active node (FIFO selection)
kpeter@875
   950
          while (_active_nodes.size() > 0 &&
kpeter@875
   951
                 _excess[_active_nodes.front()] <= 0) {
kpeter@875
   952
            _active_nodes.pop_front();
kpeter@874
   953
          }
kpeter@875
   954
          if (_active_nodes.size() == 0) break;
kpeter@875
   955
          int start = _active_nodes.front();
kpeter@874
   956
          path_nodes.clear();
kpeter@874
   957
          path_nodes.push_back(start);
kpeter@874
   958
kpeter@874
   959
          // Find an augmenting path from the start node
kpeter@875
   960
          int tip = start;
kpeter@875
   961
          while (_excess[tip] >= 0 &&
kpeter@876
   962
                 int(path_nodes.size()) <= max_length) {
kpeter@875
   963
            int u;
kpeter@875
   964
            LargeCost min_red_cost, rc;
kpeter@875
   965
            int last_out = _sum_supply < 0 ?
kpeter@875
   966
              _first_out[tip+1] : _first_out[tip+1] - 1;
kpeter@875
   967
            for (int a = _next_out[tip]; a != last_out; ++a) {
kpeter@875
   968
              if (_res_cap[a] > 0 &&
kpeter@875
   969
                  _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
kpeter@875
   970
                u = _target[a];
kpeter@875
   971
                pred_arc[u] = a;
kpeter@875
   972
                _next_out[tip] = a;
kpeter@874
   973
                tip = u;
kpeter@874
   974
                path_nodes.push_back(tip);
kpeter@874
   975
                goto next_step;
kpeter@874
   976
              }
kpeter@874
   977
            }
kpeter@874
   978
kpeter@874
   979
            // Relabel tip node
kpeter@875
   980
            min_red_cost = std::numeric_limits<LargeCost>::max() / 2;
kpeter@875
   981
            for (int a = _first_out[tip]; a != last_out; ++a) {
kpeter@875
   982
              rc = _cost[a] + _pi[_source[a]] - _pi[_target[a]];
kpeter@875
   983
              if (_res_cap[a] > 0 && rc < min_red_cost) {
kpeter@875
   984
                min_red_cost = rc;
kpeter@875
   985
              }
kpeter@874
   986
            }
kpeter@875
   987
            _pi[tip] -= min_red_cost + _epsilon;
kpeter@874
   988
kpeter@875
   989
            // Reset the next arc of tip
kpeter@875
   990
            _next_out[tip] = _first_out[tip];
kpeter@874
   991
kpeter@874
   992
            // Step back
kpeter@874
   993
            if (tip != start) {
kpeter@874
   994
              path_nodes.pop_back();
kpeter@875
   995
              tip = path_nodes.back();
kpeter@874
   996
            }
kpeter@874
   997
kpeter@875
   998
          next_step: ;
kpeter@874
   999
          }
kpeter@874
  1000
kpeter@874
  1001
          // Augment along the found path (as much flow as possible)
kpeter@875
  1002
          Value delta;
kpeter@875
  1003
          int u, v = path_nodes.front(), pa;
kpeter@874
  1004
          for (int i = 1; i < int(path_nodes.size()); ++i) {
kpeter@875
  1005
            u = v;
kpeter@875
  1006
            v = path_nodes[i];
kpeter@875
  1007
            pa = pred_arc[v];
kpeter@875
  1008
            delta = std::min(_res_cap[pa], _excess[u]);
kpeter@875
  1009
            _res_cap[pa] -= delta;
kpeter@875
  1010
            _res_cap[_reverse[pa]] += delta;
kpeter@875
  1011
            _excess[u] -= delta;
kpeter@875
  1012
            _excess[v] += delta;
kpeter@875
  1013
            if (_excess[v] > 0 && _excess[v] <= delta)
kpeter@875
  1014
              _active_nodes.push_back(v);
kpeter@874
  1015
          }
kpeter@874
  1016
        }
kpeter@874
  1017
      }
kpeter@874
  1018
    }
kpeter@874
  1019
kpeter@875
  1020
    /// Execute the algorithm performing push and relabel operations
kpeter@876
  1021
    void startPush() {
kpeter@874
  1022
      // Paramters for heuristics
kpeter@875
  1023
      const int BF_HEURISTIC_EPSILON_BOUND = 1000;
kpeter@875
  1024
      const int BF_HEURISTIC_BOUND_FACTOR  = 3;
kpeter@874
  1025
kpeter@875
  1026
      // Perform cost scaling phases
kpeter@875
  1027
      BoolVector hyper(_res_node_num, false);
kpeter@874
  1028
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
kpeter@874
  1029
                                        1 : _epsilon / _alpha )
kpeter@874
  1030
      {
kpeter@874
  1031
        // "Early Termination" heuristic: use Bellman-Ford algorithm
kpeter@874
  1032
        // to check if the current flow is optimal
kpeter@874
  1033
        if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
kpeter@875
  1034
          _arc_vec.clear();
kpeter@875
  1035
          _cost_vec.clear();
kpeter@875
  1036
          for (int j = 0; j != _res_arc_num; ++j) {
kpeter@875
  1037
            if (_res_cap[j] > 0) {
kpeter@875
  1038
              _arc_vec.push_back(IntPair(_source[j], _target[j]));
kpeter@875
  1039
              _cost_vec.push_back(_cost[j] + 1);
kpeter@875
  1040
            }
kpeter@875
  1041
          }
kpeter@875
  1042
          _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
kpeter@875
  1043
kpeter@875
  1044
          BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
kpeter@874
  1045
          bf.init(0);
kpeter@874
  1046
          bool done = false;
kpeter@875
  1047
          int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(_res_node_num));
kpeter@874
  1048
          for (int i = 0; i < K && !done; ++i)
kpeter@874
  1049
            done = bf.processNextWeakRound();
kpeter@874
  1050
          if (done) break;
kpeter@874
  1051
        }
kpeter@874
  1052
kpeter@874
  1053
        // Saturate arcs not satisfying the optimality condition
kpeter@875
  1054
        for (int a = 0; a != _res_arc_num; ++a) {
kpeter@875
  1055
          if (_res_cap[a] > 0 &&
kpeter@875
  1056
              _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
kpeter@875
  1057
            Value delta = _res_cap[a];
kpeter@875
  1058
            _excess[_source[a]] -= delta;
kpeter@875
  1059
            _excess[_target[a]] += delta;
kpeter@875
  1060
            _res_cap[a] = 0;
kpeter@875
  1061
            _res_cap[_reverse[a]] += delta;
kpeter@874
  1062
          }
kpeter@874
  1063
        }
kpeter@874
  1064
kpeter@874
  1065
        // Find active nodes (i.e. nodes with positive excess)
kpeter@875
  1066
        for (int u = 0; u != _res_node_num; ++u) {
kpeter@875
  1067
          if (_excess[u] > 0) _active_nodes.push_back(u);
kpeter@874
  1068
        }
kpeter@874
  1069
kpeter@875
  1070
        // Initialize the next arcs
kpeter@875
  1071
        for (int u = 0; u != _res_node_num; ++u) {
kpeter@875
  1072
          _next_out[u] = _first_out[u];
kpeter@874
  1073
        }
kpeter@874
  1074
kpeter@874
  1075
        // Perform push and relabel operations
kpeter@875
  1076
        while (_active_nodes.size() > 0) {
kpeter@875
  1077
          LargeCost min_red_cost, rc;
kpeter@875
  1078
          Value delta;
kpeter@875
  1079
          int n, t, a, last_out = _res_arc_num;
kpeter@875
  1080
kpeter@874
  1081
          // Select an active node (FIFO selection)
kpeter@875
  1082
        next_node:
kpeter@875
  1083
          n = _active_nodes.front();
kpeter@875
  1084
          last_out = _sum_supply < 0 ?
kpeter@875
  1085
            _first_out[n+1] : _first_out[n+1] - 1;
kpeter@874
  1086
kpeter@874
  1087
          // Perform push operations if there are admissible arcs
kpeter@875
  1088
          if (_excess[n] > 0) {
kpeter@875
  1089
            for (a = _next_out[n]; a != last_out; ++a) {
kpeter@875
  1090
              if (_res_cap[a] > 0 &&
kpeter@875
  1091
                  _cost[a] + _pi[_source[a]] - _pi[_target[a]] < 0) {
kpeter@875
  1092
                delta = std::min(_res_cap[a], _excess[n]);
kpeter@875
  1093
                t = _target[a];
kpeter@874
  1094
kpeter@874
  1095
                // Push-look-ahead heuristic
kpeter@875
  1096
                Value ahead = -_excess[t];
kpeter@875
  1097
                int last_out_t = _sum_supply < 0 ?
kpeter@875
  1098
                  _first_out[t+1] : _first_out[t+1] - 1;
kpeter@875
  1099
                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
kpeter@875
  1100
                  if (_res_cap[ta] > 0 && 
kpeter@875
  1101
                      _cost[ta] + _pi[_source[ta]] - _pi[_target[ta]] < 0)
kpeter@875
  1102
                    ahead += _res_cap[ta];
kpeter@875
  1103
                  if (ahead >= delta) break;
kpeter@874
  1104
                }
kpeter@874
  1105
                if (ahead < 0) ahead = 0;
kpeter@874
  1106
kpeter@874
  1107
                // Push flow along the arc
kpeter@874
  1108
                if (ahead < delta) {
kpeter@875
  1109
                  _res_cap[a] -= ahead;
kpeter@875
  1110
                  _res_cap[_reverse[a]] += ahead;
kpeter@874
  1111
                  _excess[n] -= ahead;
kpeter@874
  1112
                  _excess[t] += ahead;
kpeter@875
  1113
                  _active_nodes.push_front(t);
kpeter@874
  1114
                  hyper[t] = true;
kpeter@875
  1115
                  _next_out[n] = a;
kpeter@875
  1116
                  goto next_node;
kpeter@874
  1117
                } else {
kpeter@875
  1118
                  _res_cap[a] -= delta;
kpeter@875
  1119
                  _res_cap[_reverse[a]] += delta;
kpeter@874
  1120
                  _excess[n] -= delta;
kpeter@874
  1121
                  _excess[t] += delta;
kpeter@874
  1122
                  if (_excess[t] > 0 && _excess[t] <= delta)
kpeter@875
  1123
                    _active_nodes.push_back(t);
kpeter@874
  1124
                }
kpeter@874
  1125
kpeter@875
  1126
                if (_excess[n] == 0) {
kpeter@875
  1127
                  _next_out[n] = a;
kpeter@875
  1128
                  goto remove_nodes;
kpeter@875
  1129
                }
kpeter@874
  1130
              }
kpeter@874
  1131
            }
kpeter@875
  1132
            _next_out[n] = a;
kpeter@874
  1133
          }
kpeter@874
  1134
kpeter@874
  1135
          // Relabel the node if it is still active (or hyper)
kpeter@875
  1136
          if (_excess[n] > 0 || hyper[n]) {
kpeter@875
  1137
            min_red_cost = std::numeric_limits<LargeCost>::max() / 2;
kpeter@875
  1138
            for (int a = _first_out[n]; a != last_out; ++a) {
kpeter@875
  1139
              rc = _cost[a] + _pi[_source[a]] - _pi[_target[a]];
kpeter@875
  1140
              if (_res_cap[a] > 0 && rc < min_red_cost) {
kpeter@875
  1141
                min_red_cost = rc;
kpeter@875
  1142
              }
kpeter@874
  1143
            }
kpeter@875
  1144
            _pi[n] -= min_red_cost + _epsilon;
kpeter@874
  1145
            hyper[n] = false;
kpeter@874
  1146
kpeter@875
  1147
            // Reset the next arc
kpeter@875
  1148
            _next_out[n] = _first_out[n];
kpeter@874
  1149
          }
kpeter@875
  1150
        
kpeter@874
  1151
          // Remove nodes that are not active nor hyper
kpeter@875
  1152
        remove_nodes:
kpeter@875
  1153
          while ( _active_nodes.size() > 0 &&
kpeter@875
  1154
                  _excess[_active_nodes.front()] <= 0 &&
kpeter@875
  1155
                  !hyper[_active_nodes.front()] ) {
kpeter@875
  1156
            _active_nodes.pop_front();
kpeter@874
  1157
          }
kpeter@874
  1158
        }
kpeter@874
  1159
      }
kpeter@874
  1160
    }
kpeter@874
  1161
kpeter@874
  1162
  }; //class CostScaling
kpeter@874
  1163
kpeter@874
  1164
  ///@}
kpeter@874
  1165
kpeter@874
  1166
} //namespace lemon
kpeter@874
  1167
kpeter@874
  1168
#endif //LEMON_COST_SCALING_H