lemon/bellman_ford.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 12 Nov 2009 23:26:13 +0100
changeset 806 fa6f37d7a25b
parent 788 c92296660262
child 825 75e6020b19b1
permissions -rw-r--r--
Entirely rework CapacityScaling (#180)

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