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