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