lemon/cost_scaling.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 12 Nov 2009 23:30:45 +0100
changeset 809 22bb98ca0101
parent 808 9c428bb2b105
child 810 3b53491bf643
permissions -rw-r--r--
Entirely rework CostScaling (#180)

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