COIN-OR::LEMON - Graph Library

source: lemon/lemon/bellman_ford.h @ 870:4db8d5ccd26b

Last change on this file since 870:4db8d5ccd26b was 870:4db8d5ccd26b, checked in by Peter Kovacs <kpeter@…>, 10 years ago

Memory leak bugfix in BellmanFord? (#51)

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