COIN-OR::LEMON - Graph Library

source: lemon/lemon/bellman_ford.h @ 960:b89e46862dc2

Last change on this file since 960:b89e46862dc2 was 960:b89e46862dc2, checked in by Alpar Juttner <alpar@…>, 10 years ago

Merge backout of a6eb9698c321 (#360,#51)

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