lemon/cost_scaling.h
author Peter Kovacs <kpeter@inf.elte.hu>
Sat, 20 Feb 2010 18:39:03 +0100
changeset 910 f3bc4e9b5f3a
parent 887 072ec8120958
child 911 2914b6f0fde0
permissions -rw-r--r--
New heuristics for MCF algorithms (#340)
and some implementation improvements.

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