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