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