COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/bellman_ford.h @ 902:79fab87ee483

Last change on this file since 902:79fab87ee483 was 881:b89e46862dc2, checked in by Alpar Juttner <alpar@…>, 14 years ago

Merge backout of a6eb9698c321 (#360,#51)

File size: 37.9 KB
RevLine 
[877]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
[696]2 *
[877]3 * This file is a part of LEMON, a generic C++ optimization library.
[696]4 *
[877]5 * Copyright (C) 2003-2010
[696]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
[697]19#ifndef LEMON_BELLMAN_FORD_H
20#define LEMON_BELLMAN_FORD_H
[696]21
22/// \ingroup shortest_path
23/// \file
24/// \brief Bellman-Ford algorithm.
25
[781]26#include <lemon/list_graph.h>
[696]27#include <lemon/bits/path_dump.h>
28#include <lemon/core.h>
29#include <lemon/error.h>
30#include <lemon/maps.h>
[697]31#include <lemon/path.h>
[696]32
33#include <limits>
34
35namespace lemon {
36
[879]37  /// \brief Default OperationTraits for the BellmanFord algorithm class.
[877]38  ///
[697]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.
[696]44  template <
[877]45    typename V,
[697]46    bool has_inf = std::numeric_limits<V>::has_infinity>
[696]47  struct BellmanFordDefaultOperationTraits {
[879]48    /// \e
[697]49    typedef V Value;
[696]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    }
[697]62    /// \brief Gives back \c true only if the first value is less than
63    /// the second.
[696]64    static bool less(const Value& left, const Value& right) {
65      return left < right;
66    }
67  };
68
[697]69  template <typename V>
70  struct BellmanFordDefaultOperationTraits<V, false> {
71    typedef V Value;
[696]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  };
[877]86
[696]87  /// \brief Default traits class of BellmanFord class.
88  ///
89  /// Default traits class of BellmanFord class.
[697]90  /// \param GR The type of the digraph.
91  /// \param LEN The type of the length map.
92  template<typename GR, typename LEN>
[696]93  struct BellmanFordDefaultTraits {
[877]94    /// The type of the digraph the algorithm runs on.
[697]95    typedef GR Digraph;
[696]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.
[697]100    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
101    typedef LEN LengthMap;
[696]102
[697]103    /// The type of the arc lengths.
104    typedef typename LEN::Value Value;
[696]105
106    /// \brief Operation traits for Bellman-Ford algorithm.
107    ///
[697]108    /// It defines the used operations and the infinity value for the
109    /// given \c Value type.
[879]110    /// \see BellmanFordDefaultOperationTraits
[696]111    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
[877]112
113    /// \brief The type of the map that stores the last arcs of the
[696]114    /// shortest paths.
[877]115    ///
[696]116    /// The type of the map that stores the last
117    /// arcs of the shortest paths.
[697]118    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
119    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
[696]120
[697]121    /// \brief Instantiates a \c PredMap.
[877]122    ///
123    /// This function instantiates a \ref PredMap.
[697]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);
[696]128    }
129
[697]130    /// \brief The type of the map that stores the distances of the nodes.
[696]131    ///
[697]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;
[696]135
[697]136    /// \brief Instantiates a \c DistMap.
[696]137    ///
[877]138    /// This function instantiates a \ref DistMap.
139    /// \param g is the digraph to which we would like to define the
[697]140    /// \ref DistMap.
141    static DistMap *createDistMap(const GR& g) {
142      return new DistMap(g);
[696]143    }
144
145  };
[877]146
[696]147  /// \brief %BellmanFord algorithm class.
148  ///
149  /// \ingroup shortest_path
[877]150  /// This class provides an efficient implementation of the Bellman-Ford
[697]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
[877]161  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
[697]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.
[696]164  ///
[697]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.
[696]168  ///
[697]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>".
[825]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.
[696]179#ifdef DOXYGEN
[697]180  template <typename GR, typename LEN, typename TR>
[696]181#else
[697]182  template <typename GR=ListDigraph,
183            typename LEN=typename GR::template ArcMap<int>,
184            typename TR=BellmanFordDefaultTraits<GR,LEN> >
[696]185#endif
186  class BellmanFord {
187  public:
188
189    ///The type of the underlying digraph.
[697]190    typedef typename TR::Digraph Digraph;
[877]191
[697]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:
[696]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;
[697]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.
[696]222    PredMap *_pred;
[697]223    // Indicates if _pred is locally allocated (true) or not.
224    bool _local_pred;
225    // Pointer to the map of distances.
[696]226    DistMap *_dist;
[697]227    // Indicates if _dist is locally allocated (true) or not.
228    bool _local_dist;
[696]229
230    typedef typename Digraph::template NodeMap<bool> MaskMap;
231    MaskMap *_mask;
232
233    std::vector<Node> _process;
234
[697]235    // Creates the maps if necessary.
[696]236    void create_maps() {
237      if(!_pred) {
[877]238        _local_pred = true;
239        _pred = Traits::createPredMap(*_gr);
[696]240      }
241      if(!_dist) {
[877]242        _local_dist = true;
243        _dist = Traits::createDistMap(*_gr);
[696]244      }
[804]245      if(!_mask) {
246        _mask = new MaskMap(*_gr);
247      }
[696]248    }
[877]249
[696]250  public :
[877]251
[696]252    typedef BellmanFord Create;
253
[697]254    /// \name Named Template Parameters
[696]255
256    ///@{
257
258    template <class T>
[697]259    struct SetPredMapTraits : public Traits {
[696]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
[697]267    /// \brief \ref named-templ-param "Named parameter" for setting
268    /// \c PredMap type.
[696]269    ///
[697]270    /// \ref named-templ-param "Named parameter" for setting
271    /// \c PredMap type.
272    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
[696]273    template <class T>
[877]274    struct SetPredMap
[697]275      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
276      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
[696]277    };
[877]278
[696]279    template <class T>
[697]280    struct SetDistMapTraits : public Traits {
[696]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
[697]288    /// \brief \ref named-templ-param "Named parameter" for setting
289    /// \c DistMap type.
[696]290    ///
[697]291    /// \ref named-templ-param "Named parameter" for setting
292    /// \c DistMap type.
293    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
[696]294    template <class T>
[877]295    struct SetDistMap
[697]296      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
297      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
[696]298    };
[697]299
[696]300    template <class T>
[697]301    struct SetOperationTraitsTraits : public Traits {
[696]302      typedef T OperationTraits;
303    };
[877]304
305    /// \brief \ref named-templ-param "Named parameter" for setting
[697]306    /// \c OperationTraits type.
[696]307    ///
[697]308    /// \ref named-templ-param "Named parameter" for setting
309    /// \c OperationTraits type.
[786]310    /// For more information, see \ref BellmanFordDefaultOperationTraits.
[696]311    template <class T>
312    struct SetOperationTraits
[697]313      : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
314      typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
[696]315      Create;
316    };
[877]317
[696]318    ///@}
319
320  protected:
[877]321
[696]322    BellmanFord() {}
323
[877]324  public:
325
[696]326    /// \brief Constructor.
327    ///
[697]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) {}
[877]335
[696]336    ///Destructor.
337    ~BellmanFord() {
[697]338      if(_local_pred) delete _pred;
339      if(_local_dist) delete _dist;
[696]340      if(_mask) delete _mask;
341    }
342
343    /// \brief Sets the length map.
344    ///
345    /// Sets the length map.
[697]346    /// \return <tt>(*this)</tt>
347    BellmanFord &lengthMap(const LengthMap &map) {
348      _length = &map;
[696]349      return *this;
350    }
351
[697]352    /// \brief Sets the map that stores the predecessor arcs.
[696]353    ///
[697]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) {
[877]362        delete _pred;
363        _local_pred=false;
[696]364      }
[697]365      _pred = &map;
[696]366      return *this;
367    }
368
[697]369    /// \brief Sets the map that stores the distances of the nodes.
[696]370    ///
[697]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) {
[877]380        delete _dist;
381        _local_dist=false;
[696]382      }
[697]383      _dist = &map;
[696]384      return *this;
385    }
386
[697]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().
[696]395
396    ///@{
397
398    /// \brief Initializes the internal data structures.
[877]399    ///
[697]400    /// Initializes the internal data structures. The optional parameter
401    /// is the initial distance of each node.
[696]402    void init(const Value value = OperationTraits::infinity()) {
403      create_maps();
[697]404      for (NodeIt it(*_gr); it != INVALID; ++it) {
[877]405        _pred->set(it, INVALID);
406        _dist->set(it, value);
[696]407      }
408      _process.clear();
409      if (OperationTraits::less(value, OperationTraits::infinity())) {
[877]410        for (NodeIt it(*_gr); it != INVALID; ++it) {
411          _process.push_back(it);
412          _mask->set(it, true);
413        }
[804]414      } else {
[877]415        for (NodeIt it(*_gr); it != INVALID; ++it) {
416          _mask->set(it, false);
417        }
[696]418      }
419    }
[877]420
[696]421    /// \brief Adds a new source node.
422    ///
[697]423    /// This function adds a new source node. The optional second parameter
424    /// is the initial distance of the node.
[696]425    void addSource(Node source, Value dst = OperationTraits::zero()) {
426      _dist->set(source, dst);
427      if (!(*_mask)[source]) {
[877]428        _process.push_back(source);
429        _mask->set(source, true);
[696]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
[697]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.
[696]441    ///
442    /// \warning The paths with limited arc number cannot be retrieved
[697]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.
[696]447    ///
448    /// \return \c true when the algorithm have not found more shorter
449    /// paths.
[697]450    ///
451    /// \see ActiveIt
[696]452    bool processNextRound() {
453      for (int i = 0; i < int(_process.size()); ++i) {
[877]454        _mask->set(_process[i], false);
[696]455      }
456      std::vector<Node> nextProcess;
457      std::vector<Value> values(_process.size());
458      for (int i = 0; i < int(_process.size()); ++i) {
[877]459        values[i] = (*_dist)[_process[i]];
[696]460      }
461      for (int i = 0; i < int(_process.size()); ++i) {
[877]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        }
[696]474      }
475      _process.swap(nextProcess);
476      return _process.empty();
477    }
478
479    /// \brief Executes one weak round from the Bellman-Ford algorithm.
480    ///
[697]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
[696]493    bool processNextWeakRound() {
494      for (int i = 0; i < int(_process.size()); ++i) {
[877]495        _mask->set(_process[i], false);
[696]496      }
497      std::vector<Node> nextProcess;
498      for (int i = 0; i < int(_process.size()); ++i) {
[877]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        }
[696]512      }
513      _process.swap(nextProcess);
514      return _process.empty();
515    }
516
517    /// \brief Executes the algorithm.
518    ///
[697]519    /// Executes the algorithm.
[696]520    ///
[697]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.
[696]530    void start() {
[697]531      int num = countNodes(*_gr) - 1;
[696]532      for (int i = 0; i < num; ++i) {
[877]533        if (processNextWeakRound()) break;
[696]534      }
535    }
536
537    /// \brief Executes the algorithm and checks the negative cycles.
538    ///
[697]539    /// Executes the algorithm and checks the negative cycles.
[696]540    ///
[697]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    ///
[877]545    /// The algorithm computes
[697]546    /// - the shortest path tree (forest),
547    /// - the distance of each node from the root(s).
[877]548    ///
[696]549    /// \return \c false if there is a negative cycle in the digraph.
[697]550    ///
551    /// \pre init() must be called and at least one root node should be
[877]552    /// added with addSource() before using this function.
[696]553    bool checkedStart() {
[697]554      int num = countNodes(*_gr);
[696]555      for (int i = 0; i < num; ++i) {
[877]556        if (processNextWeakRound()) return true;
[696]557      }
558      return _process.empty();
559    }
560
[697]561    /// \brief Executes the algorithm with arc number limit.
[696]562    ///
[697]563    /// Executes the algorithm with arc number limit.
[696]564    ///
[697]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.
[696]572    ///
573    /// \warning The paths with limited arc number cannot be retrieved
[697]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.
[696]578    ///
[697]579    /// \pre init() must be called and at least one root node should be
[877]580    /// added with addSource() before using this function.
[696]581    void limitedStart(int num) {
582      for (int i = 0; i < num; ++i) {
[877]583        if (processNextRound()) break;
[696]584      }
585    }
[877]586
[697]587    /// \brief Runs the algorithm from the given root node.
[877]588    ///
[697]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.
[696]591    ///
[697]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
[696]602    void run(Node s) {
603      init();
604      addSource(s);
605      start();
606    }
[877]607
[697]608    /// \brief Runs the algorithm from the given root node with arc
609    /// number limit.
[877]610    ///
[697]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.
[696]614    ///
[697]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
[696]631    void run(Node s, int num) {
632      init();
633      addSource(s);
634      limitedStart(num);
635    }
[877]636
[696]637    ///@}
638
[697]639    /// \brief LEMON iterator for getting the active nodes.
[696]640    ///
[697]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.
[696]645    class ActiveIt {
646    public:
647
648      /// \brief Constructor.
649      ///
[697]650      /// Constructor for getting the active nodes of the given BellmanFord
[877]651      /// instance.
[696]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
[697]662      /// \brief Conversion to \c Node.
[696]663      ///
[697]664      /// Conversion to \c Node.
[877]665      operator Node() const {
[696]666        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
667      }
668
669      /// \brief Increment operator.
670      ///
671      /// Increment operator.
672      ActiveIt& operator++() {
673        --_index;
[877]674        return *this;
[696]675      }
676
[877]677      bool operator==(const ActiveIt& it) const {
678        return static_cast<Node>(*this) == static_cast<Node>(it);
[696]679      }
[877]680      bool operator!=(const ActiveIt& it) const {
681        return static_cast<Node>(*this) != static_cast<Node>(it);
[696]682      }
[877]683      bool operator<(const ActiveIt& it) const {
684        return static_cast<Node>(*this) < static_cast<Node>(it);
[696]685      }
[877]686
[696]687    private:
688      const BellmanFord* _algorithm;
689      int _index;
690    };
[877]691
[697]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.
[877]696
[697]697    ///@{
[696]698
[697]699    /// \brief The shortest path to the given node.
[877]700    ///
[697]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    }
[877]711
[697]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]; }
[696]722
[697]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
[786]732    /// tree used in \ref predNode() and \ref predMap().
[697]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
[786]747    /// tree used in \ref predArc() and \ref predMap().
[697]748    ///
749    /// \pre Either \ref run() or \ref init() must be called before
750    /// using this function.
[877]751    Node predNode(Node v) const {
752      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
[697]753    }
[877]754
[697]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;}
[877]764
[697]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; }
[877]774
[697]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();
[696]783    }
784
[699]785    /// \brief Gives back a negative cycle.
[877]786    ///
[699]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.
[781]790    lemon::Path<Digraph> negativeCycle() const {
[699]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    }
[877]813
[696]814    ///@}
815  };
[877]816
[697]817  /// \brief Default traits class of bellmanFord() function.
[696]818  ///
[697]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>
[696]823  struct BellmanFordWizardDefaultTraits {
[877]824    /// The type of the digraph the algorithm runs on.
[697]825    typedef GR Digraph;
[696]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.
[697]831    typedef LEN LengthMap;
[696]832
[697]833    /// The type of the arc lengths.
834    typedef typename LEN::Value Value;
[696]835
836    /// \brief Operation traits for Bellman-Ford algorithm.
837    ///
[697]838    /// It defines the used operations and the infinity value for the
839    /// given \c Value type.
[879]840    /// \see BellmanFordDefaultOperationTraits
[696]841    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
842
843    /// \brief The type of the map that stores the last
844    /// arcs of the shortest paths.
[877]845    ///
[697]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;
[696]849
[697]850    /// \brief Instantiates a \c PredMap.
[877]851    ///
[697]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);
[696]857    }
[697]858
859    /// \brief The type of the map that stores the distances of the nodes.
[696]860    ///
[697]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.
[696]866    ///
[877]867    /// This function instantiates a \ref DistMap.
[697]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);
[696]872    }
[697]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;
[696]879  };
[877]880
[697]881  /// \brief Default traits class used by BellmanFordWizard.
[696]882  ///
[697]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>
[877]887  class BellmanFordWizardBase
[697]888    : public BellmanFordWizardDefaultTraits<GR, LEN> {
[696]889
[697]890    typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
[696]891  protected:
[697]892    // Type of the nodes in the digraph.
[696]893    typedef typename Base::Digraph::Node Node;
894
[697]895    // Pointer to the underlying digraph.
[696]896    void *_graph;
[697]897    // Pointer to the length map
[696]898    void *_length;
[697]899    // Pointer to the map of predecessors arcs.
[696]900    void *_pred;
[697]901    // Pointer to the map of distances.
[696]902    void *_dist;
[697]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;
[696]907
908    public:
909    /// Constructor.
[877]910
[697]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) {}
[696]915
916    /// Constructor.
[877]917
[697]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.
[877]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))),
[697]926      _pred(0), _dist(0), _path(0), _di(0) {}
[696]927
928  };
[877]929
[697]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.
[825]941  ///
942  /// \tparam TR The traits class that defines various types used by the
943  /// algorithm.
[697]944  template<class TR>
945  class BellmanFordWizard : public TR {
946    typedef TR Base;
[696]947
[697]948    typedef typename TR::Digraph Digraph;
[696]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;
[877]954
[697]955    typedef typename TR::LengthMap LengthMap;
[696]956    typedef typename LengthMap::Value Value;
[697]957    typedef typename TR::PredMap PredMap;
958    typedef typename TR::DistMap DistMap;
959    typedef typename TR::Path Path;
[696]960
961  public:
962    /// Constructor.
[697]963    BellmanFordWizard() : TR() {}
[696]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.
[697]969    /// \param gr The digraph the algorithm runs on.
970    /// \param len The length map.
[877]971    BellmanFordWizard(const Digraph& gr, const LengthMap& len)
[697]972      : TR(gr, len) {}
[696]973
974    /// \brief Copy constructor
[697]975    BellmanFordWizard(const TR &b) : TR(b) {}
[696]976
977    ~BellmanFordWizard() {}
978
[697]979    /// \brief Runs the Bellman-Ford algorithm from the given source node.
[877]980    ///
[697]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) {
[877]984      BellmanFord<Digraph,LengthMap,TR>
985        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
[696]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));
[697]989      bf.run(s);
[696]990    }
991
[697]992    /// \brief Runs the Bellman-Ford algorithm to find the shortest path
993    /// between \c s and \c t.
[696]994    ///
[697]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);
[696]1012    }
1013
1014    template<class T>
[697]1015    struct SetPredMapBase : public Base {
[696]1016      typedef T PredMap;
1017      static PredMap *createPredMap(const Digraph &) { return 0; };
[697]1018      SetPredMapBase(const TR &b) : TR(b) {}
[696]1019    };
[877]1020
[697]1021    /// \brief \ref named-templ-param "Named parameter" for setting
1022    /// the predecessor map.
[696]1023    ///
[697]1024    /// \ref named-templ-param "Named parameter" for setting
1025    /// the map that stores the predecessor arcs of the nodes.
[696]1026    template<class T>
[697]1027    BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
[696]1028      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
[697]1029      return BellmanFordWizard<SetPredMapBase<T> >(*this);
[696]1030    }
[877]1031
[696]1032    template<class T>
[697]1033    struct SetDistMapBase : public Base {
[696]1034      typedef T DistMap;
1035      static DistMap *createDistMap(const Digraph &) { return 0; };
[697]1036      SetDistMapBase(const TR &b) : TR(b) {}
[696]1037    };
[877]1038
[697]1039    /// \brief \ref named-templ-param "Named parameter" for setting
1040    /// the distance map.
[696]1041    ///
[697]1042    /// \ref named-templ-param "Named parameter" for setting
1043    /// the map that stores the distances of the nodes calculated
1044    /// by the algorithm.
[696]1045    template<class T>
[697]1046    BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
[696]1047      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
[697]1048      return BellmanFordWizard<SetDistMapBase<T> >(*this);
[696]1049    }
1050
1051    template<class T>
[697]1052    struct SetPathBase : public Base {
1053      typedef T Path;
1054      SetPathBase(const TR &b) : TR(b) {}
[696]1055    };
[697]1056
1057    /// \brief \ref named-func-param "Named parameter" for getting
1058    /// the shortest path to the target node.
[696]1059    ///
[697]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.
[696]1071    ///
[697]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));
[696]1077      return *this;
1078    }
[877]1079
[696]1080  };
[877]1081
[697]1082  /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1083  /// algorithm.
[696]1084  ///
1085  /// \ingroup shortest_path
[697]1086  /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1087  /// algorithm.
[696]1088  ///
[877]1089  /// This function also has several \ref named-templ-func-param
1090  /// "named parameters", they are declared as the members of class
[696]1091  /// \ref BellmanFordWizard.
[697]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
[696]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
[697]1104  template<typename GR, typename LEN>
1105  BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1106  bellmanFord(const GR& digraph,
[877]1107              const LEN& length)
[697]1108  {
1109    return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
[696]1110  }
1111
1112} //END OF NAMESPACE LEMON
1113
1114#endif
1115
Note: See TracBrowser for help on using the repository browser.