lemon/cost_scaling.h
author Alpar Juttner <alpar@cs.elte.hu>
Wed, 24 Jul 2013 10:21:35 +0200
changeset 1067 8a3fb3155dca
parent 1049 7bf489cf624e
child 1071 879fcb781086
permissions -rw-r--r--
Bugfix in test/maps_test.cc (#469)
alpar@877
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@808
     2
 *
alpar@877
     3
 * This file is a part of LEMON, a generic C++ optimization library.
kpeter@808
     4
 *
alpar@877
     5
 * Copyright (C) 2003-2010
kpeter@808
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@808
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@808
     8
 *
kpeter@808
     9
 * Permission to use, modify and distribute this software is granted
kpeter@808
    10
 * provided that this copyright notice appears in all copies. For
kpeter@808
    11
 * precise terms see the accompanying LICENSE file.
kpeter@808
    12
 *
kpeter@808
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@808
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@808
    15
 * purpose.
kpeter@808
    16
 *
kpeter@808
    17
 */
kpeter@808
    18
kpeter@808
    19
#ifndef LEMON_COST_SCALING_H
kpeter@808
    20
#define LEMON_COST_SCALING_H
kpeter@808
    21
kpeter@808
    22
/// \ingroup min_cost_flow_algs
kpeter@808
    23
/// \file
kpeter@808
    24
/// \brief Cost scaling algorithm for finding a minimum cost flow.
kpeter@808
    25
kpeter@808
    26
#include <vector>
kpeter@808
    27
#include <deque>
kpeter@808
    28
#include <limits>
kpeter@808
    29
kpeter@808
    30
#include <lemon/core.h>
kpeter@808
    31
#include <lemon/maps.h>
kpeter@808
    32
#include <lemon/math.h>
kpeter@809
    33
#include <lemon/static_graph.h>
kpeter@808
    34
#include <lemon/circulation.h>
kpeter@808
    35
#include <lemon/bellman_ford.h>
kpeter@808
    36
kpeter@808
    37
namespace lemon {
kpeter@808
    38
kpeter@809
    39
  /// \brief Default traits class of CostScaling algorithm.
kpeter@809
    40
  ///
kpeter@809
    41
  /// Default traits class of CostScaling algorithm.
kpeter@809
    42
  /// \tparam GR Digraph type.
kpeter@812
    43
  /// \tparam V The number type used for flow amounts, capacity bounds
kpeter@809
    44
  /// and supply values. By default it is \c int.
kpeter@812
    45
  /// \tparam C The number type used for costs and potentials.
kpeter@809
    46
  /// By default it is the same as \c V.
kpeter@809
    47
#ifdef DOXYGEN
kpeter@809
    48
  template <typename GR, typename V = int, typename C = V>
kpeter@809
    49
#else
kpeter@809
    50
  template < typename GR, typename V = int, typename C = V,
kpeter@809
    51
             bool integer = std::numeric_limits<C>::is_integer >
kpeter@809
    52
#endif
kpeter@809
    53
  struct CostScalingDefaultTraits
kpeter@809
    54
  {
kpeter@809
    55
    /// The type of the digraph
kpeter@809
    56
    typedef GR Digraph;
kpeter@809
    57
    /// The type of the flow amounts, capacity bounds and supply values
kpeter@809
    58
    typedef V Value;
kpeter@809
    59
    /// The type of the arc costs
kpeter@809
    60
    typedef C Cost;
kpeter@809
    61
kpeter@809
    62
    /// \brief The large cost type used for internal computations
kpeter@809
    63
    ///
kpeter@809
    64
    /// The large cost type used for internal computations.
kpeter@809
    65
    /// It is \c long \c long if the \c Cost type is integer,
kpeter@809
    66
    /// otherwise it is \c double.
kpeter@809
    67
    /// \c Cost must be convertible to \c LargeCost.
kpeter@809
    68
    typedef double LargeCost;
kpeter@809
    69
  };
kpeter@809
    70
kpeter@809
    71
  // Default traits class for integer cost types
kpeter@809
    72
  template <typename GR, typename V, typename C>
kpeter@809
    73
  struct CostScalingDefaultTraits<GR, V, C, true>
kpeter@809
    74
  {
kpeter@809
    75
    typedef GR Digraph;
kpeter@809
    76
    typedef V Value;
kpeter@809
    77
    typedef C Cost;
kpeter@809
    78
#ifdef LEMON_HAVE_LONG_LONG
kpeter@809
    79
    typedef long long LargeCost;
kpeter@809
    80
#else
kpeter@809
    81
    typedef long LargeCost;
kpeter@809
    82
#endif
kpeter@809
    83
  };
kpeter@809
    84
kpeter@809
    85
kpeter@808
    86
  /// \addtogroup min_cost_flow_algs
kpeter@808
    87
  /// @{
kpeter@808
    88
kpeter@809
    89
  /// \brief Implementation of the Cost Scaling algorithm for
kpeter@809
    90
  /// finding a \ref min_cost_flow "minimum cost flow".
kpeter@808
    91
  ///
kpeter@809
    92
  /// \ref CostScaling implements a cost scaling algorithm that performs
kpeter@813
    93
  /// push/augment and relabel operations for finding a \ref min_cost_flow
alpar@1053
    94
  /// "minimum cost flow" \cite amo93networkflows, \cite goldberg90approximation,
alpar@1053
    95
  /// \cite goldberg97efficient, \cite bunnagel98efficient.
kpeter@813
    96
  /// It is a highly efficient primal-dual solution method, which
kpeter@809
    97
  /// can be viewed as the generalization of the \ref Preflow
kpeter@809
    98
  /// "preflow push-relabel" algorithm for the maximum flow problem.
kpeter@1049
    99
  /// It is a polynomial algorithm, its running time complexity is
kpeter@1049
   100
  /// \f$O(n^2e\log(nK))\f$, where <i>K</i> denotes the maximum arc cost.
kpeter@808
   101
  ///
kpeter@919
   102
  /// In general, \ref NetworkSimplex and \ref CostScaling are the fastest
kpeter@1003
   103
  /// implementations available in LEMON for solving this problem.
kpeter@1003
   104
  /// (For more information, see \ref min_cost_flow_algs "the module page".)
kpeter@919
   105
  ///
kpeter@809
   106
  /// Most of the parameters of the problem (except for the digraph)
kpeter@809
   107
  /// can be given using separate functions, and the algorithm can be
kpeter@809
   108
  /// executed using the \ref run() function. If some parameters are not
kpeter@809
   109
  /// specified, then default values will be used.
kpeter@808
   110
  ///
kpeter@809
   111
  /// \tparam GR The digraph type the algorithm runs on.
kpeter@812
   112
  /// \tparam V The number type used for flow amounts, capacity bounds
kpeter@825
   113
  /// and supply values in the algorithm. By default, it is \c int.
kpeter@812
   114
  /// \tparam C The number type used for costs and potentials in the
kpeter@825
   115
  /// algorithm. By default, it is the same as \c V.
kpeter@825
   116
  /// \tparam TR The traits class that defines various types used by the
kpeter@825
   117
  /// algorithm. By default, it is \ref CostScalingDefaultTraits
kpeter@825
   118
  /// "CostScalingDefaultTraits<GR, V, C>".
kpeter@825
   119
  /// In most cases, this parameter should not be set directly,
kpeter@825
   120
  /// consider to use the named template parameters instead.
kpeter@808
   121
  ///
kpeter@921
   122
  /// \warning Both \c V and \c C must be signed number types.
kpeter@921
   123
  /// \warning All input data (capacities, supply values, and costs) must
kpeter@809
   124
  /// be integer.
kpeter@919
   125
  /// \warning This algorithm does not support negative costs for
kpeter@919
   126
  /// arcs having infinite upper bound.
kpeter@810
   127
  ///
kpeter@810
   128
  /// \note %CostScaling provides three different internal methods,
kpeter@810
   129
  /// from which the most efficient one is used by default.
kpeter@810
   130
  /// For more information, see \ref Method.
kpeter@809
   131
#ifdef DOXYGEN
kpeter@809
   132
  template <typename GR, typename V, typename C, typename TR>
kpeter@809
   133
#else
kpeter@809
   134
  template < typename GR, typename V = int, typename C = V,
kpeter@809
   135
             typename TR = CostScalingDefaultTraits<GR, V, C> >
kpeter@809
   136
#endif
kpeter@808
   137
  class CostScaling
kpeter@808
   138
  {
kpeter@809
   139
  public:
kpeter@808
   140
kpeter@809
   141
    /// The type of the digraph
kpeter@809
   142
    typedef typename TR::Digraph Digraph;
kpeter@809
   143
    /// The type of the flow amounts, capacity bounds and supply values
kpeter@809
   144
    typedef typename TR::Value Value;
kpeter@809
   145
    /// The type of the arc costs
kpeter@809
   146
    typedef typename TR::Cost Cost;
kpeter@808
   147
kpeter@809
   148
    /// \brief The large cost type
kpeter@809
   149
    ///
kpeter@809
   150
    /// The large cost type used for internal computations.
kpeter@825
   151
    /// By default, it is \c long \c long if the \c Cost type is integer,
kpeter@809
   152
    /// otherwise it is \c double.
kpeter@809
   153
    typedef typename TR::LargeCost LargeCost;
kpeter@808
   154
kpeter@809
   155
    /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
kpeter@809
   156
    typedef TR Traits;
kpeter@808
   157
kpeter@808
   158
  public:
kpeter@808
   159
kpeter@809
   160
    /// \brief Problem type constants for the \c run() function.
kpeter@809
   161
    ///
kpeter@809
   162
    /// Enum type containing the problem type constants that can be
kpeter@809
   163
    /// returned by the \ref run() function of the algorithm.
kpeter@809
   164
    enum ProblemType {
kpeter@809
   165
      /// The problem has no feasible solution (flow).
kpeter@809
   166
      INFEASIBLE,
kpeter@809
   167
      /// The problem has optimal solution (i.e. it is feasible and
kpeter@809
   168
      /// bounded), and the algorithm has found optimal flow and node
kpeter@809
   169
      /// potentials (primal and dual solutions).
kpeter@809
   170
      OPTIMAL,
kpeter@809
   171
      /// The digraph contains an arc of negative cost and infinite
kpeter@809
   172
      /// upper bound. It means that the objective function is unbounded
kpeter@812
   173
      /// on that arc, however, note that it could actually be bounded
kpeter@809
   174
      /// over the feasible flows, but this algroithm cannot handle
kpeter@809
   175
      /// these cases.
kpeter@809
   176
      UNBOUNDED
kpeter@809
   177
    };
kpeter@808
   178
kpeter@810
   179
    /// \brief Constants for selecting the internal method.
kpeter@810
   180
    ///
kpeter@810
   181
    /// Enum type containing constants for selecting the internal method
kpeter@810
   182
    /// for the \ref run() function.
kpeter@810
   183
    ///
kpeter@810
   184
    /// \ref CostScaling provides three internal methods that differ mainly
kpeter@810
   185
    /// in their base operations, which are used in conjunction with the
kpeter@810
   186
    /// relabel operation.
kpeter@810
   187
    /// By default, the so called \ref PARTIAL_AUGMENT
kpeter@919
   188
    /// "Partial Augment-Relabel" method is used, which turned out to be
kpeter@810
   189
    /// the most efficient and the most robust on various test inputs.
kpeter@810
   190
    /// However, the other methods can be selected using the \ref run()
kpeter@810
   191
    /// function with the proper parameter.
kpeter@810
   192
    enum Method {
kpeter@810
   193
      /// Local push operations are used, i.e. flow is moved only on one
kpeter@810
   194
      /// admissible arc at once.
kpeter@810
   195
      PUSH,
kpeter@810
   196
      /// Augment operations are used, i.e. flow is moved on admissible
kpeter@810
   197
      /// paths from a node with excess to a node with deficit.
kpeter@810
   198
      AUGMENT,
alpar@877
   199
      /// Partial augment operations are used, i.e. flow is moved on
kpeter@810
   200
      /// admissible paths started from a node with excess, but the
kpeter@810
   201
      /// lengths of these paths are limited. This method can be viewed
kpeter@810
   202
      /// as a combined version of the previous two operations.
kpeter@810
   203
      PARTIAL_AUGMENT
kpeter@810
   204
    };
kpeter@810
   205
kpeter@808
   206
  private:
kpeter@808
   207
kpeter@809
   208
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
kpeter@808
   209
kpeter@809
   210
    typedef std::vector<int> IntVector;
kpeter@809
   211
    typedef std::vector<Value> ValueVector;
kpeter@809
   212
    typedef std::vector<Cost> CostVector;
kpeter@809
   213
    typedef std::vector<LargeCost> LargeCostVector;
kpeter@839
   214
    typedef std::vector<char> BoolVector;
kpeter@839
   215
    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
kpeter@808
   216
kpeter@809
   217
  private:
alpar@877
   218
kpeter@809
   219
    template <typename KT, typename VT>
kpeter@820
   220
    class StaticVectorMap {
kpeter@808
   221
    public:
kpeter@809
   222
      typedef KT Key;
kpeter@809
   223
      typedef VT Value;
alpar@877
   224
kpeter@820
   225
      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
alpar@877
   226
kpeter@809
   227
      const Value& operator[](const Key& key) const {
kpeter@809
   228
        return _v[StaticDigraph::id(key)];
kpeter@808
   229
      }
kpeter@808
   230
kpeter@809
   231
      Value& operator[](const Key& key) {
kpeter@809
   232
        return _v[StaticDigraph::id(key)];
kpeter@809
   233
      }
alpar@877
   234
kpeter@809
   235
      void set(const Key& key, const Value& val) {
kpeter@809
   236
        _v[StaticDigraph::id(key)] = val;
kpeter@808
   237
      }
kpeter@808
   238
kpeter@809
   239
    private:
kpeter@809
   240
      std::vector<Value>& _v;
kpeter@809
   241
    };
kpeter@809
   242
kpeter@820
   243
    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
kpeter@808
   244
kpeter@808
   245
  private:
kpeter@808
   246
kpeter@809
   247
    // Data related to the underlying digraph
kpeter@809
   248
    const GR &_graph;
kpeter@809
   249
    int _node_num;
kpeter@809
   250
    int _arc_num;
kpeter@809
   251
    int _res_node_num;
kpeter@809
   252
    int _res_arc_num;
kpeter@809
   253
    int _root;
kpeter@808
   254
kpeter@809
   255
    // Parameters of the problem
kpeter@809
   256
    bool _have_lower;
kpeter@809
   257
    Value _sum_supply;
kpeter@839
   258
    int _sup_node_num;
kpeter@808
   259
kpeter@809
   260
    // Data structures for storing the digraph
kpeter@809
   261
    IntNodeMap _node_id;
kpeter@809
   262
    IntArcMap _arc_idf;
kpeter@809
   263
    IntArcMap _arc_idb;
kpeter@809
   264
    IntVector _first_out;
kpeter@809
   265
    BoolVector _forward;
kpeter@809
   266
    IntVector _source;
kpeter@809
   267
    IntVector _target;
kpeter@809
   268
    IntVector _reverse;
kpeter@809
   269
kpeter@809
   270
    // Node and arc data
kpeter@809
   271
    ValueVector _lower;
kpeter@809
   272
    ValueVector _upper;
kpeter@809
   273
    CostVector _scost;
kpeter@809
   274
    ValueVector _supply;
kpeter@809
   275
kpeter@809
   276
    ValueVector _res_cap;
kpeter@809
   277
    LargeCostVector _cost;
kpeter@809
   278
    LargeCostVector _pi;
kpeter@809
   279
    ValueVector _excess;
kpeter@809
   280
    IntVector _next_out;
kpeter@809
   281
    std::deque<int> _active_nodes;
kpeter@809
   282
kpeter@809
   283
    // Data for scaling
kpeter@809
   284
    LargeCost _epsilon;
kpeter@808
   285
    int _alpha;
kpeter@808
   286
kpeter@839
   287
    IntVector _buckets;
kpeter@839
   288
    IntVector _bucket_next;
kpeter@839
   289
    IntVector _bucket_prev;
kpeter@839
   290
    IntVector _rank;
kpeter@839
   291
    int _max_rank;
alpar@877
   292
kpeter@809
   293
  public:
alpar@877
   294
kpeter@809
   295
    /// \brief Constant for infinite upper bounds (capacities).
kpeter@809
   296
    ///
kpeter@809
   297
    /// Constant for infinite upper bounds (capacities).
kpeter@809
   298
    /// It is \c std::numeric_limits<Value>::infinity() if available,
kpeter@809
   299
    /// \c std::numeric_limits<Value>::max() otherwise.
kpeter@809
   300
    const Value INF;
kpeter@809
   301
kpeter@808
   302
  public:
kpeter@808
   303
kpeter@809
   304
    /// \name Named Template Parameters
kpeter@809
   305
    /// @{
kpeter@809
   306
kpeter@809
   307
    template <typename T>
kpeter@809
   308
    struct SetLargeCostTraits : public Traits {
kpeter@809
   309
      typedef T LargeCost;
kpeter@809
   310
    };
kpeter@809
   311
kpeter@809
   312
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@809
   313
    /// \c LargeCost type.
kpeter@808
   314
    ///
kpeter@809
   315
    /// \ref named-templ-param "Named parameter" for setting \c LargeCost
kpeter@809
   316
    /// type, which is used for internal computations in the algorithm.
kpeter@809
   317
    /// \c Cost must be convertible to \c LargeCost.
kpeter@809
   318
    template <typename T>
kpeter@809
   319
    struct SetLargeCost
kpeter@809
   320
      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
kpeter@809
   321
      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
kpeter@809
   322
    };
kpeter@809
   323
kpeter@809
   324
    /// @}
kpeter@809
   325
kpeter@863
   326
  protected:
kpeter@863
   327
kpeter@863
   328
    CostScaling() {}
kpeter@863
   329
kpeter@809
   330
  public:
kpeter@809
   331
kpeter@809
   332
    /// \brief Constructor.
kpeter@808
   333
    ///
kpeter@809
   334
    /// The constructor of the class.
kpeter@809
   335
    ///
kpeter@809
   336
    /// \param graph The digraph the algorithm runs on.
kpeter@809
   337
    CostScaling(const GR& graph) :
kpeter@809
   338
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
kpeter@809
   339
      INF(std::numeric_limits<Value>::has_infinity ?
kpeter@809
   340
          std::numeric_limits<Value>::infinity() :
kpeter@809
   341
          std::numeric_limits<Value>::max())
kpeter@808
   342
    {
kpeter@812
   343
      // Check the number types
kpeter@809
   344
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
kpeter@809
   345
        "The flow type of CostScaling must be signed");
kpeter@809
   346
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
kpeter@809
   347
        "The cost type of CostScaling must be signed");
alpar@877
   348
kpeter@830
   349
      // Reset data structures
kpeter@809
   350
      reset();
kpeter@808
   351
    }
kpeter@808
   352
kpeter@809
   353
    /// \name Parameters
kpeter@809
   354
    /// The parameters of the algorithm can be specified using these
kpeter@809
   355
    /// functions.
kpeter@809
   356
kpeter@809
   357
    /// @{
kpeter@809
   358
kpeter@809
   359
    /// \brief Set the lower bounds on the arcs.
kpeter@808
   360
    ///
kpeter@809
   361
    /// This function sets the lower bounds on the arcs.
kpeter@809
   362
    /// If it is not used before calling \ref run(), the lower bounds
kpeter@809
   363
    /// will be set to zero on all arcs.
kpeter@808
   364
    ///
kpeter@809
   365
    /// \param map An arc map storing the lower bounds.
kpeter@809
   366
    /// Its \c Value type must be convertible to the \c Value type
kpeter@809
   367
    /// of the algorithm.
kpeter@809
   368
    ///
kpeter@809
   369
    /// \return <tt>(*this)</tt>
kpeter@809
   370
    template <typename LowerMap>
kpeter@809
   371
    CostScaling& lowerMap(const LowerMap& map) {
kpeter@809
   372
      _have_lower = true;
kpeter@809
   373
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   374
        _lower[_arc_idf[a]] = map[a];
kpeter@809
   375
        _lower[_arc_idb[a]] = map[a];
kpeter@808
   376
      }
kpeter@808
   377
      return *this;
kpeter@808
   378
    }
kpeter@808
   379
kpeter@809
   380
    /// \brief Set the upper bounds (capacities) on the arcs.
kpeter@808
   381
    ///
kpeter@809
   382
    /// This function sets the upper bounds (capacities) on the arcs.
kpeter@809
   383
    /// If it is not used before calling \ref run(), the upper bounds
kpeter@809
   384
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
kpeter@812
   385
    /// unbounded from above).
kpeter@808
   386
    ///
kpeter@809
   387
    /// \param map An arc map storing the upper bounds.
kpeter@809
   388
    /// Its \c Value type must be convertible to the \c Value type
kpeter@809
   389
    /// of the algorithm.
kpeter@809
   390
    ///
kpeter@809
   391
    /// \return <tt>(*this)</tt>
kpeter@809
   392
    template<typename UpperMap>
kpeter@809
   393
    CostScaling& upperMap(const UpperMap& map) {
kpeter@809
   394
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   395
        _upper[_arc_idf[a]] = map[a];
kpeter@808
   396
      }
kpeter@808
   397
      return *this;
kpeter@808
   398
    }
kpeter@808
   399
kpeter@809
   400
    /// \brief Set the costs of the arcs.
kpeter@809
   401
    ///
kpeter@809
   402
    /// This function sets the costs of the arcs.
kpeter@809
   403
    /// If it is not used before calling \ref run(), the costs
kpeter@809
   404
    /// will be set to \c 1 on all arcs.
kpeter@809
   405
    ///
kpeter@809
   406
    /// \param map An arc map storing the costs.
kpeter@809
   407
    /// Its \c Value type must be convertible to the \c Cost type
kpeter@809
   408
    /// of the algorithm.
kpeter@809
   409
    ///
kpeter@809
   410
    /// \return <tt>(*this)</tt>
kpeter@809
   411
    template<typename CostMap>
kpeter@809
   412
    CostScaling& costMap(const CostMap& map) {
kpeter@809
   413
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   414
        _scost[_arc_idf[a]] =  map[a];
kpeter@809
   415
        _scost[_arc_idb[a]] = -map[a];
kpeter@809
   416
      }
kpeter@809
   417
      return *this;
kpeter@809
   418
    }
kpeter@809
   419
kpeter@809
   420
    /// \brief Set the supply values of the nodes.
kpeter@809
   421
    ///
kpeter@809
   422
    /// This function sets the supply values of the nodes.
kpeter@809
   423
    /// If neither this function nor \ref stSupply() is used before
kpeter@809
   424
    /// calling \ref run(), the supply of each node will be set to zero.
kpeter@809
   425
    ///
kpeter@809
   426
    /// \param map A node map storing the supply values.
kpeter@809
   427
    /// Its \c Value type must be convertible to the \c Value type
kpeter@809
   428
    /// of the algorithm.
kpeter@809
   429
    ///
kpeter@809
   430
    /// \return <tt>(*this)</tt>
kpeter@809
   431
    template<typename SupplyMap>
kpeter@809
   432
    CostScaling& supplyMap(const SupplyMap& map) {
kpeter@809
   433
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@809
   434
        _supply[_node_id[n]] = map[n];
kpeter@809
   435
      }
kpeter@809
   436
      return *this;
kpeter@809
   437
    }
kpeter@809
   438
kpeter@809
   439
    /// \brief Set single source and target nodes and a supply value.
kpeter@809
   440
    ///
kpeter@809
   441
    /// This function sets a single source node and a single target node
kpeter@809
   442
    /// and the required flow value.
kpeter@809
   443
    /// If neither this function nor \ref supplyMap() is used before
kpeter@809
   444
    /// calling \ref run(), the supply of each node will be set to zero.
kpeter@809
   445
    ///
kpeter@809
   446
    /// Using this function has the same effect as using \ref supplyMap()
kpeter@919
   447
    /// with a map in which \c k is assigned to \c s, \c -k is
kpeter@809
   448
    /// assigned to \c t and all other nodes have zero supply value.
kpeter@809
   449
    ///
kpeter@809
   450
    /// \param s The source node.
kpeter@809
   451
    /// \param t The target node.
kpeter@809
   452
    /// \param k The required amount of flow from node \c s to node \c t
kpeter@809
   453
    /// (i.e. the supply of \c s and the demand of \c t).
kpeter@809
   454
    ///
kpeter@809
   455
    /// \return <tt>(*this)</tt>
kpeter@809
   456
    CostScaling& stSupply(const Node& s, const Node& t, Value k) {
kpeter@809
   457
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@809
   458
        _supply[i] = 0;
kpeter@809
   459
      }
kpeter@809
   460
      _supply[_node_id[s]] =  k;
kpeter@809
   461
      _supply[_node_id[t]] = -k;
kpeter@809
   462
      return *this;
kpeter@809
   463
    }
alpar@877
   464
kpeter@809
   465
    /// @}
kpeter@809
   466
kpeter@808
   467
    /// \name Execution control
kpeter@809
   468
    /// The algorithm can be executed using \ref run().
kpeter@808
   469
kpeter@808
   470
    /// @{
kpeter@808
   471
kpeter@808
   472
    /// \brief Run the algorithm.
kpeter@808
   473
    ///
kpeter@809
   474
    /// This function runs the algorithm.
kpeter@809
   475
    /// The paramters can be specified using functions \ref lowerMap(),
kpeter@809
   476
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
kpeter@809
   477
    /// For example,
kpeter@809
   478
    /// \code
kpeter@809
   479
    ///   CostScaling<ListDigraph> cs(graph);
kpeter@809
   480
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
kpeter@809
   481
    ///     .supplyMap(sup).run();
kpeter@809
   482
    /// \endcode
kpeter@809
   483
    ///
kpeter@830
   484
    /// This function can be called more than once. All the given parameters
kpeter@830
   485
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
kpeter@830
   486
    /// is used, thus only the modified parameters have to be set again.
kpeter@830
   487
    /// If the underlying digraph was also modified after the construction
kpeter@830
   488
    /// of the class (or the last \ref reset() call), then the \ref reset()
kpeter@830
   489
    /// function must be called.
kpeter@808
   490
    ///
kpeter@810
   491
    /// \param method The internal method that will be used in the
kpeter@810
   492
    /// algorithm. For more information, see \ref Method.
kpeter@938
   493
    /// \param factor The cost scaling factor. It must be at least two.
kpeter@808
   494
    ///
kpeter@809
   495
    /// \return \c INFEASIBLE if no feasible flow exists,
kpeter@809
   496
    /// \n \c OPTIMAL if the problem has optimal solution
kpeter@809
   497
    /// (i.e. it is feasible and bounded), and the algorithm has found
kpeter@809
   498
    /// optimal flow and node potentials (primal and dual solutions),
kpeter@809
   499
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
kpeter@809
   500
    /// and infinite upper bound. It means that the objective function
kpeter@812
   501
    /// is unbounded on that arc, however, note that it could actually be
kpeter@809
   502
    /// bounded over the feasible flows, but this algroithm cannot handle
kpeter@809
   503
    /// these cases.
kpeter@809
   504
    ///
kpeter@810
   505
    /// \see ProblemType, Method
kpeter@830
   506
    /// \see resetParams(), reset()
kpeter@938
   507
    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 16) {
kpeter@938
   508
      LEMON_ASSERT(factor >= 2, "The scaling factor must be at least 2");
kpeter@810
   509
      _alpha = factor;
kpeter@809
   510
      ProblemType pt = init();
kpeter@809
   511
      if (pt != OPTIMAL) return pt;
kpeter@810
   512
      start(method);
kpeter@809
   513
      return OPTIMAL;
kpeter@809
   514
    }
kpeter@809
   515
kpeter@809
   516
    /// \brief Reset all the parameters that have been given before.
kpeter@809
   517
    ///
kpeter@809
   518
    /// This function resets all the paramaters that have been given
kpeter@809
   519
    /// before using functions \ref lowerMap(), \ref upperMap(),
kpeter@809
   520
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
kpeter@809
   521
    ///
kpeter@830
   522
    /// It is useful for multiple \ref run() calls. Basically, all the given
kpeter@830
   523
    /// parameters are kept for the next \ref run() call, unless
kpeter@830
   524
    /// \ref resetParams() or \ref reset() is used.
kpeter@830
   525
    /// If the underlying digraph was also modified after the construction
kpeter@830
   526
    /// of the class or the last \ref reset() call, then the \ref reset()
kpeter@830
   527
    /// function must be used, otherwise \ref resetParams() is sufficient.
kpeter@809
   528
    ///
kpeter@809
   529
    /// For example,
kpeter@809
   530
    /// \code
kpeter@809
   531
    ///   CostScaling<ListDigraph> cs(graph);
kpeter@809
   532
    ///
kpeter@809
   533
    ///   // First run
kpeter@809
   534
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
kpeter@809
   535
    ///     .supplyMap(sup).run();
kpeter@809
   536
    ///
kpeter@830
   537
    ///   // Run again with modified cost map (resetParams() is not called,
kpeter@809
   538
    ///   // so only the cost map have to be set again)
kpeter@809
   539
    ///   cost[e] += 100;
kpeter@809
   540
    ///   cs.costMap(cost).run();
kpeter@809
   541
    ///
kpeter@830
   542
    ///   // Run again from scratch using resetParams()
kpeter@809
   543
    ///   // (the lower bounds will be set to zero on all arcs)
kpeter@830
   544
    ///   cs.resetParams();
kpeter@809
   545
    ///   cs.upperMap(capacity).costMap(cost)
kpeter@809
   546
    ///     .supplyMap(sup).run();
kpeter@809
   547
    /// \endcode
kpeter@809
   548
    ///
kpeter@809
   549
    /// \return <tt>(*this)</tt>
kpeter@830
   550
    ///
kpeter@830
   551
    /// \see reset(), run()
kpeter@830
   552
    CostScaling& resetParams() {
kpeter@809
   553
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@809
   554
        _supply[i] = 0;
kpeter@808
   555
      }
kpeter@809
   556
      int limit = _first_out[_root];
kpeter@809
   557
      for (int j = 0; j != limit; ++j) {
kpeter@809
   558
        _lower[j] = 0;
kpeter@809
   559
        _upper[j] = INF;
kpeter@809
   560
        _scost[j] = _forward[j] ? 1 : -1;
kpeter@809
   561
      }
kpeter@809
   562
      for (int j = limit; j != _res_arc_num; ++j) {
kpeter@809
   563
        _lower[j] = 0;
kpeter@809
   564
        _upper[j] = INF;
kpeter@809
   565
        _scost[j] = 0;
kpeter@809
   566
        _scost[_reverse[j]] = 0;
alpar@877
   567
      }
kpeter@809
   568
      _have_lower = false;
kpeter@809
   569
      return *this;
kpeter@808
   570
    }
kpeter@808
   571
kpeter@934
   572
    /// \brief Reset the internal data structures and all the parameters
kpeter@934
   573
    /// that have been given before.
kpeter@830
   574
    ///
kpeter@934
   575
    /// This function resets the internal data structures and all the
kpeter@934
   576
    /// paramaters that have been given before using functions \ref lowerMap(),
kpeter@934
   577
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
kpeter@830
   578
    ///
kpeter@934
   579
    /// It is useful for multiple \ref run() calls. By default, all the given
kpeter@934
   580
    /// parameters are kept for the next \ref run() call, unless
kpeter@934
   581
    /// \ref resetParams() or \ref reset() is used.
kpeter@934
   582
    /// If the underlying digraph was also modified after the construction
kpeter@934
   583
    /// of the class or the last \ref reset() call, then the \ref reset()
kpeter@934
   584
    /// function must be used, otherwise \ref resetParams() is sufficient.
kpeter@934
   585
    ///
kpeter@934
   586
    /// See \ref resetParams() for examples.
kpeter@934
   587
    ///
kpeter@830
   588
    /// \return <tt>(*this)</tt>
kpeter@934
   589
    ///
kpeter@934
   590
    /// \see resetParams(), run()
kpeter@830
   591
    CostScaling& reset() {
kpeter@830
   592
      // Resize vectors
kpeter@830
   593
      _node_num = countNodes(_graph);
kpeter@830
   594
      _arc_num = countArcs(_graph);
kpeter@830
   595
      _res_node_num = _node_num + 1;
kpeter@830
   596
      _res_arc_num = 2 * (_arc_num + _node_num);
kpeter@830
   597
      _root = _node_num;
kpeter@830
   598
kpeter@830
   599
      _first_out.resize(_res_node_num + 1);
kpeter@830
   600
      _forward.resize(_res_arc_num);
kpeter@830
   601
      _source.resize(_res_arc_num);
kpeter@830
   602
      _target.resize(_res_arc_num);
kpeter@830
   603
      _reverse.resize(_res_arc_num);
kpeter@830
   604
kpeter@830
   605
      _lower.resize(_res_arc_num);
kpeter@830
   606
      _upper.resize(_res_arc_num);
kpeter@830
   607
      _scost.resize(_res_arc_num);
kpeter@830
   608
      _supply.resize(_res_node_num);
alpar@877
   609
kpeter@830
   610
      _res_cap.resize(_res_arc_num);
kpeter@830
   611
      _cost.resize(_res_arc_num);
kpeter@830
   612
      _pi.resize(_res_node_num);
kpeter@830
   613
      _excess.resize(_res_node_num);
kpeter@830
   614
      _next_out.resize(_res_node_num);
kpeter@830
   615
kpeter@830
   616
      // Copy the graph
kpeter@830
   617
      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
kpeter@830
   618
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@830
   619
        _node_id[n] = i;
kpeter@830
   620
      }
kpeter@830
   621
      i = 0;
kpeter@830
   622
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
kpeter@830
   623
        _first_out[i] = j;
kpeter@830
   624
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
kpeter@830
   625
          _arc_idf[a] = j;
kpeter@830
   626
          _forward[j] = true;
kpeter@830
   627
          _source[j] = i;
kpeter@830
   628
          _target[j] = _node_id[_graph.runningNode(a)];
kpeter@830
   629
        }
kpeter@830
   630
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
kpeter@830
   631
          _arc_idb[a] = j;
kpeter@830
   632
          _forward[j] = false;
kpeter@830
   633
          _source[j] = i;
kpeter@830
   634
          _target[j] = _node_id[_graph.runningNode(a)];
kpeter@830
   635
        }
kpeter@830
   636
        _forward[j] = false;
kpeter@830
   637
        _source[j] = i;
kpeter@830
   638
        _target[j] = _root;
kpeter@830
   639
        _reverse[j] = k;
kpeter@830
   640
        _forward[k] = true;
kpeter@830
   641
        _source[k] = _root;
kpeter@830
   642
        _target[k] = i;
kpeter@830
   643
        _reverse[k] = j;
kpeter@830
   644
        ++j; ++k;
kpeter@830
   645
      }
kpeter@830
   646
      _first_out[i] = j;
kpeter@830
   647
      _first_out[_res_node_num] = k;
kpeter@830
   648
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@830
   649
        int fi = _arc_idf[a];
kpeter@830
   650
        int bi = _arc_idb[a];
kpeter@830
   651
        _reverse[fi] = bi;
kpeter@830
   652
        _reverse[bi] = fi;
kpeter@830
   653
      }
alpar@877
   654
kpeter@830
   655
      // Reset parameters
kpeter@830
   656
      resetParams();
kpeter@830
   657
      return *this;
kpeter@830
   658
    }
kpeter@830
   659
kpeter@808
   660
    /// @}
kpeter@808
   661
kpeter@808
   662
    /// \name Query Functions
kpeter@809
   663
    /// The results of the algorithm can be obtained using these
kpeter@808
   664
    /// functions.\n
kpeter@809
   665
    /// The \ref run() function must be called before using them.
kpeter@808
   666
kpeter@808
   667
    /// @{
kpeter@808
   668
kpeter@809
   669
    /// \brief Return the total cost of the found flow.
kpeter@808
   670
    ///
kpeter@809
   671
    /// This function returns the total cost of the found flow.
kpeter@809
   672
    /// Its complexity is O(e).
kpeter@809
   673
    ///
kpeter@809
   674
    /// \note The return type of the function can be specified as a
kpeter@809
   675
    /// template parameter. For example,
kpeter@809
   676
    /// \code
kpeter@809
   677
    ///   cs.totalCost<double>();
kpeter@809
   678
    /// \endcode
kpeter@809
   679
    /// It is useful if the total cost cannot be stored in the \c Cost
kpeter@809
   680
    /// type of the algorithm, which is the default return type of the
kpeter@809
   681
    /// function.
kpeter@808
   682
    ///
kpeter@808
   683
    /// \pre \ref run() must be called before using this function.
kpeter@809
   684
    template <typename Number>
kpeter@809
   685
    Number totalCost() const {
kpeter@809
   686
      Number c = 0;
kpeter@809
   687
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   688
        int i = _arc_idb[a];
kpeter@809
   689
        c += static_cast<Number>(_res_cap[i]) *
kpeter@809
   690
             (-static_cast<Number>(_scost[i]));
kpeter@809
   691
      }
kpeter@809
   692
      return c;
kpeter@808
   693
    }
kpeter@808
   694
kpeter@809
   695
#ifndef DOXYGEN
kpeter@809
   696
    Cost totalCost() const {
kpeter@809
   697
      return totalCost<Cost>();
kpeter@808
   698
    }
kpeter@809
   699
#endif
kpeter@808
   700
kpeter@808
   701
    /// \brief Return the flow on the given arc.
kpeter@808
   702
    ///
kpeter@809
   703
    /// This function returns the flow on the given arc.
kpeter@808
   704
    ///
kpeter@808
   705
    /// \pre \ref run() must be called before using this function.
kpeter@809
   706
    Value flow(const Arc& a) const {
kpeter@809
   707
      return _res_cap[_arc_idb[a]];
kpeter@808
   708
    }
kpeter@808
   709
kpeter@1003
   710
    /// \brief Copy the flow values (the primal solution) into the
kpeter@1003
   711
    /// given map.
kpeter@808
   712
    ///
kpeter@809
   713
    /// This function copies the flow value on each arc into the given
kpeter@809
   714
    /// map. The \c Value type of the algorithm must be convertible to
kpeter@809
   715
    /// the \c Value type of the map.
kpeter@808
   716
    ///
kpeter@808
   717
    /// \pre \ref run() must be called before using this function.
kpeter@809
   718
    template <typename FlowMap>
kpeter@809
   719
    void flowMap(FlowMap &map) const {
kpeter@809
   720
      for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   721
        map.set(a, _res_cap[_arc_idb[a]]);
kpeter@809
   722
      }
kpeter@808
   723
    }
kpeter@808
   724
kpeter@809
   725
    /// \brief Return the potential (dual value) of the given node.
kpeter@808
   726
    ///
kpeter@809
   727
    /// This function returns the potential (dual value) of the
kpeter@809
   728
    /// given node.
kpeter@808
   729
    ///
kpeter@808
   730
    /// \pre \ref run() must be called before using this function.
kpeter@809
   731
    Cost potential(const Node& n) const {
kpeter@809
   732
      return static_cast<Cost>(_pi[_node_id[n]]);
kpeter@809
   733
    }
kpeter@809
   734
kpeter@1003
   735
    /// \brief Copy the potential values (the dual solution) into the
kpeter@1003
   736
    /// given map.
kpeter@809
   737
    ///
kpeter@809
   738
    /// This function copies the potential (dual value) of each node
kpeter@809
   739
    /// into the given map.
kpeter@809
   740
    /// The \c Cost type of the algorithm must be convertible to the
kpeter@809
   741
    /// \c Value type of the map.
kpeter@809
   742
    ///
kpeter@809
   743
    /// \pre \ref run() must be called before using this function.
kpeter@809
   744
    template <typename PotentialMap>
kpeter@809
   745
    void potentialMap(PotentialMap &map) const {
kpeter@809
   746
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@809
   747
        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
kpeter@809
   748
      }
kpeter@808
   749
    }
kpeter@808
   750
kpeter@808
   751
    /// @}
kpeter@808
   752
kpeter@808
   753
  private:
kpeter@808
   754
kpeter@809
   755
    // Initialize the algorithm
kpeter@809
   756
    ProblemType init() {
kpeter@821
   757
      if (_res_node_num <= 1) return INFEASIBLE;
kpeter@809
   758
kpeter@809
   759
      // Check the sum of supply values
kpeter@809
   760
      _sum_supply = 0;
kpeter@809
   761
      for (int i = 0; i != _root; ++i) {
kpeter@809
   762
        _sum_supply += _supply[i];
kpeter@808
   763
      }
kpeter@809
   764
      if (_sum_supply > 0) return INFEASIBLE;
alpar@877
   765
kpeter@809
   766
kpeter@809
   767
      // Initialize vectors
kpeter@809
   768
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@809
   769
        _pi[i] = 0;
kpeter@809
   770
        _excess[i] = _supply[i];
kpeter@809
   771
      }
alpar@877
   772
kpeter@809
   773
      // Remove infinite upper bounds and check negative arcs
kpeter@809
   774
      const Value MAX = std::numeric_limits<Value>::max();
kpeter@809
   775
      int last_out;
kpeter@809
   776
      if (_have_lower) {
kpeter@809
   777
        for (int i = 0; i != _root; ++i) {
kpeter@809
   778
          last_out = _first_out[i+1];
kpeter@809
   779
          for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@809
   780
            if (_forward[j]) {
kpeter@809
   781
              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
kpeter@809
   782
              if (c >= MAX) return UNBOUNDED;
kpeter@809
   783
              _excess[i] -= c;
kpeter@809
   784
              _excess[_target[j]] += c;
kpeter@809
   785
            }
kpeter@809
   786
          }
kpeter@809
   787
        }
kpeter@809
   788
      } else {
kpeter@809
   789
        for (int i = 0; i != _root; ++i) {
kpeter@809
   790
          last_out = _first_out[i+1];
kpeter@809
   791
          for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@809
   792
            if (_forward[j] && _scost[j] < 0) {
kpeter@809
   793
              Value c = _upper[j];
kpeter@809
   794
              if (c >= MAX) return UNBOUNDED;
kpeter@809
   795
              _excess[i] -= c;
kpeter@809
   796
              _excess[_target[j]] += c;
kpeter@809
   797
            }
kpeter@809
   798
          }
kpeter@809
   799
        }
kpeter@809
   800
      }
kpeter@809
   801
      Value ex, max_cap = 0;
kpeter@809
   802
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@809
   803
        ex = _excess[i];
kpeter@809
   804
        _excess[i] = 0;
kpeter@809
   805
        if (ex < 0) max_cap -= ex;
kpeter@809
   806
      }
kpeter@809
   807
      for (int j = 0; j != _res_arc_num; ++j) {
kpeter@809
   808
        if (_upper[j] >= MAX) _upper[j] = max_cap;
kpeter@808
   809
      }
kpeter@808
   810
kpeter@809
   811
      // Initialize the large cost vector and the epsilon parameter
kpeter@809
   812
      _epsilon = 0;
kpeter@809
   813
      LargeCost lc;
kpeter@809
   814
      for (int i = 0; i != _root; ++i) {
kpeter@809
   815
        last_out = _first_out[i+1];
kpeter@809
   816
        for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@809
   817
          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
kpeter@809
   818
          _cost[j] = lc;
kpeter@809
   819
          if (lc > _epsilon) _epsilon = lc;
kpeter@809
   820
        }
kpeter@809
   821
      }
kpeter@809
   822
      _epsilon /= _alpha;
kpeter@808
   823
kpeter@809
   824
      // Initialize maps for Circulation and remove non-zero lower bounds
kpeter@809
   825
      ConstMap<Arc, Value> low(0);
kpeter@809
   826
      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
kpeter@809
   827
      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
kpeter@809
   828
      ValueArcMap cap(_graph), flow(_graph);
kpeter@809
   829
      ValueNodeMap sup(_graph);
kpeter@809
   830
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@809
   831
        sup[n] = _supply[_node_id[n]];
kpeter@808
   832
      }
kpeter@809
   833
      if (_have_lower) {
kpeter@809
   834
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   835
          int j = _arc_idf[a];
kpeter@809
   836
          Value c = _lower[j];
kpeter@809
   837
          cap[a] = _upper[j] - c;
kpeter@809
   838
          sup[_graph.source(a)] -= c;
kpeter@809
   839
          sup[_graph.target(a)] += c;
kpeter@809
   840
        }
kpeter@809
   841
      } else {
kpeter@809
   842
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   843
          cap[a] = _upper[_arc_idf[a]];
kpeter@809
   844
        }
kpeter@809
   845
      }
kpeter@808
   846
kpeter@839
   847
      _sup_node_num = 0;
kpeter@839
   848
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@839
   849
        if (sup[n] > 0) ++_sup_node_num;
kpeter@839
   850
      }
kpeter@839
   851
kpeter@808
   852
      // Find a feasible flow using Circulation
kpeter@809
   853
      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
kpeter@809
   854
        circ(_graph, low, cap, sup);
kpeter@809
   855
      if (!circ.flowMap(flow).run()) return INFEASIBLE;
kpeter@809
   856
kpeter@809
   857
      // Set residual capacities and handle GEQ supply type
kpeter@809
   858
      if (_sum_supply < 0) {
kpeter@809
   859
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   860
          Value fa = flow[a];
kpeter@809
   861
          _res_cap[_arc_idf[a]] = cap[a] - fa;
kpeter@809
   862
          _res_cap[_arc_idb[a]] = fa;
kpeter@809
   863
          sup[_graph.source(a)] -= fa;
kpeter@809
   864
          sup[_graph.target(a)] += fa;
kpeter@809
   865
        }
kpeter@809
   866
        for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@809
   867
          _excess[_node_id[n]] = sup[n];
kpeter@809
   868
        }
kpeter@809
   869
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
kpeter@809
   870
          int u = _target[a];
kpeter@809
   871
          int ra = _reverse[a];
kpeter@809
   872
          _res_cap[a] = -_sum_supply + 1;
kpeter@809
   873
          _res_cap[ra] = -_excess[u];
kpeter@809
   874
          _cost[a] = 0;
kpeter@809
   875
          _cost[ra] = 0;
kpeter@809
   876
          _excess[u] = 0;
kpeter@809
   877
        }
kpeter@809
   878
      } else {
kpeter@809
   879
        for (ArcIt a(_graph); a != INVALID; ++a) {
kpeter@809
   880
          Value fa = flow[a];
kpeter@809
   881
          _res_cap[_arc_idf[a]] = cap[a] - fa;
kpeter@809
   882
          _res_cap[_arc_idb[a]] = fa;
kpeter@809
   883
        }
kpeter@809
   884
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
kpeter@809
   885
          int ra = _reverse[a];
kpeter@839
   886
          _res_cap[a] = 0;
kpeter@809
   887
          _res_cap[ra] = 0;
kpeter@809
   888
          _cost[a] = 0;
kpeter@809
   889
          _cost[ra] = 0;
kpeter@809
   890
        }
kpeter@809
   891
      }
alpar@877
   892
alpar@877
   893
      // Initialize data structures for buckets
kpeter@839
   894
      _max_rank = _alpha * _res_node_num;
kpeter@839
   895
      _buckets.resize(_max_rank);
kpeter@839
   896
      _bucket_next.resize(_res_node_num + 1);
kpeter@839
   897
      _bucket_prev.resize(_res_node_num + 1);
kpeter@839
   898
      _rank.resize(_res_node_num + 1);
alpar@877
   899
kpeter@934
   900
      return OPTIMAL;
kpeter@934
   901
    }
kpeter@934
   902
kpeter@934
   903
    // Execute the algorithm and transform the results
kpeter@934
   904
    void start(Method method) {
kpeter@934
   905
      const int MAX_PARTIAL_PATH_LENGTH = 4;
kpeter@934
   906
kpeter@810
   907
      switch (method) {
kpeter@810
   908
        case PUSH:
kpeter@810
   909
          startPush();
kpeter@810
   910
          break;
kpeter@810
   911
        case AUGMENT:
kpeter@931
   912
          startAugment(_res_node_num - 1);
kpeter@810
   913
          break;
kpeter@810
   914
        case PARTIAL_AUGMENT:
kpeter@934
   915
          startAugment(MAX_PARTIAL_PATH_LENGTH);
kpeter@810
   916
          break;
kpeter@809
   917
      }
kpeter@809
   918
kpeter@937
   919
      // Compute node potentials (dual solution)
kpeter@937
   920
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@937
   921
        _pi[i] = static_cast<Cost>(_pi[i] / (_res_node_num * _alpha));
kpeter@937
   922
      }
kpeter@937
   923
      bool optimal = true;
kpeter@937
   924
      for (int i = 0; optimal && i != _res_node_num; ++i) {
kpeter@937
   925
        LargeCost pi_i = _pi[i];
kpeter@937
   926
        int last_out = _first_out[i+1];
kpeter@937
   927
        for (int j = _first_out[i]; j != last_out; ++j) {
kpeter@937
   928
          if (_res_cap[j] > 0 && _scost[j] + pi_i - _pi[_target[j]] < 0) {
kpeter@937
   929
            optimal = false;
kpeter@937
   930
            break;
kpeter@937
   931
          }
kpeter@809
   932
        }
kpeter@809
   933
      }
kpeter@809
   934
kpeter@937
   935
      if (!optimal) {
kpeter@937
   936
        // Compute node potentials for the original costs with BellmanFord
kpeter@937
   937
        // (if it is necessary)
kpeter@937
   938
        typedef std::pair<int, int> IntPair;
kpeter@937
   939
        StaticDigraph sgr;
kpeter@937
   940
        std::vector<IntPair> arc_vec;
kpeter@937
   941
        std::vector<LargeCost> cost_vec;
kpeter@937
   942
        LargeCostArcMap cost_map(cost_vec);
kpeter@937
   943
kpeter@937
   944
        arc_vec.clear();
kpeter@937
   945
        cost_vec.clear();
kpeter@937
   946
        for (int j = 0; j != _res_arc_num; ++j) {
kpeter@937
   947
          if (_res_cap[j] > 0) {
kpeter@937
   948
            int u = _source[j], v = _target[j];
kpeter@937
   949
            arc_vec.push_back(IntPair(u, v));
kpeter@937
   950
            cost_vec.push_back(_scost[j] + _pi[u] - _pi[v]);
kpeter@937
   951
          }
kpeter@937
   952
        }
kpeter@937
   953
        sgr.build(_res_node_num, arc_vec.begin(), arc_vec.end());
kpeter@937
   954
kpeter@937
   955
        typename BellmanFord<StaticDigraph, LargeCostArcMap>::Create
kpeter@937
   956
          bf(sgr, cost_map);
kpeter@937
   957
        bf.init(0);
kpeter@937
   958
        bf.start();
kpeter@937
   959
kpeter@937
   960
        for (int i = 0; i != _res_node_num; ++i) {
kpeter@937
   961
          _pi[i] += bf.dist(sgr.node(i));
kpeter@937
   962
        }
kpeter@937
   963
      }
kpeter@937
   964
kpeter@937
   965
      // Shift potentials to meet the requirements of the GEQ type
kpeter@937
   966
      // optimality conditions
kpeter@937
   967
      LargeCost max_pot = _pi[_root];
kpeter@937
   968
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@937
   969
        if (_pi[i] > max_pot) max_pot = _pi[i];
kpeter@937
   970
      }
kpeter@937
   971
      if (max_pot != 0) {
kpeter@937
   972
        for (int i = 0; i != _res_node_num; ++i) {
kpeter@937
   973
          _pi[i] -= max_pot;
kpeter@937
   974
        }
kpeter@937
   975
      }
kpeter@809
   976
kpeter@809
   977
      // Handle non-zero lower bounds
kpeter@809
   978
      if (_have_lower) {
kpeter@809
   979
        int limit = _first_out[_root];
kpeter@809
   980
        for (int j = 0; j != limit; ++j) {
kpeter@809
   981
          if (!_forward[j]) _res_cap[j] += _lower[j];
kpeter@809
   982
        }
kpeter@809
   983
      }
kpeter@808
   984
    }
alpar@877
   985
kpeter@839
   986
    // Initialize a cost scaling phase
kpeter@839
   987
    void initPhase() {
kpeter@839
   988
      // Saturate arcs not satisfying the optimality condition
kpeter@839
   989
      for (int u = 0; u != _res_node_num; ++u) {
kpeter@839
   990
        int last_out = _first_out[u+1];
kpeter@839
   991
        LargeCost pi_u = _pi[u];
kpeter@839
   992
        for (int a = _first_out[u]; a != last_out; ++a) {
kpeter@934
   993
          Value delta = _res_cap[a];
kpeter@934
   994
          if (delta > 0) {
kpeter@934
   995
            int v = _target[a];
kpeter@934
   996
            if (_cost[a] + pi_u - _pi[v] < 0) {
kpeter@934
   997
              _excess[u] -= delta;
kpeter@934
   998
              _excess[v] += delta;
kpeter@934
   999
              _res_cap[a] = 0;
kpeter@934
  1000
              _res_cap[_reverse[a]] += delta;
kpeter@934
  1001
            }
kpeter@839
  1002
          }
kpeter@839
  1003
        }
kpeter@839
  1004
      }
alpar@877
  1005
kpeter@839
  1006
      // Find active nodes (i.e. nodes with positive excess)
kpeter@839
  1007
      for (int u = 0; u != _res_node_num; ++u) {
kpeter@839
  1008
        if (_excess[u] > 0) _active_nodes.push_back(u);
kpeter@839
  1009
      }
kpeter@839
  1010
kpeter@839
  1011
      // Initialize the next arcs
kpeter@839
  1012
      for (int u = 0; u != _res_node_num; ++u) {
kpeter@839
  1013
        _next_out[u] = _first_out[u];
kpeter@839
  1014
      }
kpeter@839
  1015
    }
alpar@877
  1016
kpeter@936
  1017
    // Price (potential) refinement heuristic
kpeter@936
  1018
    bool priceRefinement() {
kpeter@839
  1019
kpeter@936
  1020
      // Stack for stroing the topological order
kpeter@936
  1021
      IntVector stack(_res_node_num);
kpeter@936
  1022
      int stack_top;
kpeter@936
  1023
kpeter@936
  1024
      // Perform phases
kpeter@936
  1025
      while (topologicalSort(stack, stack_top)) {
kpeter@936
  1026
kpeter@936
  1027
        // Compute node ranks in the acyclic admissible network and
kpeter@936
  1028
        // store the nodes in buckets
kpeter@936
  1029
        for (int i = 0; i != _res_node_num; ++i) {
kpeter@936
  1030
          _rank[i] = 0;
kpeter@839
  1031
        }
kpeter@936
  1032
        const int bucket_end = _root + 1;
kpeter@936
  1033
        for (int r = 0; r != _max_rank; ++r) {
kpeter@936
  1034
          _buckets[r] = bucket_end;
kpeter@936
  1035
        }
kpeter@936
  1036
        int top_rank = 0;
kpeter@936
  1037
        for ( ; stack_top >= 0; --stack_top) {
kpeter@936
  1038
          int u = stack[stack_top], v;
kpeter@936
  1039
          int rank_u = _rank[u];
kpeter@936
  1040
kpeter@936
  1041
          LargeCost rc, pi_u = _pi[u];
kpeter@936
  1042
          int last_out = _first_out[u+1];
kpeter@936
  1043
          for (int a = _first_out[u]; a != last_out; ++a) {
kpeter@936
  1044
            if (_res_cap[a] > 0) {
kpeter@936
  1045
              v = _target[a];
kpeter@936
  1046
              rc = _cost[a] + pi_u - _pi[v];
kpeter@936
  1047
              if (rc < 0) {
kpeter@936
  1048
                LargeCost nrc = static_cast<LargeCost>((-rc - 0.5) / _epsilon);
kpeter@936
  1049
                if (nrc < LargeCost(_max_rank)) {
kpeter@936
  1050
                  int new_rank_v = rank_u + static_cast<int>(nrc);
kpeter@936
  1051
                  if (new_rank_v > _rank[v]) {
kpeter@936
  1052
                    _rank[v] = new_rank_v;
kpeter@936
  1053
                  }
kpeter@936
  1054
                }
kpeter@936
  1055
              }
kpeter@936
  1056
            }
kpeter@936
  1057
          }
kpeter@936
  1058
kpeter@936
  1059
          if (rank_u > 0) {
kpeter@936
  1060
            top_rank = std::max(top_rank, rank_u);
kpeter@936
  1061
            int bfirst = _buckets[rank_u];
kpeter@936
  1062
            _bucket_next[u] = bfirst;
kpeter@936
  1063
            _bucket_prev[bfirst] = u;
kpeter@936
  1064
            _buckets[rank_u] = u;
kpeter@936
  1065
          }
kpeter@936
  1066
        }
kpeter@936
  1067
kpeter@936
  1068
        // Check if the current flow is epsilon-optimal
kpeter@936
  1069
        if (top_rank == 0) {
kpeter@936
  1070
          return true;
kpeter@936
  1071
        }
kpeter@936
  1072
kpeter@936
  1073
        // Process buckets in top-down order
kpeter@936
  1074
        for (int rank = top_rank; rank > 0; --rank) {
kpeter@936
  1075
          while (_buckets[rank] != bucket_end) {
kpeter@936
  1076
            // Remove the first node from the current bucket
kpeter@936
  1077
            int u = _buckets[rank];
kpeter@936
  1078
            _buckets[rank] = _bucket_next[u];
kpeter@936
  1079
kpeter@936
  1080
            // Search the outgoing arcs of u
kpeter@936
  1081
            LargeCost rc, pi_u = _pi[u];
kpeter@936
  1082
            int last_out = _first_out[u+1];
kpeter@936
  1083
            int v, old_rank_v, new_rank_v;
kpeter@936
  1084
            for (int a = _first_out[u]; a != last_out; ++a) {
kpeter@936
  1085
              if (_res_cap[a] > 0) {
kpeter@936
  1086
                v = _target[a];
kpeter@936
  1087
                old_rank_v = _rank[v];
kpeter@936
  1088
kpeter@936
  1089
                if (old_rank_v < rank) {
kpeter@936
  1090
kpeter@936
  1091
                  // Compute the new rank of node v
kpeter@936
  1092
                  rc = _cost[a] + pi_u - _pi[v];
kpeter@936
  1093
                  if (rc < 0) {
kpeter@936
  1094
                    new_rank_v = rank;
kpeter@936
  1095
                  } else {
kpeter@936
  1096
                    LargeCost nrc = rc / _epsilon;
kpeter@936
  1097
                    new_rank_v = 0;
kpeter@936
  1098
                    if (nrc < LargeCost(_max_rank)) {
kpeter@936
  1099
                      new_rank_v = rank - 1 - static_cast<int>(nrc);
kpeter@936
  1100
                    }
kpeter@936
  1101
                  }
kpeter@936
  1102
kpeter@936
  1103
                  // Change the rank of node v
kpeter@936
  1104
                  if (new_rank_v > old_rank_v) {
kpeter@936
  1105
                    _rank[v] = new_rank_v;
kpeter@936
  1106
kpeter@936
  1107
                    // Remove v from its old bucket
kpeter@936
  1108
                    if (old_rank_v > 0) {
kpeter@936
  1109
                      if (_buckets[old_rank_v] == v) {
kpeter@936
  1110
                        _buckets[old_rank_v] = _bucket_next[v];
kpeter@936
  1111
                      } else {
kpeter@936
  1112
                        int pv = _bucket_prev[v], nv = _bucket_next[v];
kpeter@936
  1113
                        _bucket_next[pv] = nv;
kpeter@936
  1114
                        _bucket_prev[nv] = pv;
kpeter@936
  1115
                      }
kpeter@936
  1116
                    }
kpeter@936
  1117
kpeter@936
  1118
                    // Insert v into its new bucket
kpeter@936
  1119
                    int nv = _buckets[new_rank_v];
kpeter@936
  1120
                    _bucket_next[v] = nv;
kpeter@936
  1121
                    _bucket_prev[nv] = v;
kpeter@936
  1122
                    _buckets[new_rank_v] = v;
kpeter@936
  1123
                  }
kpeter@936
  1124
                }
kpeter@936
  1125
              }
kpeter@936
  1126
            }
kpeter@936
  1127
kpeter@936
  1128
            // Refine potential of node u
kpeter@936
  1129
            _pi[u] -= rank * _epsilon;
kpeter@936
  1130
          }
kpeter@936
  1131
        }
kpeter@936
  1132
kpeter@839
  1133
      }
kpeter@839
  1134
kpeter@936
  1135
      return false;
kpeter@936
  1136
    }
kpeter@936
  1137
kpeter@936
  1138
    // Find and cancel cycles in the admissible network and
kpeter@936
  1139
    // determine topological order using DFS
kpeter@936
  1140
    bool topologicalSort(IntVector &stack, int &stack_top) {
kpeter@936
  1141
      const int MAX_CYCLE_CANCEL = 1;
kpeter@936
  1142
kpeter@936
  1143
      BoolVector reached(_res_node_num, false);
kpeter@936
  1144
      BoolVector processed(_res_node_num, false);
kpeter@936
  1145
      IntVector pred(_res_node_num);
kpeter@936
  1146
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@936
  1147
        _next_out[i] = _first_out[i];
kpeter@839
  1148
      }
kpeter@936
  1149
      stack_top = -1;
kpeter@936
  1150
kpeter@936
  1151
      int cycle_cnt = 0;
kpeter@936
  1152
      for (int start = 0; start != _res_node_num; ++start) {
kpeter@936
  1153
        if (reached[start]) continue;
kpeter@936
  1154
kpeter@936
  1155
        // Start DFS search from this start node
kpeter@936
  1156
        pred[start] = -1;
kpeter@936
  1157
        int tip = start, v;
kpeter@936
  1158
        while (true) {
kpeter@936
  1159
          // Check the outgoing arcs of the current tip node
kpeter@936
  1160
          reached[tip] = true;
kpeter@936
  1161
          LargeCost pi_tip = _pi[tip];
kpeter@936
  1162
          int a, last_out = _first_out[tip+1];
kpeter@936
  1163
          for (a = _next_out[tip]; a != last_out; ++a) {
kpeter@936
  1164
            if (_res_cap[a] > 0) {
kpeter@936
  1165
              v = _target[a];
kpeter@936
  1166
              if (_cost[a] + pi_tip - _pi[v] < 0) {
kpeter@936
  1167
                if (!reached[v]) {
kpeter@936
  1168
                  // A new node is reached
kpeter@936
  1169
                  reached[v] = true;
kpeter@936
  1170
                  pred[v] = tip;
kpeter@936
  1171
                  _next_out[tip] = a;
kpeter@936
  1172
                  tip = v;
kpeter@936
  1173
                  a = _next_out[tip];
kpeter@936
  1174
                  last_out = _first_out[tip+1];
kpeter@936
  1175
                  break;
kpeter@936
  1176
                }
kpeter@936
  1177
                else if (!processed[v]) {
kpeter@936
  1178
                  // A cycle is found
kpeter@936
  1179
                  ++cycle_cnt;
kpeter@936
  1180
                  _next_out[tip] = a;
kpeter@936
  1181
kpeter@936
  1182
                  // Find the minimum residual capacity along the cycle
kpeter@936
  1183
                  Value d, delta = _res_cap[a];
kpeter@936
  1184
                  int u, delta_node = tip;
kpeter@936
  1185
                  for (u = tip; u != v; ) {
kpeter@936
  1186
                    u = pred[u];
kpeter@936
  1187
                    d = _res_cap[_next_out[u]];
kpeter@936
  1188
                    if (d <= delta) {
kpeter@936
  1189
                      delta = d;
kpeter@936
  1190
                      delta_node = u;
kpeter@936
  1191
                    }
kpeter@936
  1192
                  }
kpeter@936
  1193
kpeter@936
  1194
                  // Augment along the cycle
kpeter@936
  1195
                  _res_cap[a] -= delta;
kpeter@936
  1196
                  _res_cap[_reverse[a]] += delta;
kpeter@936
  1197
                  for (u = tip; u != v; ) {
kpeter@936
  1198
                    u = pred[u];
kpeter@936
  1199
                    int ca = _next_out[u];
kpeter@936
  1200
                    _res_cap[ca] -= delta;
kpeter@936
  1201
                    _res_cap[_reverse[ca]] += delta;
kpeter@936
  1202
                  }
kpeter@936
  1203
kpeter@936
  1204
                  // Check the maximum number of cycle canceling
kpeter@936
  1205
                  if (cycle_cnt >= MAX_CYCLE_CANCEL) {
kpeter@936
  1206
                    return false;
kpeter@936
  1207
                  }
kpeter@936
  1208
kpeter@936
  1209
                  // Roll back search to delta_node
kpeter@936
  1210
                  if (delta_node != tip) {
kpeter@936
  1211
                    for (u = tip; u != delta_node; u = pred[u]) {
kpeter@936
  1212
                      reached[u] = false;
kpeter@936
  1213
                    }
kpeter@936
  1214
                    tip = delta_node;
kpeter@936
  1215
                    a = _next_out[tip] + 1;
kpeter@936
  1216
                    last_out = _first_out[tip+1];
kpeter@936
  1217
                    break;
kpeter@936
  1218
                  }
kpeter@936
  1219
                }
kpeter@936
  1220
              }
kpeter@936
  1221
            }
kpeter@936
  1222
          }
kpeter@936
  1223
kpeter@936
  1224
          // Step back to the previous node
kpeter@936
  1225
          if (a == last_out) {
kpeter@936
  1226
            processed[tip] = true;
kpeter@936
  1227
            stack[++stack_top] = tip;
kpeter@936
  1228
            tip = pred[tip];
kpeter@936
  1229
            if (tip < 0) {
kpeter@936
  1230
              // Finish DFS from the current start node
kpeter@936
  1231
              break;
kpeter@936
  1232
            }
kpeter@936
  1233
            ++_next_out[tip];
kpeter@936
  1234
          }
kpeter@936
  1235
        }
kpeter@936
  1236
kpeter@936
  1237
      }
kpeter@936
  1238
kpeter@936
  1239
      return (cycle_cnt == 0);
kpeter@839
  1240
    }
kpeter@839
  1241
kpeter@839
  1242
    // Global potential update heuristic
kpeter@839
  1243
    void globalUpdate() {
kpeter@934
  1244
      const int bucket_end = _root + 1;
alpar@877
  1245
kpeter@839
  1246
      // Initialize buckets
kpeter@839
  1247
      for (int r = 0; r != _max_rank; ++r) {
kpeter@839
  1248
        _buckets[r] = bucket_end;
kpeter@839
  1249
      }
kpeter@839
  1250
      Value total_excess = 0;
kpeter@934
  1251
      int b0 = bucket_end;
kpeter@839
  1252
      for (int i = 0; i != _res_node_num; ++i) {
kpeter@839
  1253
        if (_excess[i] < 0) {
kpeter@839
  1254
          _rank[i] = 0;
kpeter@934
  1255
          _bucket_next[i] = b0;
kpeter@934
  1256
          _bucket_prev[b0] = i;
kpeter@934
  1257
          b0 = i;
kpeter@839
  1258
        } else {
kpeter@839
  1259
          total_excess += _excess[i];
kpeter@839
  1260
          _rank[i] = _max_rank;
kpeter@839
  1261
        }
kpeter@839
  1262
      }
kpeter@839
  1263
      if (total_excess == 0) return;
kpeter@934
  1264
      _buckets[0] = b0;
kpeter@839
  1265
kpeter@839
  1266
      // Search the buckets
kpeter@839
  1267
      int r = 0;
kpeter@839
  1268
      for ( ; r != _max_rank; ++r) {
kpeter@839
  1269
        while (_buckets[r] != bucket_end) {
kpeter@839
  1270
          // Remove the first node from the current bucket
kpeter@839
  1271
          int u = _buckets[r];
kpeter@839
  1272
          _buckets[r] = _bucket_next[u];
alpar@877
  1273
kpeter@1049
  1274
          // Search the incoming arcs of u
kpeter@839
  1275
          LargeCost pi_u = _pi[u];
kpeter@839
  1276
          int last_out = _first_out[u+1];
kpeter@839
  1277
          for (int a = _first_out[u]; a != last_out; ++a) {
kpeter@839
  1278
            int ra = _reverse[a];
kpeter@839
  1279
            if (_res_cap[ra] > 0) {
kpeter@839
  1280
              int v = _source[ra];
kpeter@839
  1281
              int old_rank_v = _rank[v];
kpeter@839
  1282
              if (r < old_rank_v) {
kpeter@839
  1283
                // Compute the new rank of v
kpeter@839
  1284
                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
kpeter@839
  1285
                int new_rank_v = old_rank_v;
kpeter@934
  1286
                if (nrc < LargeCost(_max_rank)) {
kpeter@934
  1287
                  new_rank_v = r + 1 + static_cast<int>(nrc);
kpeter@934
  1288
                }
alpar@877
  1289
kpeter@839
  1290
                // Change the rank of v
kpeter@839
  1291
                if (new_rank_v < old_rank_v) {
kpeter@839
  1292
                  _rank[v] = new_rank_v;
kpeter@839
  1293
                  _next_out[v] = _first_out[v];
alpar@877
  1294
kpeter@839
  1295
                  // Remove v from its old bucket
kpeter@839
  1296
                  if (old_rank_v < _max_rank) {
kpeter@839
  1297
                    if (_buckets[old_rank_v] == v) {
kpeter@839
  1298
                      _buckets[old_rank_v] = _bucket_next[v];
kpeter@839
  1299
                    } else {
kpeter@934
  1300
                      int pv = _bucket_prev[v], nv = _bucket_next[v];
kpeter@934
  1301
                      _bucket_next[pv] = nv;
kpeter@934
  1302
                      _bucket_prev[nv] = pv;
kpeter@839
  1303
                    }
kpeter@839
  1304
                  }
alpar@877
  1305
kpeter@934
  1306
                  // Insert v into its new bucket
kpeter@934
  1307
                  int nv = _buckets[new_rank_v];
kpeter@934
  1308
                  _bucket_next[v] = nv;
kpeter@934
  1309
                  _bucket_prev[nv] = v;
kpeter@839
  1310
                  _buckets[new_rank_v] = v;
kpeter@839
  1311
                }
kpeter@839
  1312
              }
kpeter@839
  1313
            }
kpeter@839
  1314
          }
kpeter@839
  1315
kpeter@839
  1316
          // Finish search if there are no more active nodes
kpeter@839
  1317
          if (_excess[u] > 0) {
kpeter@839
  1318
            total_excess -= _excess[u];
kpeter@839
  1319
            if (total_excess <= 0) break;
kpeter@839
  1320
          }
kpeter@839
  1321
        }
kpeter@839
  1322
        if (total_excess <= 0) break;
kpeter@839
  1323
      }
alpar@877
  1324
kpeter@839
  1325
      // Relabel nodes
kpeter@839
  1326
      for (int u = 0; u != _res_node_num; ++u) {
kpeter@839
  1327
        int k = std::min(_rank[u], r);
kpeter@839
  1328
        if (k > 0) {
kpeter@839
  1329
          _pi[u] -= _epsilon * k;
kpeter@839
  1330
          _next_out[u] = _first_out[u];
kpeter@839
  1331
        }
kpeter@839
  1332
      }
kpeter@839
  1333
    }
kpeter@808
  1334
kpeter@810
  1335
    /// Execute the algorithm performing augment and relabel operations
kpeter@931
  1336
    void startAugment(int max_length) {
kpeter@808
  1337
      // Paramters for heuristics
kpeter@936
  1338
      const int PRICE_REFINEMENT_LIMIT = 2;
kpeter@935
  1339
      const double GLOBAL_UPDATE_FACTOR = 1.0;
kpeter@935
  1340
      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
kpeter@839
  1341
        (_res_node_num + _sup_node_num * _sup_node_num));
kpeter@935
  1342
      int next_global_update_limit = global_update_skip;
alpar@877
  1343
kpeter@809
  1344
      // Perform cost scaling phases
kpeter@935
  1345
      IntVector path;
kpeter@935
  1346
      BoolVector path_arc(_res_arc_num, false);
kpeter@935
  1347
      int relabel_cnt = 0;
kpeter@936
  1348
      int eps_phase_cnt = 0;
kpeter@808
  1349
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
kpeter@808
  1350
                                        1 : _epsilon / _alpha )
kpeter@808
  1351
      {
kpeter@936
  1352
        ++eps_phase_cnt;
kpeter@936
  1353
kpeter@936
  1354
        // Price refinement heuristic
kpeter@936
  1355
        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
kpeter@936
  1356
          if (priceRefinement()) continue;
kpeter@808
  1357
        }
alpar@877
  1358
kpeter@839
  1359
        // Initialize current phase
kpeter@839
  1360
        initPhase();
alpar@877
  1361
kpeter@808
  1362
        // Perform partial augment and relabel operations
kpeter@809
  1363
        while (true) {
kpeter@808
  1364
          // Select an active node (FIFO selection)
kpeter@809
  1365
          while (_active_nodes.size() > 0 &&
kpeter@809
  1366
                 _excess[_active_nodes.front()] <= 0) {
kpeter@809
  1367
            _active_nodes.pop_front();
kpeter@808
  1368
          }
kpeter@809
  1369
          if (_active_nodes.size() == 0) break;
kpeter@809
  1370
          int start = _active_nodes.front();
kpeter@808
  1371
kpeter@808
  1372
          // Find an augmenting path from the start node
kpeter@809
  1373
          int tip = start;
kpeter@935
  1374
          while (int(path.size()) < max_length && _excess[tip] >= 0) {
kpeter@809
  1375
            int u;
kpeter@935
  1376
            LargeCost rc, min_red_cost = std::numeric_limits<LargeCost>::max();
kpeter@935
  1377
            LargeCost pi_tip = _pi[tip];
kpeter@839
  1378
            int last_out = _first_out[tip+1];
kpeter@809
  1379
            for (int a = _next_out[tip]; a != last_out; ++a) {
kpeter@935
  1380
              if (_res_cap[a] > 0) {
kpeter@935
  1381
                u = _target[a];
kpeter@935
  1382
                rc = _cost[a] + pi_tip - _pi[u];
kpeter@935
  1383
                if (rc < 0) {
kpeter@935
  1384
                  path.push_back(a);
kpeter@935
  1385
                  _next_out[tip] = a;
kpeter@935
  1386
                  if (path_arc[a]) {
kpeter@935
  1387
                    goto augment;   // a cycle is found, stop path search
kpeter@935
  1388
                  }
kpeter@935
  1389
                  tip = u;
kpeter@935
  1390
                  path_arc[a] = true;
kpeter@935
  1391
                  goto next_step;
kpeter@935
  1392
                }
kpeter@935
  1393
                else if (rc < min_red_cost) {
kpeter@935
  1394
                  min_red_cost = rc;
kpeter@935
  1395
                }
kpeter@808
  1396
              }
kpeter@808
  1397
            }
kpeter@808
  1398
kpeter@808
  1399
            // Relabel tip node
kpeter@839
  1400
            if (tip != start) {
kpeter@839
  1401
              int ra = _reverse[path.back()];
kpeter@935
  1402
              min_red_cost =
kpeter@935
  1403
                std::min(min_red_cost, _cost[ra] + pi_tip - _pi[_target[ra]]);
kpeter@839
  1404
            }
kpeter@935
  1405
            last_out = _next_out[tip];
kpeter@809
  1406
            for (int a = _first_out[tip]; a != last_out; ++a) {
kpeter@935
  1407
              if (_res_cap[a] > 0) {
kpeter@935
  1408
                rc = _cost[a] + pi_tip - _pi[_target[a]];
kpeter@935
  1409
                if (rc < min_red_cost) {
kpeter@935
  1410
                  min_red_cost = rc;
kpeter@935
  1411
                }
kpeter@809
  1412
              }
kpeter@808
  1413
            }
kpeter@809
  1414
            _pi[tip] -= min_red_cost + _epsilon;
kpeter@809
  1415
            _next_out[tip] = _first_out[tip];
kpeter@839
  1416
            ++relabel_cnt;
kpeter@808
  1417
kpeter@808
  1418
            // Step back
kpeter@808
  1419
            if (tip != start) {
kpeter@935
  1420
              int pa = path.back();
kpeter@935
  1421
              path_arc[pa] = false;
kpeter@935
  1422
              tip = _source[pa];
kpeter@839
  1423
              path.pop_back();
kpeter@808
  1424
            }
kpeter@808
  1425
kpeter@809
  1426
          next_step: ;
kpeter@808
  1427
          }
kpeter@808
  1428
kpeter@808
  1429
          // Augment along the found path (as much flow as possible)
kpeter@935
  1430
        augment:
kpeter@809
  1431
          Value delta;
kpeter@839
  1432
          int pa, u, v = start;
kpeter@839
  1433
          for (int i = 0; i != int(path.size()); ++i) {
kpeter@839
  1434
            pa = path[i];
kpeter@809
  1435
            u = v;
kpeter@839
  1436
            v = _target[pa];
kpeter@935
  1437
            path_arc[pa] = false;
kpeter@809
  1438
            delta = std::min(_res_cap[pa], _excess[u]);
kpeter@809
  1439
            _res_cap[pa] -= delta;
kpeter@809
  1440
            _res_cap[_reverse[pa]] += delta;
kpeter@809
  1441
            _excess[u] -= delta;
kpeter@809
  1442
            _excess[v] += delta;
kpeter@935
  1443
            if (_excess[v] > 0 && _excess[v] <= delta) {
kpeter@809
  1444
              _active_nodes.push_back(v);
kpeter@935
  1445
            }
kpeter@808
  1446
          }
kpeter@935
  1447
          path.clear();
kpeter@839
  1448
kpeter@839
  1449
          // Global update heuristic
kpeter@935
  1450
          if (relabel_cnt >= next_global_update_limit) {
kpeter@839
  1451
            globalUpdate();
kpeter@935
  1452
            next_global_update_limit += global_update_skip;
kpeter@839
  1453
          }
kpeter@808
  1454
        }
kpeter@935
  1455
kpeter@808
  1456
      }
kpeter@935
  1457
kpeter@808
  1458
    }
kpeter@808
  1459
kpeter@809
  1460
    /// Execute the algorithm performing push and relabel operations
kpeter@810
  1461
    void startPush() {
kpeter@808
  1462
      // Paramters for heuristics
kpeter@936
  1463
      const int PRICE_REFINEMENT_LIMIT = 2;
kpeter@839
  1464
      const double GLOBAL_UPDATE_FACTOR = 2.0;
kpeter@808
  1465
kpeter@935
  1466
      const int global_update_skip = static_cast<int>(GLOBAL_UPDATE_FACTOR *
kpeter@839
  1467
        (_res_node_num + _sup_node_num * _sup_node_num));
kpeter@935
  1468
      int next_global_update_limit = global_update_skip;
alpar@877
  1469
kpeter@809
  1470
      // Perform cost scaling phases
kpeter@809
  1471
      BoolVector hyper(_res_node_num, false);
kpeter@839
  1472
      LargeCostVector hyper_cost(_res_node_num);
kpeter@935
  1473
      int relabel_cnt = 0;
kpeter@936
  1474
      int eps_phase_cnt = 0;
kpeter@808
  1475
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
kpeter@808
  1476
                                        1 : _epsilon / _alpha )
kpeter@808
  1477
      {
kpeter@936
  1478
        ++eps_phase_cnt;
kpeter@936
  1479
kpeter@936
  1480
        // Price refinement heuristic
kpeter@936
  1481
        if (eps_phase_cnt >= PRICE_REFINEMENT_LIMIT) {
kpeter@936
  1482
          if (priceRefinement()) continue;
kpeter@808
  1483
        }
alpar@877
  1484
kpeter@839
  1485
        // Initialize current phase
kpeter@839
  1486
        initPhase();
kpeter@808
  1487
kpeter@808
  1488
        // Perform push and relabel operations
kpeter@809
  1489
        while (_active_nodes.size() > 0) {
kpeter@839
  1490
          LargeCost min_red_cost, rc, pi_n;
kpeter@809
  1491
          Value delta;
kpeter@809
  1492
          int n, t, a, last_out = _res_arc_num;
kpeter@809
  1493
kpeter@839
  1494
        next_node:
kpeter@808
  1495
          // Select an active node (FIFO selection)
kpeter@809
  1496
          n = _active_nodes.front();
kpeter@839
  1497
          last_out = _first_out[n+1];
kpeter@839
  1498
          pi_n = _pi[n];
alpar@877
  1499
kpeter@808
  1500
          // Perform push operations if there are admissible arcs
kpeter@809
  1501
          if (_excess[n] > 0) {
kpeter@809
  1502
            for (a = _next_out[n]; a != last_out; ++a) {
kpeter@809
  1503
              if (_res_cap[a] > 0 &&
kpeter@839
  1504
                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
kpeter@809
  1505
                delta = std::min(_res_cap[a], _excess[n]);
kpeter@809
  1506
                t = _target[a];
kpeter@808
  1507
kpeter@808
  1508
                // Push-look-ahead heuristic
kpeter@809
  1509
                Value ahead = -_excess[t];
kpeter@839
  1510
                int last_out_t = _first_out[t+1];
kpeter@839
  1511
                LargeCost pi_t = _pi[t];
kpeter@809
  1512
                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
alpar@877
  1513
                  if (_res_cap[ta] > 0 &&
kpeter@839
  1514
                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
kpeter@809
  1515
                    ahead += _res_cap[ta];
kpeter@809
  1516
                  if (ahead >= delta) break;
kpeter@808
  1517
                }
kpeter@808
  1518
                if (ahead < 0) ahead = 0;
kpeter@808
  1519
kpeter@808
  1520
                // Push flow along the arc
kpeter@839
  1521
                if (ahead < delta && !hyper[t]) {
kpeter@809
  1522
                  _res_cap[a] -= ahead;
kpeter@809
  1523
                  _res_cap[_reverse[a]] += ahead;
kpeter@808
  1524
                  _excess[n] -= ahead;
kpeter@808
  1525
                  _excess[t] += ahead;
kpeter@809
  1526
                  _active_nodes.push_front(t);
kpeter@808
  1527
                  hyper[t] = true;
kpeter@839
  1528
                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
kpeter@809
  1529
                  _next_out[n] = a;
kpeter@809
  1530
                  goto next_node;
kpeter@808
  1531
                } else {
kpeter@809
  1532
                  _res_cap[a] -= delta;
kpeter@809
  1533
                  _res_cap[_reverse[a]] += delta;
kpeter@808
  1534
                  _excess[n] -= delta;
kpeter@808
  1535
                  _excess[t] += delta;
kpeter@808
  1536
                  if (_excess[t] > 0 && _excess[t] <= delta)
kpeter@809
  1537
                    _active_nodes.push_back(t);
kpeter@808
  1538
                }
kpeter@808
  1539
kpeter@809
  1540
                if (_excess[n] == 0) {
kpeter@809
  1541
                  _next_out[n] = a;
kpeter@809
  1542
                  goto remove_nodes;
kpeter@809
  1543
                }
kpeter@808
  1544
              }
kpeter@808
  1545
            }
kpeter@809
  1546
            _next_out[n] = a;
kpeter@808
  1547
          }
kpeter@808
  1548
kpeter@808
  1549
          // Relabel the node if it is still active (or hyper)
kpeter@809
  1550
          if (_excess[n] > 0 || hyper[n]) {
kpeter@839
  1551
             min_red_cost = hyper[n] ? -hyper_cost[n] :
kpeter@839
  1552
               std::numeric_limits<LargeCost>::max();
kpeter@809
  1553
            for (int a = _first_out[n]; a != last_out; ++a) {
kpeter@935
  1554
              if (_res_cap[a] > 0) {
kpeter@935
  1555
                rc = _cost[a] + pi_n - _pi[_target[a]];
kpeter@935
  1556
                if (rc < min_red_cost) {
kpeter@935
  1557
                  min_red_cost = rc;
kpeter@935
  1558
                }
kpeter@809
  1559
              }
kpeter@808
  1560
            }
kpeter@809
  1561
            _pi[n] -= min_red_cost + _epsilon;
kpeter@839
  1562
            _next_out[n] = _first_out[n];
kpeter@808
  1563
            hyper[n] = false;
kpeter@839
  1564
            ++relabel_cnt;
kpeter@808
  1565
          }
alpar@877
  1566
kpeter@808
  1567
          // Remove nodes that are not active nor hyper
kpeter@809
  1568
        remove_nodes:
kpeter@809
  1569
          while ( _active_nodes.size() > 0 &&
kpeter@809
  1570
                  _excess[_active_nodes.front()] <= 0 &&
kpeter@809
  1571
                  !hyper[_active_nodes.front()] ) {
kpeter@809
  1572
            _active_nodes.pop_front();
kpeter@808
  1573
          }
alpar@877
  1574
kpeter@839
  1575
          // Global update heuristic
kpeter@935
  1576
          if (relabel_cnt >= next_global_update_limit) {
kpeter@839
  1577
            globalUpdate();
kpeter@839
  1578
            for (int u = 0; u != _res_node_num; ++u)
kpeter@839
  1579
              hyper[u] = false;
kpeter@935
  1580
            next_global_update_limit += global_update_skip;
kpeter@839
  1581
          }
kpeter@808
  1582
        }
kpeter@808
  1583
      }
kpeter@808
  1584
    }
kpeter@808
  1585
kpeter@808
  1586
  }; //class CostScaling
kpeter@808
  1587
kpeter@808
  1588
  ///@}
kpeter@808
  1589
kpeter@808
  1590
} //namespace lemon
kpeter@808
  1591
kpeter@808
  1592
#endif //LEMON_COST_SCALING_H