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