lemon/circulation.h
author Alpar Juttner <alpar@cs.elte.hu>
Thu, 13 Sep 2012 11:56:19 +0200
changeset 1159 7fdaa05a69a1
parent 956 141f9c0db4a3
parent 1157 761fe0846f49
child 1250 97d978243703
permissions -rw-r--r--
Merge #449 to branches >=1.2
alpar@414
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
alpar@414
     2
 *
alpar@414
     3
 * This file is a part of LEMON, a generic C++ optimization library.
alpar@414
     4
 *
alpar@956
     5
 * Copyright (C) 2003-2010
alpar@414
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@414
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@414
     8
 *
alpar@414
     9
 * Permission to use, modify and distribute this software is granted
alpar@414
    10
 * provided that this copyright notice appears in all copies. For
alpar@414
    11
 * precise terms see the accompanying LICENSE file.
alpar@414
    12
 *
alpar@414
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@414
    14
 * express or implied, and with no claim as to its suitability for any
alpar@414
    15
 * purpose.
alpar@414
    16
 *
alpar@414
    17
 */
alpar@414
    18
alpar@414
    19
#ifndef LEMON_CIRCULATION_H
alpar@414
    20
#define LEMON_CIRCULATION_H
alpar@414
    21
alpar@414
    22
#include <lemon/tolerance.h>
alpar@414
    23
#include <lemon/elevator.h>
kpeter@669
    24
#include <limits>
alpar@414
    25
alpar@414
    26
///\ingroup max_flow
alpar@414
    27
///\file
kpeter@417
    28
///\brief Push-relabel algorithm for finding a feasible circulation.
alpar@414
    29
///
alpar@414
    30
namespace lemon {
alpar@414
    31
alpar@414
    32
  /// \brief Default traits class of Circulation class.
alpar@414
    33
  ///
alpar@414
    34
  /// Default traits class of Circulation class.
kpeter@657
    35
  ///
kpeter@657
    36
  /// \tparam GR Type of the digraph the algorithm runs on.
kpeter@657
    37
  /// \tparam LM The type of the lower bound map.
kpeter@657
    38
  /// \tparam UM The type of the upper bound (capacity) map.
kpeter@657
    39
  /// \tparam SM The type of the supply map.
kpeter@525
    40
  template <typename GR, typename LM,
kpeter@657
    41
            typename UM, typename SM>
alpar@414
    42
  struct CirculationDefaultTraits {
alpar@414
    43
kpeter@417
    44
    /// \brief The type of the digraph the algorithm runs on.
kpeter@525
    45
    typedef GR Digraph;
alpar@414
    46
kpeter@657
    47
    /// \brief The type of the lower bound map.
alpar@414
    48
    ///
kpeter@657
    49
    /// The type of the map that stores the lower bounds on the arcs.
kpeter@657
    50
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@657
    51
    typedef LM LowerMap;
alpar@414
    52
kpeter@657
    53
    /// \brief The type of the upper bound (capacity) map.
alpar@414
    54
    ///
kpeter@657
    55
    /// The type of the map that stores the upper bounds (capacities)
kpeter@657
    56
    /// on the arcs.
kpeter@657
    57
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@657
    58
    typedef UM UpperMap;
alpar@414
    59
kpeter@657
    60
    /// \brief The type of supply map.
alpar@414
    61
    ///
alpar@956
    62
    /// The type of the map that stores the signed supply values of the
alpar@956
    63
    /// nodes.
kpeter@657
    64
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@657
    65
    typedef SM SupplyMap;
alpar@414
    66
kpeter@688
    67
    /// \brief The type of the flow and supply values.
kpeter@688
    68
    typedef typename SupplyMap::Value Value;
alpar@414
    69
kpeter@417
    70
    /// \brief The type of the map that stores the flow values.
alpar@414
    71
    ///
kpeter@417
    72
    /// The type of the map that stores the flow values.
kpeter@657
    73
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
kpeter@657
    74
    /// concept.
kpeter@760
    75
#ifdef DOXYGEN
kpeter@760
    76
    typedef GR::ArcMap<Value> FlowMap;
kpeter@760
    77
#else
kpeter@688
    78
    typedef typename Digraph::template ArcMap<Value> FlowMap;
kpeter@760
    79
#endif
alpar@414
    80
alpar@414
    81
    /// \brief Instantiates a FlowMap.
alpar@414
    82
    ///
alpar@414
    83
    /// This function instantiates a \ref FlowMap.
kpeter@657
    84
    /// \param digraph The digraph for which we would like to define
alpar@414
    85
    /// the flow map.
alpar@414
    86
    static FlowMap* createFlowMap(const Digraph& digraph) {
alpar@414
    87
      return new FlowMap(digraph);
alpar@414
    88
    }
alpar@414
    89
kpeter@417
    90
    /// \brief The elevator type used by the algorithm.
alpar@414
    91
    ///
kpeter@417
    92
    /// The elevator type used by the algorithm.
alpar@414
    93
    ///
kpeter@760
    94
    /// \sa Elevator, LinkedElevator
kpeter@760
    95
#ifdef DOXYGEN
kpeter@760
    96
    typedef lemon::Elevator<GR, GR::Node> Elevator;
kpeter@760
    97
#else
alpar@414
    98
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
kpeter@760
    99
#endif
alpar@414
   100
alpar@414
   101
    /// \brief Instantiates an Elevator.
alpar@414
   102
    ///
kpeter@417
   103
    /// This function instantiates an \ref Elevator.
kpeter@657
   104
    /// \param digraph The digraph for which we would like to define
alpar@414
   105
    /// the elevator.
alpar@414
   106
    /// \param max_level The maximum level of the elevator.
alpar@414
   107
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
alpar@414
   108
      return new Elevator(digraph, max_level);
alpar@414
   109
    }
alpar@414
   110
alpar@414
   111
    /// \brief The tolerance used by the algorithm
alpar@414
   112
    ///
alpar@414
   113
    /// The tolerance used by the algorithm to handle inexact computation.
kpeter@688
   114
    typedef lemon::Tolerance<Value> Tolerance;
alpar@414
   115
alpar@414
   116
  };
alpar@414
   117
kpeter@417
   118
  /**
kpeter@417
   119
     \brief Push-relabel algorithm for the network circulation problem.
alpar@414
   120
alpar@414
   121
     \ingroup max_flow
kpeter@657
   122
     This class implements a push-relabel algorithm for the \e network
kpeter@657
   123
     \e circulation problem.
kpeter@417
   124
     It is to find a feasible circulation when lower and upper bounds
kpeter@657
   125
     are given for the flow values on the arcs and lower bounds are
kpeter@657
   126
     given for the difference between the outgoing and incoming flow
kpeter@657
   127
     at the nodes.
kpeter@417
   128
alpar@414
   129
     The exact formulation of this problem is the following.
kpeter@669
   130
     Let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{R}\f$
kpeter@669
   131
     \f$upper: A\rightarrow\mathbf{R}\cup\{\infty\}\f$ denote the lower and
kpeter@669
   132
     upper bounds on the arcs, for which \f$lower(uv) \leq upper(uv)\f$
kpeter@657
   133
     holds for all \f$uv\in A\f$, and \f$sup: V\rightarrow\mathbf{R}\f$
kpeter@657
   134
     denotes the signed supply values of the nodes.
kpeter@657
   135
     If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
kpeter@657
   136
     supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
kpeter@657
   137
     \f$-sup(u)\f$ demand.
kpeter@669
   138
     A feasible circulation is an \f$f: A\rightarrow\mathbf{R}\f$
kpeter@657
   139
     solution of the following problem.
kpeter@417
   140
kpeter@657
   141
     \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu)
kpeter@657
   142
     \geq sup(u) \quad \forall u\in V, \f]
kpeter@657
   143
     \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A. \f]
alpar@956
   144
kpeter@657
   145
     The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
kpeter@657
   146
     zero or negative in order to have a feasible solution (since the sum
kpeter@657
   147
     of the expressions on the left-hand side of the inequalities is zero).
kpeter@657
   148
     It means that the total demand must be greater or equal to the total
kpeter@657
   149
     supply and all the supplies have to be carried out from the supply nodes,
kpeter@657
   150
     but there could be demands that are not satisfied.
kpeter@657
   151
     If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
kpeter@657
   152
     constraints have to be satisfied with equality, i.e. all demands
kpeter@657
   153
     have to be satisfied and all supplies have to be used.
alpar@956
   154
kpeter@657
   155
     If you need the opposite inequalities in the supply/demand constraints
kpeter@657
   156
     (i.e. the total demand is less than the total supply and all the demands
kpeter@657
   157
     have to be satisfied while there could be supplies that are not used),
kpeter@657
   158
     then you could easily transform the problem to the above form by reversing
kpeter@657
   159
     the direction of the arcs and taking the negative of the supply values
kpeter@657
   160
     (e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
kpeter@657
   161
kpeter@669
   162
     This algorithm either calculates a feasible circulation, or provides
kpeter@669
   163
     a \ref barrier() "barrier", which prooves that a feasible soultion
kpeter@669
   164
     cannot exist.
kpeter@669
   165
kpeter@657
   166
     Note that this algorithm also provides a feasible solution for the
kpeter@657
   167
     \ref min_cost_flow "minimum cost flow problem".
kpeter@417
   168
kpeter@525
   169
     \tparam GR The type of the digraph the algorithm runs on.
kpeter@657
   170
     \tparam LM The type of the lower bound map. The default
kpeter@525
   171
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
kpeter@657
   172
     \tparam UM The type of the upper bound (capacity) map.
kpeter@657
   173
     The default map type is \c LM.
kpeter@657
   174
     \tparam SM The type of the supply map. The default map type is
kpeter@525
   175
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
kpeter@891
   176
     \tparam TR The traits class that defines various types used by the
kpeter@891
   177
     algorithm. By default, it is \ref CirculationDefaultTraits
kpeter@891
   178
     "CirculationDefaultTraits<GR, LM, UM, SM>".
kpeter@891
   179
     In most cases, this parameter should not be set directly,
kpeter@891
   180
     consider to use the named template parameters instead.
alpar@414
   181
  */
kpeter@417
   182
#ifdef DOXYGEN
kpeter@525
   183
template< typename GR,
kpeter@525
   184
          typename LM,
kpeter@525
   185
          typename UM,
kpeter@657
   186
          typename SM,
kpeter@525
   187
          typename TR >
kpeter@417
   188
#else
kpeter@525
   189
template< typename GR,
kpeter@525
   190
          typename LM = typename GR::template ArcMap<int>,
kpeter@525
   191
          typename UM = LM,
kpeter@657
   192
          typename SM = typename GR::template NodeMap<typename UM::Value>,
kpeter@657
   193
          typename TR = CirculationDefaultTraits<GR, LM, UM, SM> >
kpeter@417
   194
#endif
alpar@414
   195
  class Circulation {
kpeter@417
   196
  public:
alpar@414
   197
kpeter@417
   198
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
kpeter@525
   199
    typedef TR Traits;
kpeter@417
   200
    ///The type of the digraph the algorithm runs on.
alpar@414
   201
    typedef typename Traits::Digraph Digraph;
kpeter@688
   202
    ///The type of the flow and supply values.
kpeter@688
   203
    typedef typename Traits::Value Value;
alpar@414
   204
kpeter@657
   205
    ///The type of the lower bound map.
kpeter@657
   206
    typedef typename Traits::LowerMap LowerMap;
kpeter@657
   207
    ///The type of the upper bound (capacity) map.
kpeter@657
   208
    typedef typename Traits::UpperMap UpperMap;
kpeter@657
   209
    ///The type of the supply map.
kpeter@657
   210
    typedef typename Traits::SupplyMap SupplyMap;
kpeter@417
   211
    ///The type of the flow map.
alpar@414
   212
    typedef typename Traits::FlowMap FlowMap;
kpeter@417
   213
kpeter@417
   214
    ///The type of the elevator.
alpar@414
   215
    typedef typename Traits::Elevator Elevator;
kpeter@417
   216
    ///The type of the tolerance.
alpar@414
   217
    typedef typename Traits::Tolerance Tolerance;
alpar@414
   218
kpeter@417
   219
  private:
kpeter@417
   220
kpeter@417
   221
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
alpar@414
   222
alpar@414
   223
    const Digraph &_g;
alpar@414
   224
    int _node_num;
alpar@414
   225
kpeter@657
   226
    const LowerMap *_lo;
kpeter@657
   227
    const UpperMap *_up;
kpeter@657
   228
    const SupplyMap *_supply;
alpar@414
   229
alpar@414
   230
    FlowMap *_flow;
alpar@414
   231
    bool _local_flow;
alpar@414
   232
alpar@414
   233
    Elevator* _level;
alpar@414
   234
    bool _local_level;
alpar@414
   235
kpeter@688
   236
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
alpar@414
   237
    ExcessMap* _excess;
alpar@414
   238
alpar@414
   239
    Tolerance _tol;
alpar@414
   240
    int _el;
alpar@414
   241
alpar@414
   242
  public:
alpar@414
   243
alpar@414
   244
    typedef Circulation Create;
alpar@414
   245
kpeter@417
   246
    ///\name Named Template Parameters
alpar@414
   247
alpar@414
   248
    ///@{
alpar@414
   249
kpeter@606
   250
    template <typename T>
alpar@416
   251
    struct SetFlowMapTraits : public Traits {
kpeter@606
   252
      typedef T FlowMap;
alpar@414
   253
      static FlowMap *createFlowMap(const Digraph&) {
alpar@414
   254
        LEMON_ASSERT(false, "FlowMap is not initialized");
alpar@414
   255
        return 0; // ignore warnings
alpar@414
   256
      }
alpar@414
   257
    };
alpar@414
   258
alpar@414
   259
    /// \brief \ref named-templ-param "Named parameter" for setting
alpar@414
   260
    /// FlowMap type
alpar@414
   261
    ///
alpar@414
   262
    /// \ref named-templ-param "Named parameter" for setting FlowMap
kpeter@417
   263
    /// type.
kpeter@606
   264
    template <typename T>
alpar@416
   265
    struct SetFlowMap
kpeter@657
   266
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   267
                           SetFlowMapTraits<T> > {
kpeter@657
   268
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   269
                          SetFlowMapTraits<T> > Create;
alpar@414
   270
    };
alpar@414
   271
kpeter@606
   272
    template <typename T>
alpar@416
   273
    struct SetElevatorTraits : public Traits {
kpeter@606
   274
      typedef T Elevator;
alpar@414
   275
      static Elevator *createElevator(const Digraph&, int) {
alpar@414
   276
        LEMON_ASSERT(false, "Elevator is not initialized");
alpar@414
   277
        return 0; // ignore warnings
alpar@414
   278
      }
alpar@414
   279
    };
alpar@414
   280
alpar@414
   281
    /// \brief \ref named-templ-param "Named parameter" for setting
alpar@414
   282
    /// Elevator type
alpar@414
   283
    ///
alpar@414
   284
    /// \ref named-templ-param "Named parameter" for setting Elevator
kpeter@417
   285
    /// type. If this named parameter is used, then an external
kpeter@417
   286
    /// elevator object must be passed to the algorithm using the
kpeter@417
   287
    /// \ref elevator(Elevator&) "elevator()" function before calling
kpeter@417
   288
    /// \ref run() or \ref init().
kpeter@417
   289
    /// \sa SetStandardElevator
kpeter@606
   290
    template <typename T>
alpar@416
   291
    struct SetElevator
kpeter@657
   292
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   293
                           SetElevatorTraits<T> > {
kpeter@657
   294
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   295
                          SetElevatorTraits<T> > Create;
alpar@414
   296
    };
alpar@414
   297
kpeter@606
   298
    template <typename T>
alpar@416
   299
    struct SetStandardElevatorTraits : public Traits {
kpeter@606
   300
      typedef T Elevator;
alpar@414
   301
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
alpar@414
   302
        return new Elevator(digraph, max_level);
alpar@414
   303
      }
alpar@414
   304
    };
alpar@414
   305
alpar@414
   306
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@417
   307
    /// Elevator type with automatic allocation
alpar@414
   308
    ///
alpar@414
   309
    /// \ref named-templ-param "Named parameter" for setting Elevator
kpeter@417
   310
    /// type with automatic allocation.
kpeter@417
   311
    /// The Elevator should have standard constructor interface to be
kpeter@417
   312
    /// able to automatically created by the algorithm (i.e. the
kpeter@417
   313
    /// digraph and the maximum level should be passed to it).
kpeter@833
   314
    /// However, an external elevator object could also be passed to the
kpeter@417
   315
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
kpeter@417
   316
    /// before calling \ref run() or \ref init().
kpeter@417
   317
    /// \sa SetElevator
kpeter@606
   318
    template <typename T>
alpar@416
   319
    struct SetStandardElevator
kpeter@657
   320
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   321
                       SetStandardElevatorTraits<T> > {
kpeter@657
   322
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   323
                      SetStandardElevatorTraits<T> > Create;
alpar@414
   324
    };
alpar@414
   325
alpar@414
   326
    /// @}
alpar@414
   327
alpar@414
   328
  protected:
alpar@414
   329
alpar@414
   330
    Circulation() {}
alpar@414
   331
alpar@414
   332
  public:
alpar@414
   333
kpeter@657
   334
    /// Constructor.
alpar@414
   335
alpar@414
   336
    /// The constructor of the class.
kpeter@657
   337
    ///
kpeter@657
   338
    /// \param graph The digraph the algorithm runs on.
kpeter@657
   339
    /// \param lower The lower bounds for the flow values on the arcs.
alpar@956
   340
    /// \param upper The upper bounds (capacities) for the flow values
kpeter@657
   341
    /// on the arcs.
kpeter@657
   342
    /// \param supply The signed supply values of the nodes.
kpeter@657
   343
    Circulation(const Digraph &graph, const LowerMap &lower,
kpeter@657
   344
                const UpperMap &upper, const SupplyMap &supply)
kpeter@657
   345
      : _g(graph), _lo(&lower), _up(&upper), _supply(&supply),
kpeter@657
   346
        _flow(NULL), _local_flow(false), _level(NULL), _local_level(false),
kpeter@657
   347
        _excess(NULL) {}
alpar@414
   348
kpeter@417
   349
    /// Destructor.
alpar@414
   350
    ~Circulation() {
alpar@414
   351
      destroyStructures();
alpar@414
   352
    }
alpar@414
   353
kpeter@417
   354
alpar@414
   355
  private:
alpar@414
   356
kpeter@669
   357
    bool checkBoundMaps() {
kpeter@669
   358
      for (ArcIt e(_g);e!=INVALID;++e) {
kpeter@669
   359
        if (_tol.less((*_up)[e], (*_lo)[e])) return false;
kpeter@669
   360
      }
kpeter@669
   361
      return true;
kpeter@669
   362
    }
kpeter@669
   363
alpar@414
   364
    void createStructures() {
alpar@414
   365
      _node_num = _el = countNodes(_g);
alpar@414
   366
alpar@414
   367
      if (!_flow) {
alpar@414
   368
        _flow = Traits::createFlowMap(_g);
alpar@414
   369
        _local_flow = true;
alpar@414
   370
      }
alpar@414
   371
      if (!_level) {
alpar@414
   372
        _level = Traits::createElevator(_g, _node_num);
alpar@414
   373
        _local_level = true;
alpar@414
   374
      }
alpar@414
   375
      if (!_excess) {
alpar@414
   376
        _excess = new ExcessMap(_g);
alpar@414
   377
      }
alpar@414
   378
    }
alpar@414
   379
alpar@414
   380
    void destroyStructures() {
alpar@414
   381
      if (_local_flow) {
alpar@414
   382
        delete _flow;
alpar@414
   383
      }
alpar@414
   384
      if (_local_level) {
alpar@414
   385
        delete _level;
alpar@414
   386
      }
alpar@414
   387
      if (_excess) {
alpar@414
   388
        delete _excess;
alpar@414
   389
      }
alpar@414
   390
    }
alpar@414
   391
alpar@414
   392
  public:
alpar@414
   393
kpeter@657
   394
    /// Sets the lower bound map.
alpar@414
   395
kpeter@657
   396
    /// Sets the lower bound map.
kpeter@417
   397
    /// \return <tt>(*this)</tt>
kpeter@657
   398
    Circulation& lowerMap(const LowerMap& map) {
alpar@414
   399
      _lo = &map;
alpar@414
   400
      return *this;
alpar@414
   401
    }
alpar@414
   402
kpeter@657
   403
    /// Sets the upper bound (capacity) map.
alpar@414
   404
kpeter@657
   405
    /// Sets the upper bound (capacity) map.
kpeter@417
   406
    /// \return <tt>(*this)</tt>
kpeter@669
   407
    Circulation& upperMap(const UpperMap& map) {
alpar@414
   408
      _up = &map;
alpar@414
   409
      return *this;
alpar@414
   410
    }
alpar@414
   411
kpeter@657
   412
    /// Sets the supply map.
alpar@414
   413
kpeter@657
   414
    /// Sets the supply map.
kpeter@417
   415
    /// \return <tt>(*this)</tt>
kpeter@657
   416
    Circulation& supplyMap(const SupplyMap& map) {
kpeter@657
   417
      _supply = &map;
alpar@414
   418
      return *this;
alpar@414
   419
    }
alpar@414
   420
kpeter@417
   421
    /// \brief Sets the flow map.
kpeter@417
   422
    ///
alpar@414
   423
    /// Sets the flow map.
kpeter@417
   424
    /// If you don't use this function before calling \ref run() or
kpeter@417
   425
    /// \ref init(), an instance will be allocated automatically.
kpeter@417
   426
    /// The destructor deallocates this automatically allocated map,
kpeter@417
   427
    /// of course.
kpeter@417
   428
    /// \return <tt>(*this)</tt>
alpar@414
   429
    Circulation& flowMap(FlowMap& map) {
alpar@414
   430
      if (_local_flow) {
alpar@414
   431
        delete _flow;
alpar@414
   432
        _local_flow = false;
alpar@414
   433
      }
alpar@414
   434
      _flow = &map;
alpar@414
   435
      return *this;
alpar@414
   436
    }
alpar@414
   437
kpeter@417
   438
    /// \brief Sets the elevator used by algorithm.
alpar@414
   439
    ///
kpeter@417
   440
    /// Sets the elevator used by algorithm.
kpeter@417
   441
    /// If you don't use this function before calling \ref run() or
kpeter@417
   442
    /// \ref init(), an instance will be allocated automatically.
kpeter@417
   443
    /// The destructor deallocates this automatically allocated elevator,
kpeter@417
   444
    /// of course.
kpeter@417
   445
    /// \return <tt>(*this)</tt>
alpar@414
   446
    Circulation& elevator(Elevator& elevator) {
alpar@414
   447
      if (_local_level) {
alpar@414
   448
        delete _level;
alpar@414
   449
        _local_level = false;
alpar@414
   450
      }
alpar@414
   451
      _level = &elevator;
alpar@414
   452
      return *this;
alpar@414
   453
    }
alpar@414
   454
kpeter@417
   455
    /// \brief Returns a const reference to the elevator.
alpar@414
   456
    ///
kpeter@417
   457
    /// Returns a const reference to the elevator.
kpeter@417
   458
    ///
kpeter@417
   459
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   460
    /// using this function.
kpeter@437
   461
    const Elevator& elevator() const {
alpar@414
   462
      return *_level;
alpar@414
   463
    }
alpar@414
   464
kpeter@736
   465
    /// \brief Sets the tolerance used by the algorithm.
kpeter@417
   466
    ///
kpeter@736
   467
    /// Sets the tolerance object used by the algorithm.
kpeter@736
   468
    /// \return <tt>(*this)</tt>
kpeter@735
   469
    Circulation& tolerance(const Tolerance& tolerance) {
alpar@414
   470
      _tol = tolerance;
alpar@414
   471
      return *this;
alpar@414
   472
    }
alpar@414
   473
kpeter@417
   474
    /// \brief Returns a const reference to the tolerance.
alpar@414
   475
    ///
kpeter@736
   476
    /// Returns a const reference to the tolerance object used by
kpeter@736
   477
    /// the algorithm.
alpar@414
   478
    const Tolerance& tolerance() const {
kpeter@735
   479
      return _tol;
alpar@414
   480
    }
alpar@414
   481
kpeter@417
   482
    /// \name Execution Control
kpeter@417
   483
    /// The simplest way to execute the algorithm is to call \ref run().\n
kpeter@760
   484
    /// If you need better control on the initial solution or the execution,
kpeter@760
   485
    /// you have to call one of the \ref init() functions first, then
kpeter@417
   486
    /// the \ref start() function.
alpar@414
   487
alpar@414
   488
    ///@{
alpar@414
   489
alpar@414
   490
    /// Initializes the internal data structures.
alpar@414
   491
kpeter@417
   492
    /// Initializes the internal data structures and sets all flow values
kpeter@417
   493
    /// to the lower bound.
alpar@414
   494
    void init()
alpar@414
   495
    {
kpeter@669
   496
      LEMON_DEBUG(checkBoundMaps(),
kpeter@669
   497
        "Upper bounds must be greater or equal to the lower bounds");
kpeter@669
   498
alpar@414
   499
      createStructures();
alpar@414
   500
alpar@414
   501
      for(NodeIt n(_g);n!=INVALID;++n) {
alpar@658
   502
        (*_excess)[n] = (*_supply)[n];
alpar@414
   503
      }
alpar@414
   504
alpar@414
   505
      for (ArcIt e(_g);e!=INVALID;++e) {
alpar@414
   506
        _flow->set(e, (*_lo)[e]);
kpeter@628
   507
        (*_excess)[_g.target(e)] += (*_flow)[e];
kpeter@628
   508
        (*_excess)[_g.source(e)] -= (*_flow)[e];
alpar@414
   509
      }
alpar@414
   510
alpar@414
   511
      // global relabeling tested, but in general case it provides
alpar@414
   512
      // worse performance for random digraphs
alpar@414
   513
      _level->initStart();
alpar@414
   514
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   515
        _level->initAddItem(n);
alpar@414
   516
      _level->initFinish();
alpar@414
   517
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   518
        if(_tol.positive((*_excess)[n]))
alpar@414
   519
          _level->activate(n);
alpar@414
   520
    }
alpar@414
   521
kpeter@417
   522
    /// Initializes the internal data structures using a greedy approach.
alpar@414
   523
kpeter@417
   524
    /// Initializes the internal data structures using a greedy approach
kpeter@417
   525
    /// to construct the initial solution.
alpar@414
   526
    void greedyInit()
alpar@414
   527
    {
kpeter@669
   528
      LEMON_DEBUG(checkBoundMaps(),
kpeter@669
   529
        "Upper bounds must be greater or equal to the lower bounds");
kpeter@669
   530
alpar@414
   531
      createStructures();
alpar@414
   532
alpar@414
   533
      for(NodeIt n(_g);n!=INVALID;++n) {
alpar@658
   534
        (*_excess)[n] = (*_supply)[n];
alpar@414
   535
      }
alpar@414
   536
alpar@414
   537
      for (ArcIt e(_g);e!=INVALID;++e) {
kpeter@669
   538
        if (!_tol.less(-(*_excess)[_g.target(e)], (*_up)[e])) {
alpar@414
   539
          _flow->set(e, (*_up)[e]);
kpeter@628
   540
          (*_excess)[_g.target(e)] += (*_up)[e];
kpeter@628
   541
          (*_excess)[_g.source(e)] -= (*_up)[e];
kpeter@669
   542
        } else if (_tol.less(-(*_excess)[_g.target(e)], (*_lo)[e])) {
alpar@414
   543
          _flow->set(e, (*_lo)[e]);
kpeter@628
   544
          (*_excess)[_g.target(e)] += (*_lo)[e];
kpeter@628
   545
          (*_excess)[_g.source(e)] -= (*_lo)[e];
alpar@414
   546
        } else {
kpeter@688
   547
          Value fc = -(*_excess)[_g.target(e)];
alpar@414
   548
          _flow->set(e, fc);
kpeter@628
   549
          (*_excess)[_g.target(e)] = 0;
kpeter@628
   550
          (*_excess)[_g.source(e)] -= fc;
alpar@414
   551
        }
alpar@414
   552
      }
alpar@414
   553
alpar@414
   554
      _level->initStart();
alpar@414
   555
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   556
        _level->initAddItem(n);
alpar@414
   557
      _level->initFinish();
alpar@414
   558
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   559
        if(_tol.positive((*_excess)[n]))
alpar@414
   560
          _level->activate(n);
alpar@414
   561
    }
alpar@414
   562
kpeter@417
   563
    ///Executes the algorithm
alpar@414
   564
kpeter@417
   565
    ///This function executes the algorithm.
kpeter@417
   566
    ///
kpeter@417
   567
    ///\return \c true if a feasible circulation is found.
alpar@414
   568
    ///
alpar@414
   569
    ///\sa barrier()
kpeter@417
   570
    ///\sa barrierMap()
alpar@414
   571
    bool start()
alpar@414
   572
    {
alpar@414
   573
alpar@414
   574
      Node act;
alpar@414
   575
      while((act=_level->highestActive())!=INVALID) {
alpar@414
   576
        int actlevel=(*_level)[act];
alpar@414
   577
        int mlevel=_node_num;
kpeter@688
   578
        Value exc=(*_excess)[act];
alpar@414
   579
alpar@414
   580
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
alpar@414
   581
          Node v = _g.target(e);
kpeter@688
   582
          Value fc=(*_up)[e]-(*_flow)[e];
alpar@414
   583
          if(!_tol.positive(fc)) continue;
alpar@414
   584
          if((*_level)[v]<actlevel) {
alpar@414
   585
            if(!_tol.less(fc, exc)) {
alpar@414
   586
              _flow->set(e, (*_flow)[e] + exc);
kpeter@628
   587
              (*_excess)[v] += exc;
alpar@414
   588
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   589
                _level->activate(v);
kpeter@628
   590
              (*_excess)[act] = 0;
alpar@414
   591
              _level->deactivate(act);
alpar@414
   592
              goto next_l;
alpar@414
   593
            }
alpar@414
   594
            else {
alpar@414
   595
              _flow->set(e, (*_up)[e]);
kpeter@628
   596
              (*_excess)[v] += fc;
alpar@414
   597
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   598
                _level->activate(v);
alpar@414
   599
              exc-=fc;
alpar@414
   600
            }
alpar@414
   601
          }
alpar@414
   602
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
alpar@414
   603
        }
alpar@414
   604
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
alpar@414
   605
          Node v = _g.source(e);
kpeter@688
   606
          Value fc=(*_flow)[e]-(*_lo)[e];
alpar@414
   607
          if(!_tol.positive(fc)) continue;
alpar@414
   608
          if((*_level)[v]<actlevel) {
alpar@414
   609
            if(!_tol.less(fc, exc)) {
alpar@414
   610
              _flow->set(e, (*_flow)[e] - exc);
kpeter@628
   611
              (*_excess)[v] += exc;
alpar@414
   612
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   613
                _level->activate(v);
kpeter@628
   614
              (*_excess)[act] = 0;
alpar@414
   615
              _level->deactivate(act);
alpar@414
   616
              goto next_l;
alpar@414
   617
            }
alpar@414
   618
            else {
alpar@414
   619
              _flow->set(e, (*_lo)[e]);
kpeter@628
   620
              (*_excess)[v] += fc;
alpar@414
   621
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   622
                _level->activate(v);
alpar@414
   623
              exc-=fc;
alpar@414
   624
            }
alpar@414
   625
          }
alpar@414
   626
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
alpar@414
   627
        }
alpar@414
   628
kpeter@628
   629
        (*_excess)[act] = exc;
alpar@414
   630
        if(!_tol.positive(exc)) _level->deactivate(act);
alpar@414
   631
        else if(mlevel==_node_num) {
alpar@414
   632
          _level->liftHighestActiveToTop();
alpar@414
   633
          _el = _node_num;
alpar@414
   634
          return false;
alpar@414
   635
        }
alpar@414
   636
        else {
alpar@414
   637
          _level->liftHighestActive(mlevel+1);
alpar@414
   638
          if(_level->onLevel(actlevel)==0) {
alpar@414
   639
            _el = actlevel;
alpar@414
   640
            return false;
alpar@414
   641
          }
alpar@414
   642
        }
alpar@414
   643
      next_l:
alpar@414
   644
        ;
alpar@414
   645
      }
alpar@414
   646
      return true;
alpar@414
   647
    }
alpar@414
   648
kpeter@417
   649
    /// Runs the algorithm.
alpar@414
   650
kpeter@417
   651
    /// This function runs the algorithm.
kpeter@417
   652
    ///
kpeter@417
   653
    /// \return \c true if a feasible circulation is found.
kpeter@417
   654
    ///
kpeter@417
   655
    /// \note Apart from the return value, c.run() is just a shortcut of
kpeter@417
   656
    /// the following code.
alpar@414
   657
    /// \code
kpeter@417
   658
    ///   c.greedyInit();
kpeter@417
   659
    ///   c.start();
alpar@414
   660
    /// \endcode
alpar@414
   661
    bool run() {
alpar@414
   662
      greedyInit();
alpar@414
   663
      return start();
alpar@414
   664
    }
alpar@414
   665
alpar@414
   666
    /// @}
alpar@414
   667
alpar@414
   668
    /// \name Query Functions
kpeter@417
   669
    /// The results of the circulation algorithm can be obtained using
kpeter@417
   670
    /// these functions.\n
kpeter@417
   671
    /// Either \ref run() or \ref start() should be called before
kpeter@417
   672
    /// using them.
alpar@414
   673
alpar@414
   674
    ///@{
alpar@414
   675
kpeter@688
   676
    /// \brief Returns the flow value on the given arc.
kpeter@417
   677
    ///
kpeter@688
   678
    /// Returns the flow value on the given arc.
kpeter@417
   679
    ///
kpeter@417
   680
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   681
    /// using this function.
kpeter@688
   682
    Value flow(const Arc& arc) const {
kpeter@417
   683
      return (*_flow)[arc];
kpeter@417
   684
    }
kpeter@417
   685
kpeter@417
   686
    /// \brief Returns a const reference to the flow map.
kpeter@417
   687
    ///
kpeter@417
   688
    /// Returns a const reference to the arc map storing the found flow.
kpeter@417
   689
    ///
kpeter@417
   690
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   691
    /// using this function.
kpeter@437
   692
    const FlowMap& flowMap() const {
kpeter@417
   693
      return *_flow;
kpeter@417
   694
    }
kpeter@417
   695
alpar@414
   696
    /**
kpeter@417
   697
       \brief Returns \c true if the given node is in a barrier.
kpeter@417
   698
alpar@414
   699
       Barrier is a set \e B of nodes for which
kpeter@417
   700
kpeter@657
   701
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
kpeter@657
   702
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
kpeter@417
   703
kpeter@417
   704
       holds. The existence of a set with this property prooves that a
kpeter@417
   705
       feasible circualtion cannot exist.
kpeter@417
   706
kpeter@417
   707
       This function returns \c true if the given node is in the found
kpeter@417
   708
       barrier. If a feasible circulation is found, the function
kpeter@417
   709
       gives back \c false for every node.
kpeter@417
   710
kpeter@417
   711
       \pre Either \ref run() or \ref init() must be called before
kpeter@417
   712
       using this function.
kpeter@417
   713
kpeter@417
   714
       \sa barrierMap()
alpar@414
   715
       \sa checkBarrier()
alpar@414
   716
    */
kpeter@437
   717
    bool barrier(const Node& node) const
kpeter@417
   718
    {
kpeter@417
   719
      return (*_level)[node] >= _el;
kpeter@417
   720
    }
kpeter@417
   721
kpeter@417
   722
    /// \brief Gives back a barrier.
kpeter@417
   723
    ///
kpeter@417
   724
    /// This function sets \c bar to the characteristic vector of the
kpeter@417
   725
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
kpeter@417
   726
    /// node map with \c bool (or convertible) value type.
kpeter@417
   727
    ///
kpeter@417
   728
    /// If a feasible circulation is found, the function gives back an
kpeter@417
   729
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
kpeter@417
   730
    ///
kpeter@417
   731
    /// \note This function calls \ref barrier() for each node,
kpeter@606
   732
    /// so it runs in O(n) time.
kpeter@417
   733
    ///
kpeter@417
   734
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   735
    /// using this function.
kpeter@417
   736
    ///
kpeter@417
   737
    /// \sa barrier()
kpeter@417
   738
    /// \sa checkBarrier()
kpeter@417
   739
    template<class BarrierMap>
kpeter@437
   740
    void barrierMap(BarrierMap &bar) const
alpar@414
   741
    {
alpar@414
   742
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   743
        bar.set(n, (*_level)[n] >= _el);
alpar@414
   744
    }
alpar@414
   745
alpar@414
   746
    /// @}
alpar@414
   747
alpar@414
   748
    /// \name Checker Functions
kpeter@417
   749
    /// The feasibility of the results can be checked using
kpeter@417
   750
    /// these functions.\n
kpeter@417
   751
    /// Either \ref run() or \ref start() should be called before
kpeter@417
   752
    /// using them.
alpar@414
   753
alpar@414
   754
    ///@{
alpar@414
   755
kpeter@417
   756
    ///Check if the found flow is a feasible circulation
kpeter@417
   757
kpeter@417
   758
    ///Check if the found flow is a feasible circulation,
kpeter@417
   759
    ///
kpeter@437
   760
    bool checkFlow() const {
alpar@414
   761
      for(ArcIt e(_g);e!=INVALID;++e)
alpar@414
   762
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
alpar@414
   763
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   764
        {
kpeter@688
   765
          Value dif=-(*_supply)[n];
alpar@414
   766
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
alpar@414
   767
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
alpar@414
   768
          if(_tol.negative(dif)) return false;
alpar@414
   769
        }
alpar@414
   770
      return true;
alpar@414
   771
    }
alpar@414
   772
alpar@414
   773
    ///Check whether or not the last execution provides a barrier
alpar@414
   774
kpeter@417
   775
    ///Check whether or not the last execution provides a barrier.
alpar@414
   776
    ///\sa barrier()
kpeter@417
   777
    ///\sa barrierMap()
kpeter@437
   778
    bool checkBarrier() const
alpar@414
   779
    {
kpeter@688
   780
      Value delta=0;
kpeter@688
   781
      Value inf_cap = std::numeric_limits<Value>::has_infinity ?
kpeter@688
   782
        std::numeric_limits<Value>::infinity() :
kpeter@688
   783
        std::numeric_limits<Value>::max();
alpar@414
   784
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   785
        if(barrier(n))
kpeter@657
   786
          delta-=(*_supply)[n];
alpar@414
   787
      for(ArcIt e(_g);e!=INVALID;++e)
alpar@414
   788
        {
alpar@414
   789
          Node s=_g.source(e);
alpar@414
   790
          Node t=_g.target(e);
kpeter@669
   791
          if(barrier(s)&&!barrier(t)) {
kpeter@669
   792
            if (_tol.less(inf_cap - (*_up)[e], delta)) return false;
kpeter@669
   793
            delta+=(*_up)[e];
kpeter@669
   794
          }
alpar@414
   795
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
alpar@414
   796
        }
alpar@414
   797
      return _tol.negative(delta);
alpar@414
   798
    }
alpar@414
   799
alpar@414
   800
    /// @}
alpar@414
   801
alpar@414
   802
  };
alpar@414
   803
alpar@414
   804
}
alpar@414
   805
alpar@414
   806
#endif