COIN-OR::LEMON - Graph Library

source: lemon/lemon/bellman_ford.h @ 1250:97d978243703

Last change on this file since 1250:97d978243703 was 1250:97d978243703, checked in by Alpar Juttner <alpar@…>, 11 years ago

Fix unresolved doc references (#459)

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