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