lemon/bellman_ford.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 18 Mar 2010 00:29:35 +0100
branch1.2
changeset 882 7af2ae7c1428
parent 844 a6eb9698c321
child 881 b89e46862dc2
permissions -rw-r--r--
Trim the documentation (#359)
alpar@877
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@696
     2
 *
alpar@877
     3
 * This file is a part of LEMON, a generic C++ optimization library.
kpeter@696
     4
 *
alpar@877
     5
 * Copyright (C) 2003-2010
kpeter@696
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@696
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@696
     8
 *
kpeter@696
     9
 * Permission to use, modify and distribute this software is granted
kpeter@696
    10
 * provided that this copyright notice appears in all copies. For
kpeter@696
    11
 * precise terms see the accompanying LICENSE file.
kpeter@696
    12
 *
kpeter@696
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@696
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@696
    15
 * purpose.
kpeter@696
    16
 *
kpeter@696
    17
 */
kpeter@696
    18
kpeter@697
    19
#ifndef LEMON_BELLMAN_FORD_H
kpeter@697
    20
#define LEMON_BELLMAN_FORD_H
kpeter@696
    21
kpeter@696
    22
/// \ingroup shortest_path
kpeter@696
    23
/// \file
kpeter@696
    24
/// \brief Bellman-Ford algorithm.
kpeter@696
    25
kpeter@781
    26
#include <lemon/list_graph.h>
kpeter@696
    27
#include <lemon/bits/path_dump.h>
kpeter@696
    28
#include <lemon/core.h>
kpeter@696
    29
#include <lemon/error.h>
kpeter@696
    30
#include <lemon/maps.h>
kpeter@844
    31
#include <lemon/tolerance.h>
kpeter@697
    32
#include <lemon/path.h>
kpeter@696
    33
kpeter@696
    34
#include <limits>
kpeter@696
    35
kpeter@696
    36
namespace lemon {
kpeter@696
    37
kpeter@844
    38
  /// \brief Default operation traits for the BellmanFord algorithm class.
alpar@877
    39
  ///
kpeter@697
    40
  /// This operation traits class defines all computational operations
kpeter@697
    41
  /// and constants that are used in the Bellman-Ford algorithm.
kpeter@697
    42
  /// The default implementation is based on the \c numeric_limits class.
kpeter@697
    43
  /// If the numeric type does not have infinity value, then the maximum
kpeter@697
    44
  /// value is used as extremal infinity value.
kpeter@844
    45
  ///
kpeter@844
    46
  /// \see BellmanFordToleranceOperationTraits
kpeter@696
    47
  template <
alpar@877
    48
    typename V,
kpeter@697
    49
    bool has_inf = std::numeric_limits<V>::has_infinity>
kpeter@696
    50
  struct BellmanFordDefaultOperationTraits {
kpeter@844
    51
    /// \brief Value type for the algorithm.
kpeter@697
    52
    typedef V Value;
kpeter@696
    53
    /// \brief Gives back the zero value of the type.
kpeter@696
    54
    static Value zero() {
kpeter@696
    55
      return static_cast<Value>(0);
kpeter@696
    56
    }
kpeter@696
    57
    /// \brief Gives back the positive infinity value of the type.
kpeter@696
    58
    static Value infinity() {
kpeter@696
    59
      return std::numeric_limits<Value>::infinity();
kpeter@696
    60
    }
kpeter@696
    61
    /// \brief Gives back the sum of the given two elements.
kpeter@696
    62
    static Value plus(const Value& left, const Value& right) {
kpeter@696
    63
      return left + right;
kpeter@696
    64
    }
kpeter@697
    65
    /// \brief Gives back \c true only if the first value is less than
kpeter@697
    66
    /// the second.
kpeter@696
    67
    static bool less(const Value& left, const Value& right) {
kpeter@696
    68
      return left < right;
kpeter@696
    69
    }
kpeter@696
    70
  };
kpeter@696
    71
kpeter@697
    72
  template <typename V>
kpeter@697
    73
  struct BellmanFordDefaultOperationTraits<V, false> {
kpeter@697
    74
    typedef V Value;
kpeter@696
    75
    static Value zero() {
kpeter@696
    76
      return static_cast<Value>(0);
kpeter@696
    77
    }
kpeter@696
    78
    static Value infinity() {
kpeter@696
    79
      return std::numeric_limits<Value>::max();
kpeter@696
    80
    }
kpeter@696
    81
    static Value plus(const Value& left, const Value& right) {
kpeter@696
    82
      if (left == infinity() || right == infinity()) return infinity();
kpeter@696
    83
      return left + right;
kpeter@696
    84
    }
kpeter@696
    85
    static bool less(const Value& left, const Value& right) {
kpeter@696
    86
      return left < right;
kpeter@696
    87
    }
kpeter@696
    88
  };
alpar@877
    89
kpeter@844
    90
  /// \brief Operation traits for the BellmanFord algorithm class
kpeter@844
    91
  /// using tolerance.
kpeter@844
    92
  ///
kpeter@844
    93
  /// This operation traits class defines all computational operations
kpeter@844
    94
  /// and constants that are used in the Bellman-Ford algorithm.
kpeter@844
    95
  /// The only difference between this implementation and
kpeter@844
    96
  /// \ref BellmanFordDefaultOperationTraits is that this class uses
kpeter@844
    97
  /// the \ref Tolerance "tolerance technique" in its \ref less()
kpeter@844
    98
  /// function.
kpeter@844
    99
  ///
kpeter@844
   100
  /// \tparam V The value type.
kpeter@844
   101
  /// \tparam eps The epsilon value for the \ref less() function.
kpeter@844
   102
  /// By default, it is the epsilon value used by \ref Tolerance
kpeter@844
   103
  /// "Tolerance<V>".
kpeter@844
   104
  ///
kpeter@844
   105
  /// \see BellmanFordDefaultOperationTraits
kpeter@844
   106
#ifdef DOXYGEN
kpeter@844
   107
  template <typename V, V eps>
kpeter@844
   108
#else
kpeter@844
   109
  template <
kpeter@844
   110
    typename V,
kpeter@844
   111
    V eps = Tolerance<V>::def_epsilon>
kpeter@844
   112
#endif
kpeter@844
   113
  struct BellmanFordToleranceOperationTraits {
kpeter@844
   114
    /// \brief Value type for the algorithm.
kpeter@844
   115
    typedef V Value;
kpeter@844
   116
    /// \brief Gives back the zero value of the type.
kpeter@844
   117
    static Value zero() {
kpeter@844
   118
      return static_cast<Value>(0);
kpeter@844
   119
    }
kpeter@844
   120
    /// \brief Gives back the positive infinity value of the type.
kpeter@844
   121
    static Value infinity() {
kpeter@844
   122
      return std::numeric_limits<Value>::infinity();
kpeter@844
   123
    }
kpeter@844
   124
    /// \brief Gives back the sum of the given two elements.
kpeter@844
   125
    static Value plus(const Value& left, const Value& right) {
kpeter@844
   126
      return left + right;
kpeter@844
   127
    }
kpeter@844
   128
    /// \brief Gives back \c true only if the first value is less than
kpeter@844
   129
    /// the second.
kpeter@844
   130
    static bool less(const Value& left, const Value& right) {
kpeter@844
   131
      return left + eps < right;
kpeter@844
   132
    }
kpeter@844
   133
  };
kpeter@844
   134
kpeter@696
   135
  /// \brief Default traits class of BellmanFord class.
kpeter@696
   136
  ///
kpeter@696
   137
  /// Default traits class of BellmanFord class.
kpeter@697
   138
  /// \param GR The type of the digraph.
kpeter@697
   139
  /// \param LEN The type of the length map.
kpeter@697
   140
  template<typename GR, typename LEN>
kpeter@696
   141
  struct BellmanFordDefaultTraits {
alpar@877
   142
    /// The type of the digraph the algorithm runs on.
kpeter@697
   143
    typedef GR Digraph;
kpeter@696
   144
kpeter@696
   145
    /// \brief The type of the map that stores the arc lengths.
kpeter@696
   146
    ///
kpeter@696
   147
    /// The type of the map that stores the arc lengths.
kpeter@697
   148
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@697
   149
    typedef LEN LengthMap;
kpeter@696
   150
kpeter@697
   151
    /// The type of the arc lengths.
kpeter@697
   152
    typedef typename LEN::Value Value;
kpeter@696
   153
kpeter@696
   154
    /// \brief Operation traits for Bellman-Ford algorithm.
kpeter@696
   155
    ///
kpeter@697
   156
    /// It defines the used operations and the infinity value for the
kpeter@697
   157
    /// given \c Value type.
kpeter@844
   158
    /// \see BellmanFordDefaultOperationTraits,
kpeter@844
   159
    /// BellmanFordToleranceOperationTraits
kpeter@696
   160
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
alpar@877
   161
alpar@877
   162
    /// \brief The type of the map that stores the last arcs of the
kpeter@696
   163
    /// shortest paths.
alpar@877
   164
    ///
kpeter@696
   165
    /// The type of the map that stores the last
kpeter@696
   166
    /// arcs of the shortest paths.
kpeter@697
   167
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
kpeter@697
   168
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
kpeter@696
   169
kpeter@697
   170
    /// \brief Instantiates a \c PredMap.
alpar@877
   171
    ///
alpar@877
   172
    /// This function instantiates a \ref PredMap.
kpeter@697
   173
    /// \param g is the digraph to which we would like to define the
kpeter@697
   174
    /// \ref PredMap.
kpeter@697
   175
    static PredMap *createPredMap(const GR& g) {
kpeter@697
   176
      return new PredMap(g);
kpeter@696
   177
    }
kpeter@696
   178
kpeter@697
   179
    /// \brief The type of the map that stores the distances of the nodes.
kpeter@696
   180
    ///
kpeter@697
   181
    /// The type of the map that stores the distances of the nodes.
kpeter@697
   182
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
kpeter@697
   183
    typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
kpeter@696
   184
kpeter@697
   185
    /// \brief Instantiates a \c DistMap.
kpeter@696
   186
    ///
alpar@877
   187
    /// This function instantiates a \ref DistMap.
alpar@877
   188
    /// \param g is the digraph to which we would like to define the
kpeter@697
   189
    /// \ref DistMap.
kpeter@697
   190
    static DistMap *createDistMap(const GR& g) {
kpeter@697
   191
      return new DistMap(g);
kpeter@696
   192
    }
kpeter@696
   193
kpeter@696
   194
  };
alpar@877
   195
kpeter@696
   196
  /// \brief %BellmanFord algorithm class.
kpeter@696
   197
  ///
kpeter@696
   198
  /// \ingroup shortest_path
alpar@877
   199
  /// This class provides an efficient implementation of the Bellman-Ford
kpeter@697
   200
  /// algorithm. The maximum time complexity of the algorithm is
kpeter@697
   201
  /// <tt>O(ne)</tt>.
kpeter@697
   202
  ///
kpeter@697
   203
  /// The Bellman-Ford algorithm solves the single-source shortest path
kpeter@697
   204
  /// problem when the arcs can have negative lengths, but the digraph
kpeter@697
   205
  /// should not contain directed cycles with negative total length.
kpeter@697
   206
  /// If all arc costs are non-negative, consider to use the Dijkstra
kpeter@697
   207
  /// algorithm instead, since it is more efficient.
kpeter@697
   208
  ///
kpeter@697
   209
  /// The arc lengths are passed to the algorithm using a
alpar@877
   210
  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
kpeter@697
   211
  /// kind of length. The type of the length values is determined by the
kpeter@697
   212
  /// \ref concepts::ReadMap::Value "Value" type of the length map.
kpeter@696
   213
  ///
kpeter@697
   214
  /// There is also a \ref bellmanFord() "function-type interface" for the
kpeter@697
   215
  /// Bellman-Ford algorithm, which is convenient in the simplier cases and
kpeter@697
   216
  /// it can be used easier.
kpeter@696
   217
  ///
kpeter@697
   218
  /// \tparam GR The type of the digraph the algorithm runs on.
kpeter@697
   219
  /// The default type is \ref ListDigraph.
kpeter@697
   220
  /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
kpeter@697
   221
  /// the lengths of the arcs. The default map type is
kpeter@697
   222
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
kpeter@825
   223
  /// \tparam TR The traits class that defines various types used by the
kpeter@825
   224
  /// algorithm. By default, it is \ref BellmanFordDefaultTraits
kpeter@825
   225
  /// "BellmanFordDefaultTraits<GR, LEN>".
kpeter@825
   226
  /// In most cases, this parameter should not be set directly,
kpeter@825
   227
  /// consider to use the named template parameters instead.
kpeter@696
   228
#ifdef DOXYGEN
kpeter@697
   229
  template <typename GR, typename LEN, typename TR>
kpeter@696
   230
#else
kpeter@697
   231
  template <typename GR=ListDigraph,
kpeter@697
   232
            typename LEN=typename GR::template ArcMap<int>,
kpeter@697
   233
            typename TR=BellmanFordDefaultTraits<GR,LEN> >
kpeter@696
   234
#endif
kpeter@696
   235
  class BellmanFord {
kpeter@696
   236
  public:
kpeter@696
   237
kpeter@696
   238
    ///The type of the underlying digraph.
kpeter@697
   239
    typedef typename TR::Digraph Digraph;
alpar@877
   240
kpeter@697
   241
    /// \brief The type of the arc lengths.
kpeter@697
   242
    typedef typename TR::LengthMap::Value Value;
kpeter@697
   243
    /// \brief The type of the map that stores the arc lengths.
kpeter@697
   244
    typedef typename TR::LengthMap LengthMap;
kpeter@697
   245
    /// \brief The type of the map that stores the last
kpeter@697
   246
    /// arcs of the shortest paths.
kpeter@697
   247
    typedef typename TR::PredMap PredMap;
kpeter@697
   248
    /// \brief The type of the map that stores the distances of the nodes.
kpeter@697
   249
    typedef typename TR::DistMap DistMap;
kpeter@697
   250
    /// The type of the paths.
kpeter@697
   251
    typedef PredMapPath<Digraph, PredMap> Path;
kpeter@697
   252
    ///\brief The \ref BellmanFordDefaultOperationTraits
kpeter@697
   253
    /// "operation traits class" of the algorithm.
kpeter@697
   254
    typedef typename TR::OperationTraits OperationTraits;
kpeter@697
   255
kpeter@697
   256
    ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
kpeter@697
   257
    typedef TR Traits;
kpeter@697
   258
kpeter@697
   259
  private:
kpeter@696
   260
kpeter@696
   261
    typedef typename Digraph::Node Node;
kpeter@696
   262
    typedef typename Digraph::NodeIt NodeIt;
kpeter@696
   263
    typedef typename Digraph::Arc Arc;
kpeter@696
   264
    typedef typename Digraph::OutArcIt OutArcIt;
kpeter@697
   265
kpeter@697
   266
    // Pointer to the underlying digraph.
kpeter@697
   267
    const Digraph *_gr;
kpeter@697
   268
    // Pointer to the length map
kpeter@697
   269
    const LengthMap *_length;
kpeter@697
   270
    // Pointer to the map of predecessors arcs.
kpeter@696
   271
    PredMap *_pred;
kpeter@697
   272
    // Indicates if _pred is locally allocated (true) or not.
kpeter@697
   273
    bool _local_pred;
kpeter@697
   274
    // Pointer to the map of distances.
kpeter@696
   275
    DistMap *_dist;
kpeter@697
   276
    // Indicates if _dist is locally allocated (true) or not.
kpeter@697
   277
    bool _local_dist;
kpeter@696
   278
kpeter@696
   279
    typedef typename Digraph::template NodeMap<bool> MaskMap;
kpeter@696
   280
    MaskMap *_mask;
kpeter@696
   281
kpeter@696
   282
    std::vector<Node> _process;
kpeter@696
   283
kpeter@697
   284
    // Creates the maps if necessary.
kpeter@696
   285
    void create_maps() {
kpeter@696
   286
      if(!_pred) {
alpar@877
   287
        _local_pred = true;
alpar@877
   288
        _pred = Traits::createPredMap(*_gr);
kpeter@696
   289
      }
kpeter@696
   290
      if(!_dist) {
alpar@877
   291
        _local_dist = true;
alpar@877
   292
        _dist = Traits::createDistMap(*_gr);
kpeter@696
   293
      }
kpeter@804
   294
      if(!_mask) {
kpeter@804
   295
        _mask = new MaskMap(*_gr);
kpeter@804
   296
      }
kpeter@696
   297
    }
alpar@877
   298
kpeter@696
   299
  public :
alpar@877
   300
kpeter@696
   301
    typedef BellmanFord Create;
kpeter@696
   302
kpeter@697
   303
    /// \name Named Template Parameters
kpeter@696
   304
kpeter@696
   305
    ///@{
kpeter@696
   306
kpeter@696
   307
    template <class T>
kpeter@697
   308
    struct SetPredMapTraits : public Traits {
kpeter@696
   309
      typedef T PredMap;
kpeter@696
   310
      static PredMap *createPredMap(const Digraph&) {
kpeter@696
   311
        LEMON_ASSERT(false, "PredMap is not initialized");
kpeter@696
   312
        return 0; // ignore warnings
kpeter@696
   313
      }
kpeter@696
   314
    };
kpeter@696
   315
kpeter@697
   316
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@697
   317
    /// \c PredMap type.
kpeter@696
   318
    ///
kpeter@697
   319
    /// \ref named-templ-param "Named parameter" for setting
kpeter@697
   320
    /// \c PredMap type.
kpeter@697
   321
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
kpeter@696
   322
    template <class T>
alpar@877
   323
    struct SetPredMap
kpeter@697
   324
      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
kpeter@697
   325
      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
kpeter@696
   326
    };
alpar@877
   327
kpeter@696
   328
    template <class T>
kpeter@697
   329
    struct SetDistMapTraits : public Traits {
kpeter@696
   330
      typedef T DistMap;
kpeter@696
   331
      static DistMap *createDistMap(const Digraph&) {
kpeter@696
   332
        LEMON_ASSERT(false, "DistMap is not initialized");
kpeter@696
   333
        return 0; // ignore warnings
kpeter@696
   334
      }
kpeter@696
   335
    };
kpeter@696
   336
kpeter@697
   337
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@697
   338
    /// \c DistMap type.
kpeter@696
   339
    ///
kpeter@697
   340
    /// \ref named-templ-param "Named parameter" for setting
kpeter@697
   341
    /// \c DistMap type.
kpeter@697
   342
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
kpeter@696
   343
    template <class T>
alpar@877
   344
    struct SetDistMap
kpeter@697
   345
      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
kpeter@697
   346
      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
kpeter@696
   347
    };
kpeter@697
   348
kpeter@696
   349
    template <class T>
kpeter@697
   350
    struct SetOperationTraitsTraits : public Traits {
kpeter@696
   351
      typedef T OperationTraits;
kpeter@696
   352
    };
alpar@877
   353
alpar@877
   354
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@697
   355
    /// \c OperationTraits type.
kpeter@696
   356
    ///
kpeter@697
   357
    /// \ref named-templ-param "Named parameter" for setting
kpeter@697
   358
    /// \c OperationTraits type.
kpeter@786
   359
    /// For more information, see \ref BellmanFordDefaultOperationTraits.
kpeter@696
   360
    template <class T>
kpeter@696
   361
    struct SetOperationTraits
kpeter@697
   362
      : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
kpeter@697
   363
      typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
kpeter@696
   364
      Create;
kpeter@696
   365
    };
alpar@877
   366
kpeter@696
   367
    ///@}
kpeter@696
   368
kpeter@696
   369
  protected:
alpar@877
   370
kpeter@696
   371
    BellmanFord() {}
kpeter@696
   372
alpar@877
   373
  public:
alpar@877
   374
kpeter@696
   375
    /// \brief Constructor.
kpeter@696
   376
    ///
kpeter@697
   377
    /// Constructor.
kpeter@697
   378
    /// \param g The digraph the algorithm runs on.
kpeter@697
   379
    /// \param length The length map used by the algorithm.
kpeter@697
   380
    BellmanFord(const Digraph& g, const LengthMap& length) :
kpeter@697
   381
      _gr(&g), _length(&length),
kpeter@697
   382
      _pred(0), _local_pred(false),
kpeter@697
   383
      _dist(0), _local_dist(false), _mask(0) {}
alpar@877
   384
kpeter@696
   385
    ///Destructor.
kpeter@696
   386
    ~BellmanFord() {
kpeter@697
   387
      if(_local_pred) delete _pred;
kpeter@697
   388
      if(_local_dist) delete _dist;
kpeter@696
   389
      if(_mask) delete _mask;
kpeter@696
   390
    }
kpeter@696
   391
kpeter@696
   392
    /// \brief Sets the length map.
kpeter@696
   393
    ///
kpeter@696
   394
    /// Sets the length map.
kpeter@697
   395
    /// \return <tt>(*this)</tt>
kpeter@697
   396
    BellmanFord &lengthMap(const LengthMap &map) {
kpeter@697
   397
      _length = &map;
kpeter@696
   398
      return *this;
kpeter@696
   399
    }
kpeter@696
   400
kpeter@697
   401
    /// \brief Sets the map that stores the predecessor arcs.
kpeter@696
   402
    ///
kpeter@697
   403
    /// Sets the map that stores the predecessor arcs.
kpeter@697
   404
    /// If you don't use this function before calling \ref run()
kpeter@697
   405
    /// or \ref init(), an instance will be allocated automatically.
kpeter@697
   406
    /// The destructor deallocates this automatically allocated map,
kpeter@697
   407
    /// of course.
kpeter@697
   408
    /// \return <tt>(*this)</tt>
kpeter@697
   409
    BellmanFord &predMap(PredMap &map) {
kpeter@697
   410
      if(_local_pred) {
alpar@877
   411
        delete _pred;
alpar@877
   412
        _local_pred=false;
kpeter@696
   413
      }
kpeter@697
   414
      _pred = &map;
kpeter@696
   415
      return *this;
kpeter@696
   416
    }
kpeter@696
   417
kpeter@697
   418
    /// \brief Sets the map that stores the distances of the nodes.
kpeter@696
   419
    ///
kpeter@697
   420
    /// Sets the map that stores the distances of the nodes calculated
kpeter@697
   421
    /// by the algorithm.
kpeter@697
   422
    /// If you don't use this function before calling \ref run()
kpeter@697
   423
    /// or \ref init(), an instance will be allocated automatically.
kpeter@697
   424
    /// The destructor deallocates this automatically allocated map,
kpeter@697
   425
    /// of course.
kpeter@697
   426
    /// \return <tt>(*this)</tt>
kpeter@697
   427
    BellmanFord &distMap(DistMap &map) {
kpeter@697
   428
      if(_local_dist) {
alpar@877
   429
        delete _dist;
alpar@877
   430
        _local_dist=false;
kpeter@696
   431
      }
kpeter@697
   432
      _dist = &map;
kpeter@696
   433
      return *this;
kpeter@696
   434
    }
kpeter@696
   435
kpeter@697
   436
    /// \name Execution Control
kpeter@697
   437
    /// The simplest way to execute the Bellman-Ford algorithm is to use
kpeter@697
   438
    /// one of the member functions called \ref run().\n
kpeter@697
   439
    /// If you need better control on the execution, you have to call
kpeter@697
   440
    /// \ref init() first, then you can add several source nodes
kpeter@697
   441
    /// with \ref addSource(). Finally the actual path computation can be
kpeter@697
   442
    /// performed with \ref start(), \ref checkedStart() or
kpeter@697
   443
    /// \ref limitedStart().
kpeter@696
   444
kpeter@696
   445
    ///@{
kpeter@696
   446
kpeter@696
   447
    /// \brief Initializes the internal data structures.
alpar@877
   448
    ///
kpeter@697
   449
    /// Initializes the internal data structures. The optional parameter
kpeter@697
   450
    /// is the initial distance of each node.
kpeter@696
   451
    void init(const Value value = OperationTraits::infinity()) {
kpeter@696
   452
      create_maps();
kpeter@697
   453
      for (NodeIt it(*_gr); it != INVALID; ++it) {
alpar@877
   454
        _pred->set(it, INVALID);
alpar@877
   455
        _dist->set(it, value);
kpeter@696
   456
      }
kpeter@696
   457
      _process.clear();
kpeter@696
   458
      if (OperationTraits::less(value, OperationTraits::infinity())) {
alpar@877
   459
        for (NodeIt it(*_gr); it != INVALID; ++it) {
alpar@877
   460
          _process.push_back(it);
alpar@877
   461
          _mask->set(it, true);
alpar@877
   462
        }
kpeter@804
   463
      } else {
alpar@877
   464
        for (NodeIt it(*_gr); it != INVALID; ++it) {
alpar@877
   465
          _mask->set(it, false);
alpar@877
   466
        }
kpeter@696
   467
      }
kpeter@696
   468
    }
alpar@877
   469
kpeter@696
   470
    /// \brief Adds a new source node.
kpeter@696
   471
    ///
kpeter@697
   472
    /// This function adds a new source node. The optional second parameter
kpeter@697
   473
    /// is the initial distance of the node.
kpeter@696
   474
    void addSource(Node source, Value dst = OperationTraits::zero()) {
kpeter@696
   475
      _dist->set(source, dst);
kpeter@696
   476
      if (!(*_mask)[source]) {
alpar@877
   477
        _process.push_back(source);
alpar@877
   478
        _mask->set(source, true);
kpeter@696
   479
      }
kpeter@696
   480
    }
kpeter@696
   481
kpeter@696
   482
    /// \brief Executes one round from the Bellman-Ford algorithm.
kpeter@696
   483
    ///
kpeter@696
   484
    /// If the algoritm calculated the distances in the previous round
kpeter@697
   485
    /// exactly for the paths of at most \c k arcs, then this function
kpeter@697
   486
    /// will calculate the distances exactly for the paths of at most
kpeter@697
   487
    /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
kpeter@697
   488
    /// calculates the shortest path distances exactly for the paths
kpeter@697
   489
    /// consisting of at most \c k arcs.
kpeter@696
   490
    ///
kpeter@696
   491
    /// \warning The paths with limited arc number cannot be retrieved
kpeter@697
   492
    /// easily with \ref path() or \ref predArc() functions. If you also
kpeter@697
   493
    /// need the shortest paths and not only the distances, you should
kpeter@697
   494
    /// store the \ref predMap() "predecessor map" after each iteration
kpeter@697
   495
    /// and build the path manually.
kpeter@696
   496
    ///
kpeter@696
   497
    /// \return \c true when the algorithm have not found more shorter
kpeter@696
   498
    /// paths.
kpeter@697
   499
    ///
kpeter@697
   500
    /// \see ActiveIt
kpeter@696
   501
    bool processNextRound() {
kpeter@696
   502
      for (int i = 0; i < int(_process.size()); ++i) {
alpar@877
   503
        _mask->set(_process[i], false);
kpeter@696
   504
      }
kpeter@696
   505
      std::vector<Node> nextProcess;
kpeter@696
   506
      std::vector<Value> values(_process.size());
kpeter@696
   507
      for (int i = 0; i < int(_process.size()); ++i) {
alpar@877
   508
        values[i] = (*_dist)[_process[i]];
kpeter@696
   509
      }
kpeter@696
   510
      for (int i = 0; i < int(_process.size()); ++i) {
alpar@877
   511
        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
alpar@877
   512
          Node target = _gr->target(it);
alpar@877
   513
          Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
alpar@877
   514
          if (OperationTraits::less(relaxed, (*_dist)[target])) {
alpar@877
   515
            _pred->set(target, it);
alpar@877
   516
            _dist->set(target, relaxed);
alpar@877
   517
            if (!(*_mask)[target]) {
alpar@877
   518
              _mask->set(target, true);
alpar@877
   519
              nextProcess.push_back(target);
alpar@877
   520
            }
alpar@877
   521
          }
alpar@877
   522
        }
kpeter@696
   523
      }
kpeter@696
   524
      _process.swap(nextProcess);
kpeter@696
   525
      return _process.empty();
kpeter@696
   526
    }
kpeter@696
   527
kpeter@696
   528
    /// \brief Executes one weak round from the Bellman-Ford algorithm.
kpeter@696
   529
    ///
kpeter@697
   530
    /// If the algorithm calculated the distances in the previous round
kpeter@697
   531
    /// at least for the paths of at most \c k arcs, then this function
kpeter@697
   532
    /// will calculate the distances at least for the paths of at most
kpeter@697
   533
    /// <tt>k+1</tt> arcs.
kpeter@697
   534
    /// This function does not make it possible to calculate the shortest
kpeter@697
   535
    /// path distances exactly for paths consisting of at most \c k arcs,
kpeter@697
   536
    /// this is why it is called weak round.
kpeter@697
   537
    ///
kpeter@697
   538
    /// \return \c true when the algorithm have not found more shorter
kpeter@697
   539
    /// paths.
kpeter@697
   540
    ///
kpeter@697
   541
    /// \see ActiveIt
kpeter@696
   542
    bool processNextWeakRound() {
kpeter@696
   543
      for (int i = 0; i < int(_process.size()); ++i) {
alpar@877
   544
        _mask->set(_process[i], false);
kpeter@696
   545
      }
kpeter@696
   546
      std::vector<Node> nextProcess;
kpeter@696
   547
      for (int i = 0; i < int(_process.size()); ++i) {
alpar@877
   548
        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
alpar@877
   549
          Node target = _gr->target(it);
alpar@877
   550
          Value relaxed =
alpar@877
   551
            OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
alpar@877
   552
          if (OperationTraits::less(relaxed, (*_dist)[target])) {
alpar@877
   553
            _pred->set(target, it);
alpar@877
   554
            _dist->set(target, relaxed);
alpar@877
   555
            if (!(*_mask)[target]) {
alpar@877
   556
              _mask->set(target, true);
alpar@877
   557
              nextProcess.push_back(target);
alpar@877
   558
            }
alpar@877
   559
          }
alpar@877
   560
        }
kpeter@696
   561
      }
kpeter@696
   562
      _process.swap(nextProcess);
kpeter@696
   563
      return _process.empty();
kpeter@696
   564
    }
kpeter@696
   565
kpeter@696
   566
    /// \brief Executes the algorithm.
kpeter@696
   567
    ///
kpeter@697
   568
    /// Executes the algorithm.
kpeter@696
   569
    ///
kpeter@697
   570
    /// This method runs the Bellman-Ford algorithm from the root node(s)
kpeter@697
   571
    /// in order to compute the shortest path to each node.
kpeter@697
   572
    ///
kpeter@697
   573
    /// The algorithm computes
kpeter@697
   574
    /// - the shortest path tree (forest),
kpeter@697
   575
    /// - the distance of each node from the root(s).
kpeter@697
   576
    ///
kpeter@697
   577
    /// \pre init() must be called and at least one root node should be
kpeter@697
   578
    /// added with addSource() before using this function.
kpeter@696
   579
    void start() {
kpeter@697
   580
      int num = countNodes(*_gr) - 1;
kpeter@696
   581
      for (int i = 0; i < num; ++i) {
alpar@877
   582
        if (processNextWeakRound()) break;
kpeter@696
   583
      }
kpeter@696
   584
    }
kpeter@696
   585
kpeter@696
   586
    /// \brief Executes the algorithm and checks the negative cycles.
kpeter@696
   587
    ///
kpeter@697
   588
    /// Executes the algorithm and checks the negative cycles.
kpeter@696
   589
    ///
kpeter@697
   590
    /// This method runs the Bellman-Ford algorithm from the root node(s)
kpeter@697
   591
    /// in order to compute the shortest path to each node and also checks
kpeter@697
   592
    /// if the digraph contains cycles with negative total length.
kpeter@697
   593
    ///
alpar@877
   594
    /// The algorithm computes
kpeter@697
   595
    /// - the shortest path tree (forest),
kpeter@697
   596
    /// - the distance of each node from the root(s).
alpar@877
   597
    ///
kpeter@696
   598
    /// \return \c false if there is a negative cycle in the digraph.
kpeter@697
   599
    ///
kpeter@697
   600
    /// \pre init() must be called and at least one root node should be
alpar@877
   601
    /// added with addSource() before using this function.
kpeter@696
   602
    bool checkedStart() {
kpeter@697
   603
      int num = countNodes(*_gr);
kpeter@696
   604
      for (int i = 0; i < num; ++i) {
alpar@877
   605
        if (processNextWeakRound()) return true;
kpeter@696
   606
      }
kpeter@696
   607
      return _process.empty();
kpeter@696
   608
    }
kpeter@696
   609
kpeter@697
   610
    /// \brief Executes the algorithm with arc number limit.
kpeter@696
   611
    ///
kpeter@697
   612
    /// Executes the algorithm with arc number limit.
kpeter@696
   613
    ///
kpeter@697
   614
    /// This method runs the Bellman-Ford algorithm from the root node(s)
kpeter@697
   615
    /// in order to compute the shortest path distance for each node
kpeter@697
   616
    /// using only the paths consisting of at most \c num arcs.
kpeter@697
   617
    ///
kpeter@697
   618
    /// The algorithm computes
kpeter@697
   619
    /// - the limited distance of each node from the root(s),
kpeter@697
   620
    /// - the predecessor arc for each node.
kpeter@696
   621
    ///
kpeter@696
   622
    /// \warning The paths with limited arc number cannot be retrieved
kpeter@697
   623
    /// easily with \ref path() or \ref predArc() functions. If you also
kpeter@697
   624
    /// need the shortest paths and not only the distances, you should
kpeter@697
   625
    /// store the \ref predMap() "predecessor map" after each iteration
kpeter@697
   626
    /// and build the path manually.
kpeter@696
   627
    ///
kpeter@697
   628
    /// \pre init() must be called and at least one root node should be
alpar@877
   629
    /// added with addSource() before using this function.
kpeter@696
   630
    void limitedStart(int num) {
kpeter@696
   631
      for (int i = 0; i < num; ++i) {
alpar@877
   632
        if (processNextRound()) break;
kpeter@696
   633
      }
kpeter@696
   634
    }
alpar@877
   635
kpeter@697
   636
    /// \brief Runs the algorithm from the given root node.
alpar@877
   637
    ///
kpeter@697
   638
    /// This method runs the Bellman-Ford algorithm from the given root
kpeter@697
   639
    /// node \c s in order to compute the shortest path to each node.
kpeter@696
   640
    ///
kpeter@697
   641
    /// The algorithm computes
kpeter@697
   642
    /// - the shortest path tree (forest),
kpeter@697
   643
    /// - the distance of each node from the root(s).
kpeter@697
   644
    ///
kpeter@697
   645
    /// \note bf.run(s) is just a shortcut of the following code.
kpeter@697
   646
    /// \code
kpeter@697
   647
    ///   bf.init();
kpeter@697
   648
    ///   bf.addSource(s);
kpeter@697
   649
    ///   bf.start();
kpeter@697
   650
    /// \endcode
kpeter@696
   651
    void run(Node s) {
kpeter@696
   652
      init();
kpeter@696
   653
      addSource(s);
kpeter@696
   654
      start();
kpeter@696
   655
    }
alpar@877
   656
kpeter@697
   657
    /// \brief Runs the algorithm from the given root node with arc
kpeter@697
   658
    /// number limit.
alpar@877
   659
    ///
kpeter@697
   660
    /// This method runs the Bellman-Ford algorithm from the given root
kpeter@697
   661
    /// node \c s in order to compute the shortest path distance for each
kpeter@697
   662
    /// node using only the paths consisting of at most \c num arcs.
kpeter@696
   663
    ///
kpeter@697
   664
    /// The algorithm computes
kpeter@697
   665
    /// - the limited distance of each node from the root(s),
kpeter@697
   666
    /// - the predecessor arc for each node.
kpeter@697
   667
    ///
kpeter@697
   668
    /// \warning The paths with limited arc number cannot be retrieved
kpeter@697
   669
    /// easily with \ref path() or \ref predArc() functions. If you also
kpeter@697
   670
    /// need the shortest paths and not only the distances, you should
kpeter@697
   671
    /// store the \ref predMap() "predecessor map" after each iteration
kpeter@697
   672
    /// and build the path manually.
kpeter@697
   673
    ///
kpeter@697
   674
    /// \note bf.run(s, num) is just a shortcut of the following code.
kpeter@697
   675
    /// \code
kpeter@697
   676
    ///   bf.init();
kpeter@697
   677
    ///   bf.addSource(s);
kpeter@697
   678
    ///   bf.limitedStart(num);
kpeter@697
   679
    /// \endcode
kpeter@696
   680
    void run(Node s, int num) {
kpeter@696
   681
      init();
kpeter@696
   682
      addSource(s);
kpeter@696
   683
      limitedStart(num);
kpeter@696
   684
    }
alpar@877
   685
kpeter@696
   686
    ///@}
kpeter@696
   687
kpeter@697
   688
    /// \brief LEMON iterator for getting the active nodes.
kpeter@696
   689
    ///
kpeter@697
   690
    /// This class provides a common style LEMON iterator that traverses
kpeter@697
   691
    /// the active nodes of the Bellman-Ford algorithm after the last
kpeter@697
   692
    /// phase. These nodes should be checked in the next phase to
kpeter@697
   693
    /// find augmenting arcs outgoing from them.
kpeter@696
   694
    class ActiveIt {
kpeter@696
   695
    public:
kpeter@696
   696
kpeter@696
   697
      /// \brief Constructor.
kpeter@696
   698
      ///
kpeter@697
   699
      /// Constructor for getting the active nodes of the given BellmanFord
alpar@877
   700
      /// instance.
kpeter@696
   701
      ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
kpeter@696
   702
      {
kpeter@696
   703
        _index = _algorithm->_process.size() - 1;
kpeter@696
   704
      }
kpeter@696
   705
kpeter@696
   706
      /// \brief Invalid constructor.
kpeter@696
   707
      ///
kpeter@696
   708
      /// Invalid constructor.
kpeter@696
   709
      ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
kpeter@696
   710
kpeter@697
   711
      /// \brief Conversion to \c Node.
kpeter@696
   712
      ///
kpeter@697
   713
      /// Conversion to \c Node.
alpar@877
   714
      operator Node() const {
kpeter@696
   715
        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
kpeter@696
   716
      }
kpeter@696
   717
kpeter@696
   718
      /// \brief Increment operator.
kpeter@696
   719
      ///
kpeter@696
   720
      /// Increment operator.
kpeter@696
   721
      ActiveIt& operator++() {
kpeter@696
   722
        --_index;
alpar@877
   723
        return *this;
kpeter@696
   724
      }
kpeter@696
   725
alpar@877
   726
      bool operator==(const ActiveIt& it) const {
alpar@877
   727
        return static_cast<Node>(*this) == static_cast<Node>(it);
kpeter@696
   728
      }
alpar@877
   729
      bool operator!=(const ActiveIt& it) const {
alpar@877
   730
        return static_cast<Node>(*this) != static_cast<Node>(it);
kpeter@696
   731
      }
alpar@877
   732
      bool operator<(const ActiveIt& it) const {
alpar@877
   733
        return static_cast<Node>(*this) < static_cast<Node>(it);
kpeter@696
   734
      }
alpar@877
   735
kpeter@696
   736
    private:
kpeter@696
   737
      const BellmanFord* _algorithm;
kpeter@696
   738
      int _index;
kpeter@696
   739
    };
alpar@877
   740
kpeter@697
   741
    /// \name Query Functions
kpeter@697
   742
    /// The result of the Bellman-Ford algorithm can be obtained using these
kpeter@697
   743
    /// functions.\n
kpeter@697
   744
    /// Either \ref run() or \ref init() should be called before using them.
alpar@877
   745
kpeter@697
   746
    ///@{
kpeter@696
   747
kpeter@697
   748
    /// \brief The shortest path to the given node.
alpar@877
   749
    ///
kpeter@697
   750
    /// Gives back the shortest path to the given node from the root(s).
kpeter@697
   751
    ///
kpeter@697
   752
    /// \warning \c t should be reached from the root(s).
kpeter@697
   753
    ///
kpeter@697
   754
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   755
    /// using this function.
kpeter@697
   756
    Path path(Node t) const
kpeter@697
   757
    {
kpeter@697
   758
      return Path(*_gr, *_pred, t);
kpeter@697
   759
    }
alpar@877
   760
kpeter@697
   761
    /// \brief The distance of the given node from the root(s).
kpeter@697
   762
    ///
kpeter@697
   763
    /// Returns the distance of the given node from the root(s).
kpeter@697
   764
    ///
kpeter@697
   765
    /// \warning If node \c v is not reached from the root(s), then
kpeter@697
   766
    /// the return value of this function is undefined.
kpeter@697
   767
    ///
kpeter@697
   768
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   769
    /// using this function.
kpeter@697
   770
    Value dist(Node v) const { return (*_dist)[v]; }
kpeter@696
   771
kpeter@697
   772
    /// \brief Returns the 'previous arc' of the shortest path tree for
kpeter@697
   773
    /// the given node.
kpeter@697
   774
    ///
kpeter@697
   775
    /// This function returns the 'previous arc' of the shortest path
kpeter@697
   776
    /// tree for node \c v, i.e. it returns the last arc of a
kpeter@697
   777
    /// shortest path from a root to \c v. It is \c INVALID if \c v
kpeter@697
   778
    /// is not reached from the root(s) or if \c v is a root.
kpeter@697
   779
    ///
kpeter@697
   780
    /// The shortest path tree used here is equal to the shortest path
kpeter@786
   781
    /// tree used in \ref predNode() and \ref predMap().
kpeter@697
   782
    ///
kpeter@697
   783
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   784
    /// using this function.
kpeter@697
   785
    Arc predArc(Node v) const { return (*_pred)[v]; }
kpeter@697
   786
kpeter@697
   787
    /// \brief Returns the 'previous node' of the shortest path tree for
kpeter@697
   788
    /// the given node.
kpeter@697
   789
    ///
kpeter@697
   790
    /// This function returns the 'previous node' of the shortest path
kpeter@697
   791
    /// tree for node \c v, i.e. it returns the last but one node of
kpeter@697
   792
    /// a shortest path from a root to \c v. It is \c INVALID if \c v
kpeter@697
   793
    /// is not reached from the root(s) or if \c v is a root.
kpeter@697
   794
    ///
kpeter@697
   795
    /// The shortest path tree used here is equal to the shortest path
kpeter@786
   796
    /// tree used in \ref predArc() and \ref predMap().
kpeter@697
   797
    ///
kpeter@697
   798
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   799
    /// using this function.
alpar@877
   800
    Node predNode(Node v) const {
alpar@877
   801
      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
kpeter@697
   802
    }
alpar@877
   803
kpeter@697
   804
    /// \brief Returns a const reference to the node map that stores the
kpeter@697
   805
    /// distances of the nodes.
kpeter@697
   806
    ///
kpeter@697
   807
    /// Returns a const reference to the node map that stores the distances
kpeter@697
   808
    /// of the nodes calculated by the algorithm.
kpeter@697
   809
    ///
kpeter@697
   810
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   811
    /// using this function.
kpeter@697
   812
    const DistMap &distMap() const { return *_dist;}
alpar@877
   813
kpeter@697
   814
    /// \brief Returns a const reference to the node map that stores the
kpeter@697
   815
    /// predecessor arcs.
kpeter@697
   816
    ///
kpeter@697
   817
    /// Returns a const reference to the node map that stores the predecessor
kpeter@697
   818
    /// arcs, which form the shortest path tree (forest).
kpeter@697
   819
    ///
kpeter@697
   820
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   821
    /// using this function.
kpeter@697
   822
    const PredMap &predMap() const { return *_pred; }
alpar@877
   823
kpeter@697
   824
    /// \brief Checks if a node is reached from the root(s).
kpeter@697
   825
    ///
kpeter@697
   826
    /// Returns \c true if \c v is reached from the root(s).
kpeter@697
   827
    ///
kpeter@697
   828
    /// \pre Either \ref run() or \ref init() must be called before
kpeter@697
   829
    /// using this function.
kpeter@697
   830
    bool reached(Node v) const {
kpeter@697
   831
      return (*_dist)[v] != OperationTraits::infinity();
kpeter@696
   832
    }
kpeter@696
   833
kpeter@699
   834
    /// \brief Gives back a negative cycle.
alpar@877
   835
    ///
kpeter@699
   836
    /// This function gives back a directed cycle with negative total
kpeter@699
   837
    /// length if the algorithm has already found one.
kpeter@699
   838
    /// Otherwise it gives back an empty path.
kpeter@781
   839
    lemon::Path<Digraph> negativeCycle() const {
kpeter@699
   840
      typename Digraph::template NodeMap<int> state(*_gr, -1);
kpeter@699
   841
      lemon::Path<Digraph> cycle;
kpeter@699
   842
      for (int i = 0; i < int(_process.size()); ++i) {
kpeter@699
   843
        if (state[_process[i]] != -1) continue;
kpeter@699
   844
        for (Node v = _process[i]; (*_pred)[v] != INVALID;
kpeter@699
   845
             v = _gr->source((*_pred)[v])) {
kpeter@699
   846
          if (state[v] == i) {
kpeter@699
   847
            cycle.addFront((*_pred)[v]);
kpeter@699
   848
            for (Node u = _gr->source((*_pred)[v]); u != v;
kpeter@699
   849
                 u = _gr->source((*_pred)[u])) {
kpeter@699
   850
              cycle.addFront((*_pred)[u]);
kpeter@699
   851
            }
kpeter@699
   852
            return cycle;
kpeter@699
   853
          }
kpeter@699
   854
          else if (state[v] >= 0) {
kpeter@699
   855
            break;
kpeter@699
   856
          }
kpeter@699
   857
          state[v] = i;
kpeter@699
   858
        }
kpeter@699
   859
      }
kpeter@699
   860
      return cycle;
kpeter@699
   861
    }
alpar@877
   862
kpeter@696
   863
    ///@}
kpeter@696
   864
  };
alpar@877
   865
kpeter@697
   866
  /// \brief Default traits class of bellmanFord() function.
kpeter@696
   867
  ///
kpeter@697
   868
  /// Default traits class of bellmanFord() function.
kpeter@697
   869
  /// \tparam GR The type of the digraph.
kpeter@697
   870
  /// \tparam LEN The type of the length map.
kpeter@697
   871
  template <typename GR, typename LEN>
kpeter@696
   872
  struct BellmanFordWizardDefaultTraits {
alpar@877
   873
    /// The type of the digraph the algorithm runs on.
kpeter@697
   874
    typedef GR Digraph;
kpeter@696
   875
kpeter@696
   876
    /// \brief The type of the map that stores the arc lengths.
kpeter@696
   877
    ///
kpeter@696
   878
    /// The type of the map that stores the arc lengths.
kpeter@696
   879
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
kpeter@697
   880
    typedef LEN LengthMap;
kpeter@696
   881
kpeter@697
   882
    /// The type of the arc lengths.
kpeter@697
   883
    typedef typename LEN::Value Value;
kpeter@696
   884
kpeter@696
   885
    /// \brief Operation traits for Bellman-Ford algorithm.
kpeter@696
   886
    ///
kpeter@697
   887
    /// It defines the used operations and the infinity value for the
kpeter@697
   888
    /// given \c Value type.
kpeter@844
   889
    /// \see BellmanFordDefaultOperationTraits,
kpeter@844
   890
    /// BellmanFordToleranceOperationTraits
kpeter@696
   891
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
kpeter@696
   892
kpeter@696
   893
    /// \brief The type of the map that stores the last
kpeter@696
   894
    /// arcs of the shortest paths.
alpar@877
   895
    ///
kpeter@697
   896
    /// The type of the map that stores the last arcs of the shortest paths.
kpeter@697
   897
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
kpeter@697
   898
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
kpeter@696
   899
kpeter@697
   900
    /// \brief Instantiates a \c PredMap.
alpar@877
   901
    ///
kpeter@697
   902
    /// This function instantiates a \ref PredMap.
kpeter@697
   903
    /// \param g is the digraph to which we would like to define the
kpeter@697
   904
    /// \ref PredMap.
kpeter@697
   905
    static PredMap *createPredMap(const GR &g) {
kpeter@697
   906
      return new PredMap(g);
kpeter@696
   907
    }
kpeter@697
   908
kpeter@697
   909
    /// \brief The type of the map that stores the distances of the nodes.
kpeter@696
   910
    ///
kpeter@697
   911
    /// The type of the map that stores the distances of the nodes.
kpeter@697
   912
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
kpeter@697
   913
    typedef typename GR::template NodeMap<Value> DistMap;
kpeter@697
   914
kpeter@697
   915
    /// \brief Instantiates a \c DistMap.
kpeter@696
   916
    ///
alpar@877
   917
    /// This function instantiates a \ref DistMap.
kpeter@697
   918
    /// \param g is the digraph to which we would like to define the
kpeter@697
   919
    /// \ref DistMap.
kpeter@697
   920
    static DistMap *createDistMap(const GR &g) {
kpeter@697
   921
      return new DistMap(g);
kpeter@696
   922
    }
kpeter@697
   923
kpeter@697
   924
    ///The type of the shortest paths.
kpeter@697
   925
kpeter@697
   926
    ///The type of the shortest paths.
kpeter@697
   927
    ///It must meet the \ref concepts::Path "Path" concept.
kpeter@697
   928
    typedef lemon::Path<Digraph> Path;
kpeter@696
   929
  };
alpar@877
   930
kpeter@697
   931
  /// \brief Default traits class used by BellmanFordWizard.
kpeter@696
   932
  ///
kpeter@697
   933
  /// Default traits class used by BellmanFordWizard.
kpeter@697
   934
  /// \tparam GR The type of the digraph.
kpeter@697
   935
  /// \tparam LEN The type of the length map.
kpeter@697
   936
  template <typename GR, typename LEN>
alpar@877
   937
  class BellmanFordWizardBase
kpeter@697
   938
    : public BellmanFordWizardDefaultTraits<GR, LEN> {
kpeter@696
   939
kpeter@697
   940
    typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
kpeter@696
   941
  protected:
kpeter@697
   942
    // Type of the nodes in the digraph.
kpeter@696
   943
    typedef typename Base::Digraph::Node Node;
kpeter@696
   944
kpeter@697
   945
    // Pointer to the underlying digraph.
kpeter@696
   946
    void *_graph;
kpeter@697
   947
    // Pointer to the length map
kpeter@696
   948
    void *_length;
kpeter@697
   949
    // Pointer to the map of predecessors arcs.
kpeter@696
   950
    void *_pred;
kpeter@697
   951
    // Pointer to the map of distances.
kpeter@696
   952
    void *_dist;
kpeter@697
   953
    //Pointer to the shortest path to the target node.
kpeter@697
   954
    void *_path;
kpeter@697
   955
    //Pointer to the distance of the target node.
kpeter@697
   956
    void *_di;
kpeter@696
   957
kpeter@696
   958
    public:
kpeter@696
   959
    /// Constructor.
alpar@877
   960
kpeter@697
   961
    /// This constructor does not require parameters, it initiates
kpeter@697
   962
    /// all of the attributes to default values \c 0.
kpeter@697
   963
    BellmanFordWizardBase() :
kpeter@697
   964
      _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
kpeter@696
   965
kpeter@696
   966
    /// Constructor.
alpar@877
   967
kpeter@697
   968
    /// This constructor requires two parameters,
kpeter@697
   969
    /// others are initiated to \c 0.
kpeter@697
   970
    /// \param gr The digraph the algorithm runs on.
kpeter@697
   971
    /// \param len The length map.
alpar@877
   972
    BellmanFordWizardBase(const GR& gr,
alpar@877
   973
                          const LEN& len) :
alpar@877
   974
      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
alpar@877
   975
      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
kpeter@697
   976
      _pred(0), _dist(0), _path(0), _di(0) {}
kpeter@696
   977
kpeter@696
   978
  };
alpar@877
   979
kpeter@697
   980
  /// \brief Auxiliary class for the function-type interface of the
kpeter@697
   981
  /// \ref BellmanFord "Bellman-Ford" algorithm.
kpeter@697
   982
  ///
kpeter@697
   983
  /// This auxiliary class is created to implement the
kpeter@697
   984
  /// \ref bellmanFord() "function-type interface" of the
kpeter@697
   985
  /// \ref BellmanFord "Bellman-Ford" algorithm.
kpeter@697
   986
  /// It does not have own \ref run() method, it uses the
kpeter@697
   987
  /// functions and features of the plain \ref BellmanFord.
kpeter@697
   988
  ///
kpeter@697
   989
  /// This class should only be used through the \ref bellmanFord()
kpeter@697
   990
  /// function, which makes it easier to use the algorithm.
kpeter@825
   991
  ///
kpeter@825
   992
  /// \tparam TR The traits class that defines various types used by the
kpeter@825
   993
  /// algorithm.
kpeter@697
   994
  template<class TR>
kpeter@697
   995
  class BellmanFordWizard : public TR {
kpeter@697
   996
    typedef TR Base;
kpeter@696
   997
kpeter@697
   998
    typedef typename TR::Digraph Digraph;
kpeter@696
   999
kpeter@696
  1000
    typedef typename Digraph::Node Node;
kpeter@696
  1001
    typedef typename Digraph::NodeIt NodeIt;
kpeter@696
  1002
    typedef typename Digraph::Arc Arc;
kpeter@696
  1003
    typedef typename Digraph::OutArcIt ArcIt;
alpar@877
  1004
kpeter@697
  1005
    typedef typename TR::LengthMap LengthMap;
kpeter@696
  1006
    typedef typename LengthMap::Value Value;
kpeter@697
  1007
    typedef typename TR::PredMap PredMap;
kpeter@697
  1008
    typedef typename TR::DistMap DistMap;
kpeter@697
  1009
    typedef typename TR::Path Path;
kpeter@696
  1010
kpeter@696
  1011
  public:
kpeter@696
  1012
    /// Constructor.
kpeter@697
  1013
    BellmanFordWizard() : TR() {}
kpeter@696
  1014
kpeter@696
  1015
    /// \brief Constructor that requires parameters.
kpeter@696
  1016
    ///
kpeter@696
  1017
    /// Constructor that requires parameters.
kpeter@696
  1018
    /// These parameters will be the default values for the traits class.
kpeter@697
  1019
    /// \param gr The digraph the algorithm runs on.
kpeter@697
  1020
    /// \param len The length map.
alpar@877
  1021
    BellmanFordWizard(const Digraph& gr, const LengthMap& len)
kpeter@697
  1022
      : TR(gr, len) {}
kpeter@696
  1023
kpeter@696
  1024
    /// \brief Copy constructor
kpeter@697
  1025
    BellmanFordWizard(const TR &b) : TR(b) {}
kpeter@696
  1026
kpeter@696
  1027
    ~BellmanFordWizard() {}
kpeter@696
  1028
kpeter@697
  1029
    /// \brief Runs the Bellman-Ford algorithm from the given source node.
alpar@877
  1030
    ///
kpeter@697
  1031
    /// This method runs the Bellman-Ford algorithm from the given source
kpeter@697
  1032
    /// node in order to compute the shortest path to each node.
kpeter@697
  1033
    void run(Node s) {
alpar@877
  1034
      BellmanFord<Digraph,LengthMap,TR>
alpar@877
  1035
        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
kpeter@696
  1036
           *reinterpret_cast<const LengthMap*>(Base::_length));
kpeter@696
  1037
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
kpeter@696
  1038
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
kpeter@697
  1039
      bf.run(s);
kpeter@696
  1040
    }
kpeter@696
  1041
kpeter@697
  1042
    /// \brief Runs the Bellman-Ford algorithm to find the shortest path
kpeter@697
  1043
    /// between \c s and \c t.
kpeter@696
  1044
    ///
kpeter@697
  1045
    /// This method runs the Bellman-Ford algorithm from node \c s
kpeter@697
  1046
    /// in order to compute the shortest path to node \c t.
kpeter@697
  1047
    /// Actually, it computes the shortest path to each node, but using
kpeter@697
  1048
    /// this function you can retrieve the distance and the shortest path
kpeter@697
  1049
    /// for a single target node easier.
kpeter@697
  1050
    ///
kpeter@697
  1051
    /// \return \c true if \c t is reachable form \c s.
kpeter@697
  1052
    bool run(Node s, Node t) {
kpeter@697
  1053
      BellmanFord<Digraph,LengthMap,TR>
kpeter@697
  1054
        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
kpeter@697
  1055
           *reinterpret_cast<const LengthMap*>(Base::_length));
kpeter@697
  1056
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
kpeter@697
  1057
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
kpeter@697
  1058
      bf.run(s);
kpeter@697
  1059
      if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
kpeter@697
  1060
      if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
kpeter@697
  1061
      return bf.reached(t);
kpeter@696
  1062
    }
kpeter@696
  1063
kpeter@696
  1064
    template<class T>
kpeter@697
  1065
    struct SetPredMapBase : public Base {
kpeter@696
  1066
      typedef T PredMap;
kpeter@696
  1067
      static PredMap *createPredMap(const Digraph &) { return 0; };
kpeter@697
  1068
      SetPredMapBase(const TR &b) : TR(b) {}
kpeter@696
  1069
    };
alpar@877
  1070
kpeter@697
  1071
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@697
  1072
    /// the predecessor map.
kpeter@696
  1073
    ///
kpeter@697
  1074
    /// \ref named-templ-param "Named parameter" for setting
kpeter@697
  1075
    /// the map that stores the predecessor arcs of the nodes.
kpeter@696
  1076
    template<class T>
kpeter@697
  1077
    BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
kpeter@696
  1078
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
kpeter@697
  1079
      return BellmanFordWizard<SetPredMapBase<T> >(*this);
kpeter@696
  1080
    }
alpar@877
  1081
kpeter@696
  1082
    template<class T>
kpeter@697
  1083
    struct SetDistMapBase : public Base {
kpeter@696
  1084
      typedef T DistMap;
kpeter@696
  1085
      static DistMap *createDistMap(const Digraph &) { return 0; };
kpeter@697
  1086
      SetDistMapBase(const TR &b) : TR(b) {}
kpeter@696
  1087
    };
alpar@877
  1088
kpeter@697
  1089
    /// \brief \ref named-templ-param "Named parameter" for setting
kpeter@697
  1090
    /// the distance map.
kpeter@696
  1091
    ///
kpeter@697
  1092
    /// \ref named-templ-param "Named parameter" for setting
kpeter@697
  1093
    /// the map that stores the distances of the nodes calculated
kpeter@697
  1094
    /// by the algorithm.
kpeter@696
  1095
    template<class T>
kpeter@697
  1096
    BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
kpeter@696
  1097
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
kpeter@697
  1098
      return BellmanFordWizard<SetDistMapBase<T> >(*this);
kpeter@696
  1099
    }
kpeter@696
  1100
kpeter@696
  1101
    template<class T>
kpeter@697
  1102
    struct SetPathBase : public Base {
kpeter@697
  1103
      typedef T Path;
kpeter@697
  1104
      SetPathBase(const TR &b) : TR(b) {}
kpeter@696
  1105
    };
kpeter@697
  1106
kpeter@697
  1107
    /// \brief \ref named-func-param "Named parameter" for getting
kpeter@697
  1108
    /// the shortest path to the target node.
kpeter@696
  1109
    ///
kpeter@697
  1110
    /// \ref named-func-param "Named parameter" for getting
kpeter@697
  1111
    /// the shortest path to the target node.
kpeter@697
  1112
    template<class T>
kpeter@697
  1113
    BellmanFordWizard<SetPathBase<T> > path(const T &t)
kpeter@697
  1114
    {
kpeter@697
  1115
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
kpeter@697
  1116
      return BellmanFordWizard<SetPathBase<T> >(*this);
kpeter@697
  1117
    }
kpeter@697
  1118
kpeter@697
  1119
    /// \brief \ref named-func-param "Named parameter" for getting
kpeter@697
  1120
    /// the distance of the target node.
kpeter@696
  1121
    ///
kpeter@697
  1122
    /// \ref named-func-param "Named parameter" for getting
kpeter@697
  1123
    /// the distance of the target node.
kpeter@697
  1124
    BellmanFordWizard dist(const Value &d)
kpeter@697
  1125
    {
kpeter@697
  1126
      Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
kpeter@696
  1127
      return *this;
kpeter@696
  1128
    }
alpar@877
  1129
kpeter@696
  1130
  };
alpar@877
  1131
kpeter@697
  1132
  /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
kpeter@697
  1133
  /// algorithm.
kpeter@696
  1134
  ///
kpeter@696
  1135
  /// \ingroup shortest_path
kpeter@697
  1136
  /// Function type interface for the \ref BellmanFord "Bellman-Ford"
kpeter@697
  1137
  /// algorithm.
kpeter@696
  1138
  ///
alpar@877
  1139
  /// This function also has several \ref named-templ-func-param
alpar@877
  1140
  /// "named parameters", they are declared as the members of class
kpeter@696
  1141
  /// \ref BellmanFordWizard.
kpeter@697
  1142
  /// The following examples show how to use these parameters.
kpeter@697
  1143
  /// \code
kpeter@697
  1144
  ///   // Compute shortest path from node s to each node
kpeter@697
  1145
  ///   bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
kpeter@697
  1146
  ///
kpeter@697
  1147
  ///   // Compute shortest path from s to t
kpeter@697
  1148
  ///   bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
kpeter@697
  1149
  /// \endcode
kpeter@696
  1150
  /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
kpeter@696
  1151
  /// to the end of the parameter list.
kpeter@696
  1152
  /// \sa BellmanFordWizard
kpeter@696
  1153
  /// \sa BellmanFord
kpeter@697
  1154
  template<typename GR, typename LEN>
kpeter@697
  1155
  BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
kpeter@697
  1156
  bellmanFord(const GR& digraph,
alpar@877
  1157
              const LEN& length)
kpeter@697
  1158
  {
kpeter@697
  1159
    return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
kpeter@696
  1160
  }
kpeter@696
  1161
kpeter@696
  1162
} //END OF NAMESPACE LEMON
kpeter@696
  1163
kpeter@696
  1164
#endif
kpeter@696
  1165