lemon/cost_scaling.h
author Peter Kovacs <kpeter@inf.elte.hu>
Wed, 10 Feb 2010 19:05:20 +0100
changeset 830 75c97c3786d6
parent 821 072ec8120958
child 831 cc9e0c15d747
permissions -rw-r--r--
Handle graph changes in the MCF algorithms (#327)

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