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