lemon/circulation.h
author Balazs Dezso <deba@google.com>
Sat, 27 Oct 2018 13:00:48 +0200
changeset 1423 8c567e298d7f
parent 1250 97d978243703
permissions -rw-r--r--
Paremeter to stop matching calculation when only single node is unmatched
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@1270
     5
 * Copyright (C) 2003-2013
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
alpar@1250
   198
    /// \brief The \ref lemon::CirculationDefaultTraits "traits class"
alpar@1250
   199
    /// of the algorithm.
kpeter@525
   200
    typedef TR Traits;
kpeter@417
   201
    ///The type of the digraph the algorithm runs on.
alpar@414
   202
    typedef typename Traits::Digraph Digraph;
kpeter@688
   203
    ///The type of the flow and supply values.
kpeter@688
   204
    typedef typename Traits::Value Value;
alpar@414
   205
kpeter@657
   206
    ///The type of the lower bound map.
kpeter@657
   207
    typedef typename Traits::LowerMap LowerMap;
kpeter@657
   208
    ///The type of the upper bound (capacity) map.
kpeter@657
   209
    typedef typename Traits::UpperMap UpperMap;
kpeter@657
   210
    ///The type of the supply map.
kpeter@657
   211
    typedef typename Traits::SupplyMap SupplyMap;
kpeter@417
   212
    ///The type of the flow map.
alpar@414
   213
    typedef typename Traits::FlowMap FlowMap;
kpeter@417
   214
kpeter@417
   215
    ///The type of the elevator.
alpar@414
   216
    typedef typename Traits::Elevator Elevator;
kpeter@417
   217
    ///The type of the tolerance.
alpar@414
   218
    typedef typename Traits::Tolerance Tolerance;
alpar@414
   219
kpeter@417
   220
  private:
kpeter@417
   221
kpeter@417
   222
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
alpar@414
   223
alpar@414
   224
    const Digraph &_g;
alpar@414
   225
    int _node_num;
alpar@414
   226
kpeter@657
   227
    const LowerMap *_lo;
kpeter@657
   228
    const UpperMap *_up;
kpeter@657
   229
    const SupplyMap *_supply;
alpar@414
   230
alpar@414
   231
    FlowMap *_flow;
alpar@414
   232
    bool _local_flow;
alpar@414
   233
alpar@414
   234
    Elevator* _level;
alpar@414
   235
    bool _local_level;
alpar@414
   236
kpeter@688
   237
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
alpar@414
   238
    ExcessMap* _excess;
alpar@414
   239
alpar@414
   240
    Tolerance _tol;
alpar@414
   241
    int _el;
alpar@414
   242
alpar@414
   243
  public:
alpar@414
   244
alpar@414
   245
    typedef Circulation Create;
alpar@414
   246
kpeter@417
   247
    ///\name Named Template Parameters
alpar@414
   248
alpar@414
   249
    ///@{
alpar@414
   250
kpeter@606
   251
    template <typename T>
alpar@416
   252
    struct SetFlowMapTraits : public Traits {
kpeter@606
   253
      typedef T FlowMap;
alpar@414
   254
      static FlowMap *createFlowMap(const Digraph&) {
alpar@414
   255
        LEMON_ASSERT(false, "FlowMap is not initialized");
alpar@414
   256
        return 0; // ignore warnings
alpar@414
   257
      }
alpar@414
   258
    };
alpar@414
   259
alpar@414
   260
    /// \brief \ref named-templ-param "Named parameter" for setting
alpar@414
   261
    /// FlowMap type
alpar@414
   262
    ///
alpar@414
   263
    /// \ref named-templ-param "Named parameter" for setting FlowMap
kpeter@417
   264
    /// type.
kpeter@606
   265
    template <typename T>
alpar@416
   266
    struct SetFlowMap
kpeter@657
   267
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   268
                           SetFlowMapTraits<T> > {
kpeter@657
   269
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   270
                          SetFlowMapTraits<T> > Create;
alpar@414
   271
    };
alpar@414
   272
kpeter@606
   273
    template <typename T>
alpar@416
   274
    struct SetElevatorTraits : public Traits {
kpeter@606
   275
      typedef T Elevator;
alpar@414
   276
      static Elevator *createElevator(const Digraph&, int) {
alpar@414
   277
        LEMON_ASSERT(false, "Elevator is not initialized");
alpar@414
   278
        return 0; // ignore warnings
alpar@414
   279
      }
alpar@414
   280
    };
alpar@414
   281
alpar@414
   282
    /// \brief \ref named-templ-param "Named parameter" for setting
alpar@414
   283
    /// Elevator type
alpar@414
   284
    ///
alpar@414
   285
    /// \ref named-templ-param "Named parameter" for setting Elevator
kpeter@417
   286
    /// type. If this named parameter is used, then an external
kpeter@417
   287
    /// elevator object must be passed to the algorithm using the
kpeter@417
   288
    /// \ref elevator(Elevator&) "elevator()" function before calling
kpeter@417
   289
    /// \ref run() or \ref init().
kpeter@417
   290
    /// \sa SetStandardElevator
kpeter@606
   291
    template <typename T>
alpar@416
   292
    struct SetElevator
kpeter@657
   293
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   294
                           SetElevatorTraits<T> > {
kpeter@657
   295
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   296
                          SetElevatorTraits<T> > Create;
alpar@414
   297
    };
alpar@414
   298
kpeter@606
   299
    template <typename T>
alpar@416
   300
    struct SetStandardElevatorTraits : public Traits {
kpeter@606
   301
      typedef T Elevator;
alpar@414
   302
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
alpar@414
   303
        return new Elevator(digraph, max_level);
alpar@414
   304
      }
alpar@414
   305
    };
alpar@414
   306
alpar@414
   307
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@417
   308
    /// Elevator type with automatic allocation
alpar@414
   309
    ///
alpar@414
   310
    /// \ref named-templ-param "Named parameter" for setting Elevator
kpeter@417
   311
    /// type with automatic allocation.
kpeter@417
   312
    /// The Elevator should have standard constructor interface to be
kpeter@417
   313
    /// able to automatically created by the algorithm (i.e. the
kpeter@417
   314
    /// digraph and the maximum level should be passed to it).
kpeter@833
   315
    /// However, an external elevator object could also be passed to the
kpeter@417
   316
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
kpeter@417
   317
    /// before calling \ref run() or \ref init().
kpeter@417
   318
    /// \sa SetElevator
kpeter@606
   319
    template <typename T>
alpar@416
   320
    struct SetStandardElevator
kpeter@657
   321
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   322
                       SetStandardElevatorTraits<T> > {
kpeter@657
   323
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
kpeter@606
   324
                      SetStandardElevatorTraits<T> > Create;
alpar@414
   325
    };
alpar@414
   326
alpar@414
   327
    /// @}
alpar@414
   328
alpar@414
   329
  protected:
alpar@414
   330
alpar@414
   331
    Circulation() {}
alpar@414
   332
alpar@414
   333
  public:
alpar@414
   334
kpeter@657
   335
    /// Constructor.
alpar@414
   336
alpar@414
   337
    /// The constructor of the class.
kpeter@657
   338
    ///
kpeter@657
   339
    /// \param graph The digraph the algorithm runs on.
kpeter@657
   340
    /// \param lower The lower bounds for the flow values on the arcs.
alpar@956
   341
    /// \param upper The upper bounds (capacities) for the flow values
kpeter@657
   342
    /// on the arcs.
kpeter@657
   343
    /// \param supply The signed supply values of the nodes.
kpeter@657
   344
    Circulation(const Digraph &graph, const LowerMap &lower,
kpeter@657
   345
                const UpperMap &upper, const SupplyMap &supply)
kpeter@657
   346
      : _g(graph), _lo(&lower), _up(&upper), _supply(&supply),
kpeter@657
   347
        _flow(NULL), _local_flow(false), _level(NULL), _local_level(false),
kpeter@657
   348
        _excess(NULL) {}
alpar@414
   349
kpeter@417
   350
    /// Destructor.
alpar@414
   351
    ~Circulation() {
alpar@414
   352
      destroyStructures();
alpar@414
   353
    }
alpar@414
   354
kpeter@417
   355
alpar@414
   356
  private:
alpar@414
   357
kpeter@669
   358
    bool checkBoundMaps() {
kpeter@669
   359
      for (ArcIt e(_g);e!=INVALID;++e) {
kpeter@669
   360
        if (_tol.less((*_up)[e], (*_lo)[e])) return false;
kpeter@669
   361
      }
kpeter@669
   362
      return true;
kpeter@669
   363
    }
kpeter@669
   364
alpar@414
   365
    void createStructures() {
alpar@414
   366
      _node_num = _el = countNodes(_g);
alpar@414
   367
alpar@414
   368
      if (!_flow) {
alpar@414
   369
        _flow = Traits::createFlowMap(_g);
alpar@414
   370
        _local_flow = true;
alpar@414
   371
      }
alpar@414
   372
      if (!_level) {
alpar@414
   373
        _level = Traits::createElevator(_g, _node_num);
alpar@414
   374
        _local_level = true;
alpar@414
   375
      }
alpar@414
   376
      if (!_excess) {
alpar@414
   377
        _excess = new ExcessMap(_g);
alpar@414
   378
      }
alpar@414
   379
    }
alpar@414
   380
alpar@414
   381
    void destroyStructures() {
alpar@414
   382
      if (_local_flow) {
alpar@414
   383
        delete _flow;
alpar@414
   384
      }
alpar@414
   385
      if (_local_level) {
alpar@414
   386
        delete _level;
alpar@414
   387
      }
alpar@414
   388
      if (_excess) {
alpar@414
   389
        delete _excess;
alpar@414
   390
      }
alpar@414
   391
    }
alpar@414
   392
alpar@414
   393
  public:
alpar@414
   394
kpeter@657
   395
    /// Sets the lower bound map.
alpar@414
   396
kpeter@657
   397
    /// Sets the lower bound map.
kpeter@417
   398
    /// \return <tt>(*this)</tt>
kpeter@657
   399
    Circulation& lowerMap(const LowerMap& map) {
alpar@414
   400
      _lo = &map;
alpar@414
   401
      return *this;
alpar@414
   402
    }
alpar@414
   403
kpeter@657
   404
    /// Sets the upper bound (capacity) map.
alpar@414
   405
kpeter@657
   406
    /// Sets the upper bound (capacity) map.
kpeter@417
   407
    /// \return <tt>(*this)</tt>
kpeter@669
   408
    Circulation& upperMap(const UpperMap& map) {
alpar@414
   409
      _up = &map;
alpar@414
   410
      return *this;
alpar@414
   411
    }
alpar@414
   412
kpeter@657
   413
    /// Sets the supply map.
alpar@414
   414
kpeter@657
   415
    /// Sets the supply map.
kpeter@417
   416
    /// \return <tt>(*this)</tt>
kpeter@657
   417
    Circulation& supplyMap(const SupplyMap& map) {
kpeter@657
   418
      _supply = &map;
alpar@414
   419
      return *this;
alpar@414
   420
    }
alpar@414
   421
kpeter@417
   422
    /// \brief Sets the flow map.
kpeter@417
   423
    ///
alpar@414
   424
    /// Sets the flow map.
kpeter@417
   425
    /// If you don't use this function before calling \ref run() or
kpeter@417
   426
    /// \ref init(), an instance will be allocated automatically.
kpeter@417
   427
    /// The destructor deallocates this automatically allocated map,
kpeter@417
   428
    /// of course.
kpeter@417
   429
    /// \return <tt>(*this)</tt>
alpar@414
   430
    Circulation& flowMap(FlowMap& map) {
alpar@414
   431
      if (_local_flow) {
alpar@414
   432
        delete _flow;
alpar@414
   433
        _local_flow = false;
alpar@414
   434
      }
alpar@414
   435
      _flow = &map;
alpar@414
   436
      return *this;
alpar@414
   437
    }
alpar@414
   438
kpeter@417
   439
    /// \brief Sets the elevator used by algorithm.
alpar@414
   440
    ///
kpeter@417
   441
    /// Sets the elevator used by algorithm.
kpeter@417
   442
    /// If you don't use this function before calling \ref run() or
kpeter@417
   443
    /// \ref init(), an instance will be allocated automatically.
kpeter@417
   444
    /// The destructor deallocates this automatically allocated elevator,
kpeter@417
   445
    /// of course.
kpeter@417
   446
    /// \return <tt>(*this)</tt>
alpar@414
   447
    Circulation& elevator(Elevator& elevator) {
alpar@414
   448
      if (_local_level) {
alpar@414
   449
        delete _level;
alpar@414
   450
        _local_level = false;
alpar@414
   451
      }
alpar@414
   452
      _level = &elevator;
alpar@414
   453
      return *this;
alpar@414
   454
    }
alpar@414
   455
kpeter@417
   456
    /// \brief Returns a const reference to the elevator.
alpar@414
   457
    ///
kpeter@417
   458
    /// Returns a const reference to the elevator.
kpeter@417
   459
    ///
kpeter@417
   460
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   461
    /// using this function.
kpeter@437
   462
    const Elevator& elevator() const {
alpar@414
   463
      return *_level;
alpar@414
   464
    }
alpar@414
   465
kpeter@736
   466
    /// \brief Sets the tolerance used by the algorithm.
kpeter@417
   467
    ///
kpeter@736
   468
    /// Sets the tolerance object used by the algorithm.
kpeter@736
   469
    /// \return <tt>(*this)</tt>
kpeter@735
   470
    Circulation& tolerance(const Tolerance& tolerance) {
alpar@414
   471
      _tol = tolerance;
alpar@414
   472
      return *this;
alpar@414
   473
    }
alpar@414
   474
kpeter@417
   475
    /// \brief Returns a const reference to the tolerance.
alpar@414
   476
    ///
kpeter@736
   477
    /// Returns a const reference to the tolerance object used by
kpeter@736
   478
    /// the algorithm.
alpar@414
   479
    const Tolerance& tolerance() const {
kpeter@735
   480
      return _tol;
alpar@414
   481
    }
alpar@414
   482
kpeter@417
   483
    /// \name Execution Control
kpeter@417
   484
    /// The simplest way to execute the algorithm is to call \ref run().\n
kpeter@760
   485
    /// If you need better control on the initial solution or the execution,
kpeter@760
   486
    /// you have to call one of the \ref init() functions first, then
kpeter@417
   487
    /// the \ref start() function.
alpar@414
   488
alpar@414
   489
    ///@{
alpar@414
   490
alpar@414
   491
    /// Initializes the internal data structures.
alpar@414
   492
kpeter@417
   493
    /// Initializes the internal data structures and sets all flow values
kpeter@417
   494
    /// to the lower bound.
alpar@414
   495
    void init()
alpar@414
   496
    {
kpeter@669
   497
      LEMON_DEBUG(checkBoundMaps(),
kpeter@669
   498
        "Upper bounds must be greater or equal to the lower bounds");
kpeter@669
   499
alpar@414
   500
      createStructures();
alpar@414
   501
alpar@414
   502
      for(NodeIt n(_g);n!=INVALID;++n) {
alpar@658
   503
        (*_excess)[n] = (*_supply)[n];
alpar@414
   504
      }
alpar@414
   505
alpar@414
   506
      for (ArcIt e(_g);e!=INVALID;++e) {
alpar@414
   507
        _flow->set(e, (*_lo)[e]);
kpeter@628
   508
        (*_excess)[_g.target(e)] += (*_flow)[e];
kpeter@628
   509
        (*_excess)[_g.source(e)] -= (*_flow)[e];
alpar@414
   510
      }
alpar@414
   511
alpar@414
   512
      // global relabeling tested, but in general case it provides
alpar@414
   513
      // worse performance for random digraphs
alpar@414
   514
      _level->initStart();
alpar@414
   515
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   516
        _level->initAddItem(n);
alpar@414
   517
      _level->initFinish();
alpar@414
   518
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   519
        if(_tol.positive((*_excess)[n]))
alpar@414
   520
          _level->activate(n);
alpar@414
   521
    }
alpar@414
   522
kpeter@417
   523
    /// Initializes the internal data structures using a greedy approach.
alpar@414
   524
kpeter@417
   525
    /// Initializes the internal data structures using a greedy approach
kpeter@417
   526
    /// to construct the initial solution.
alpar@414
   527
    void greedyInit()
alpar@414
   528
    {
kpeter@669
   529
      LEMON_DEBUG(checkBoundMaps(),
kpeter@669
   530
        "Upper bounds must be greater or equal to the lower bounds");
kpeter@669
   531
alpar@414
   532
      createStructures();
alpar@414
   533
alpar@414
   534
      for(NodeIt n(_g);n!=INVALID;++n) {
alpar@658
   535
        (*_excess)[n] = (*_supply)[n];
alpar@414
   536
      }
alpar@414
   537
alpar@414
   538
      for (ArcIt e(_g);e!=INVALID;++e) {
kpeter@669
   539
        if (!_tol.less(-(*_excess)[_g.target(e)], (*_up)[e])) {
alpar@414
   540
          _flow->set(e, (*_up)[e]);
kpeter@628
   541
          (*_excess)[_g.target(e)] += (*_up)[e];
kpeter@628
   542
          (*_excess)[_g.source(e)] -= (*_up)[e];
kpeter@669
   543
        } else if (_tol.less(-(*_excess)[_g.target(e)], (*_lo)[e])) {
alpar@414
   544
          _flow->set(e, (*_lo)[e]);
kpeter@628
   545
          (*_excess)[_g.target(e)] += (*_lo)[e];
kpeter@628
   546
          (*_excess)[_g.source(e)] -= (*_lo)[e];
alpar@414
   547
        } else {
kpeter@688
   548
          Value fc = -(*_excess)[_g.target(e)];
alpar@414
   549
          _flow->set(e, fc);
kpeter@628
   550
          (*_excess)[_g.target(e)] = 0;
kpeter@628
   551
          (*_excess)[_g.source(e)] -= fc;
alpar@414
   552
        }
alpar@414
   553
      }
alpar@414
   554
alpar@414
   555
      _level->initStart();
alpar@414
   556
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   557
        _level->initAddItem(n);
alpar@414
   558
      _level->initFinish();
alpar@414
   559
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   560
        if(_tol.positive((*_excess)[n]))
alpar@414
   561
          _level->activate(n);
alpar@414
   562
    }
alpar@414
   563
kpeter@417
   564
    ///Executes the algorithm
alpar@414
   565
kpeter@417
   566
    ///This function executes the algorithm.
kpeter@417
   567
    ///
kpeter@417
   568
    ///\return \c true if a feasible circulation is found.
alpar@414
   569
    ///
alpar@414
   570
    ///\sa barrier()
kpeter@417
   571
    ///\sa barrierMap()
alpar@414
   572
    bool start()
alpar@414
   573
    {
alpar@414
   574
alpar@414
   575
      Node act;
alpar@414
   576
      while((act=_level->highestActive())!=INVALID) {
alpar@414
   577
        int actlevel=(*_level)[act];
alpar@414
   578
        int mlevel=_node_num;
kpeter@688
   579
        Value exc=(*_excess)[act];
alpar@414
   580
alpar@414
   581
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
alpar@414
   582
          Node v = _g.target(e);
kpeter@688
   583
          Value fc=(*_up)[e]-(*_flow)[e];
alpar@414
   584
          if(!_tol.positive(fc)) continue;
alpar@414
   585
          if((*_level)[v]<actlevel) {
alpar@414
   586
            if(!_tol.less(fc, exc)) {
alpar@414
   587
              _flow->set(e, (*_flow)[e] + exc);
kpeter@628
   588
              (*_excess)[v] += exc;
alpar@414
   589
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   590
                _level->activate(v);
kpeter@628
   591
              (*_excess)[act] = 0;
alpar@414
   592
              _level->deactivate(act);
alpar@414
   593
              goto next_l;
alpar@414
   594
            }
alpar@414
   595
            else {
alpar@414
   596
              _flow->set(e, (*_up)[e]);
kpeter@628
   597
              (*_excess)[v] += fc;
alpar@414
   598
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   599
                _level->activate(v);
alpar@414
   600
              exc-=fc;
alpar@414
   601
            }
alpar@414
   602
          }
alpar@414
   603
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
alpar@414
   604
        }
alpar@414
   605
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
alpar@414
   606
          Node v = _g.source(e);
kpeter@688
   607
          Value fc=(*_flow)[e]-(*_lo)[e];
alpar@414
   608
          if(!_tol.positive(fc)) continue;
alpar@414
   609
          if((*_level)[v]<actlevel) {
alpar@414
   610
            if(!_tol.less(fc, exc)) {
alpar@414
   611
              _flow->set(e, (*_flow)[e] - exc);
kpeter@628
   612
              (*_excess)[v] += exc;
alpar@414
   613
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   614
                _level->activate(v);
kpeter@628
   615
              (*_excess)[act] = 0;
alpar@414
   616
              _level->deactivate(act);
alpar@414
   617
              goto next_l;
alpar@414
   618
            }
alpar@414
   619
            else {
alpar@414
   620
              _flow->set(e, (*_lo)[e]);
kpeter@628
   621
              (*_excess)[v] += fc;
alpar@414
   622
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
alpar@414
   623
                _level->activate(v);
alpar@414
   624
              exc-=fc;
alpar@414
   625
            }
alpar@414
   626
          }
alpar@414
   627
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
alpar@414
   628
        }
alpar@414
   629
kpeter@628
   630
        (*_excess)[act] = exc;
alpar@414
   631
        if(!_tol.positive(exc)) _level->deactivate(act);
alpar@414
   632
        else if(mlevel==_node_num) {
alpar@414
   633
          _level->liftHighestActiveToTop();
alpar@414
   634
          _el = _node_num;
alpar@414
   635
          return false;
alpar@414
   636
        }
alpar@414
   637
        else {
alpar@414
   638
          _level->liftHighestActive(mlevel+1);
alpar@414
   639
          if(_level->onLevel(actlevel)==0) {
alpar@414
   640
            _el = actlevel;
alpar@414
   641
            return false;
alpar@414
   642
          }
alpar@414
   643
        }
alpar@414
   644
      next_l:
alpar@414
   645
        ;
alpar@414
   646
      }
alpar@414
   647
      return true;
alpar@414
   648
    }
alpar@414
   649
kpeter@417
   650
    /// Runs the algorithm.
alpar@414
   651
kpeter@417
   652
    /// This function runs the algorithm.
kpeter@417
   653
    ///
kpeter@417
   654
    /// \return \c true if a feasible circulation is found.
kpeter@417
   655
    ///
kpeter@417
   656
    /// \note Apart from the return value, c.run() is just a shortcut of
kpeter@417
   657
    /// the following code.
alpar@414
   658
    /// \code
kpeter@417
   659
    ///   c.greedyInit();
kpeter@417
   660
    ///   c.start();
alpar@414
   661
    /// \endcode
alpar@414
   662
    bool run() {
alpar@414
   663
      greedyInit();
alpar@414
   664
      return start();
alpar@414
   665
    }
alpar@414
   666
alpar@414
   667
    /// @}
alpar@414
   668
alpar@414
   669
    /// \name Query Functions
kpeter@417
   670
    /// The results of the circulation algorithm can be obtained using
kpeter@417
   671
    /// these functions.\n
kpeter@417
   672
    /// Either \ref run() or \ref start() should be called before
kpeter@417
   673
    /// using them.
alpar@414
   674
alpar@414
   675
    ///@{
alpar@414
   676
kpeter@688
   677
    /// \brief Returns the flow value on the given arc.
kpeter@417
   678
    ///
kpeter@688
   679
    /// Returns the flow value on the given arc.
kpeter@417
   680
    ///
kpeter@417
   681
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   682
    /// using this function.
kpeter@688
   683
    Value flow(const Arc& arc) const {
kpeter@417
   684
      return (*_flow)[arc];
kpeter@417
   685
    }
kpeter@417
   686
kpeter@417
   687
    /// \brief Returns a const reference to the flow map.
kpeter@417
   688
    ///
kpeter@417
   689
    /// Returns a const reference to the arc map storing the found flow.
kpeter@417
   690
    ///
kpeter@417
   691
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   692
    /// using this function.
kpeter@437
   693
    const FlowMap& flowMap() const {
kpeter@417
   694
      return *_flow;
kpeter@417
   695
    }
kpeter@417
   696
alpar@414
   697
    /**
kpeter@417
   698
       \brief Returns \c true if the given node is in a barrier.
kpeter@417
   699
alpar@414
   700
       Barrier is a set \e B of nodes for which
kpeter@417
   701
kpeter@657
   702
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
kpeter@657
   703
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
kpeter@417
   704
kpeter@417
   705
       holds. The existence of a set with this property prooves that a
kpeter@417
   706
       feasible circualtion cannot exist.
kpeter@417
   707
kpeter@417
   708
       This function returns \c true if the given node is in the found
kpeter@417
   709
       barrier. If a feasible circulation is found, the function
kpeter@417
   710
       gives back \c false for every node.
kpeter@417
   711
kpeter@417
   712
       \pre Either \ref run() or \ref init() must be called before
kpeter@417
   713
       using this function.
kpeter@417
   714
kpeter@417
   715
       \sa barrierMap()
alpar@414
   716
       \sa checkBarrier()
alpar@414
   717
    */
kpeter@437
   718
    bool barrier(const Node& node) const
kpeter@417
   719
    {
kpeter@417
   720
      return (*_level)[node] >= _el;
kpeter@417
   721
    }
kpeter@417
   722
kpeter@417
   723
    /// \brief Gives back a barrier.
kpeter@417
   724
    ///
kpeter@417
   725
    /// This function sets \c bar to the characteristic vector of the
kpeter@417
   726
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
kpeter@417
   727
    /// node map with \c bool (or convertible) value type.
kpeter@417
   728
    ///
kpeter@417
   729
    /// If a feasible circulation is found, the function gives back an
kpeter@417
   730
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
kpeter@417
   731
    ///
kpeter@417
   732
    /// \note This function calls \ref barrier() for each node,
kpeter@606
   733
    /// so it runs in O(n) time.
kpeter@417
   734
    ///
kpeter@417
   735
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@417
   736
    /// using this function.
kpeter@417
   737
    ///
kpeter@417
   738
    /// \sa barrier()
kpeter@417
   739
    /// \sa checkBarrier()
kpeter@417
   740
    template<class BarrierMap>
kpeter@437
   741
    void barrierMap(BarrierMap &bar) const
alpar@414
   742
    {
alpar@414
   743
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   744
        bar.set(n, (*_level)[n] >= _el);
alpar@414
   745
    }
alpar@414
   746
alpar@414
   747
    /// @}
alpar@414
   748
alpar@414
   749
    /// \name Checker Functions
kpeter@417
   750
    /// The feasibility of the results can be checked using
kpeter@417
   751
    /// these functions.\n
kpeter@417
   752
    /// Either \ref run() or \ref start() should be called before
kpeter@417
   753
    /// using them.
alpar@414
   754
alpar@414
   755
    ///@{
alpar@414
   756
kpeter@417
   757
    ///Check if the found flow is a feasible circulation
kpeter@417
   758
kpeter@417
   759
    ///Check if the found flow is a feasible circulation,
kpeter@417
   760
    ///
kpeter@437
   761
    bool checkFlow() const {
alpar@414
   762
      for(ArcIt e(_g);e!=INVALID;++e)
alpar@414
   763
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
alpar@414
   764
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   765
        {
kpeter@688
   766
          Value dif=-(*_supply)[n];
alpar@414
   767
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
alpar@414
   768
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
alpar@414
   769
          if(_tol.negative(dif)) return false;
alpar@414
   770
        }
alpar@414
   771
      return true;
alpar@414
   772
    }
alpar@414
   773
alpar@414
   774
    ///Check whether or not the last execution provides a barrier
alpar@414
   775
kpeter@417
   776
    ///Check whether or not the last execution provides a barrier.
alpar@414
   777
    ///\sa barrier()
kpeter@417
   778
    ///\sa barrierMap()
kpeter@437
   779
    bool checkBarrier() const
alpar@414
   780
    {
kpeter@688
   781
      Value delta=0;
kpeter@688
   782
      Value inf_cap = std::numeric_limits<Value>::has_infinity ?
kpeter@688
   783
        std::numeric_limits<Value>::infinity() :
kpeter@688
   784
        std::numeric_limits<Value>::max();
alpar@414
   785
      for(NodeIt n(_g);n!=INVALID;++n)
alpar@414
   786
        if(barrier(n))
kpeter@657
   787
          delta-=(*_supply)[n];
alpar@414
   788
      for(ArcIt e(_g);e!=INVALID;++e)
alpar@414
   789
        {
alpar@414
   790
          Node s=_g.source(e);
alpar@414
   791
          Node t=_g.target(e);
kpeter@669
   792
          if(barrier(s)&&!barrier(t)) {
kpeter@669
   793
            if (_tol.less(inf_cap - (*_up)[e], delta)) return false;
kpeter@669
   794
            delta+=(*_up)[e];
kpeter@669
   795
          }
alpar@414
   796
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
alpar@414
   797
        }
alpar@414
   798
      return _tol.negative(delta);
alpar@414
   799
    }
alpar@414
   800
alpar@414
   801
    /// @}
alpar@414
   802
alpar@414
   803
  };
alpar@414
   804
alpar@414
   805
}
alpar@414
   806
alpar@414
   807
#endif