lemon/bellman_ford.h
author Peter Kovacs <kpeter@inf.elte.hu>
Wed, 10 Feb 2010 19:05:20 +0100
changeset 898 75c97c3786d6
parent 835 c92296660262
child 891 75e6020b19b1
permissions -rw-r--r--
Handle graph changes in the MCF algorithms (#327)

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