lemon/bellman_ford.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 12 Nov 2009 23:29:42 +0100
changeset 808 9c428bb2b105
parent 788 c92296660262
child 825 75e6020b19b1
permissions -rw-r--r--
Port CostScaling from SVN -r3524 (#180)
     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 
    19 #ifndef LEMON_BELLMAN_FORD_H
    20 #define LEMON_BELLMAN_FORD_H
    21 
    22 /// \ingroup shortest_path
    23 /// \file
    24 /// \brief Bellman-Ford algorithm.
    25 
    26 #include <lemon/list_graph.h>
    27 #include <lemon/bits/path_dump.h>
    28 #include <lemon/core.h>
    29 #include <lemon/error.h>
    30 #include <lemon/maps.h>
    31 #include <lemon/path.h>
    32 
    33 #include <limits>
    34 
    35 namespace lemon {
    36 
    37   /// \brief Default OperationTraits for the BellmanFord algorithm class.
    38   ///  
    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.
    44   template <
    45     typename V, 
    46     bool has_inf = std::numeric_limits<V>::has_infinity>
    47   struct BellmanFordDefaultOperationTraits {
    48     /// \e
    49     typedef V Value;
    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     }
    62     /// \brief Gives back \c true only if the first value is less than
    63     /// the second.
    64     static bool less(const Value& left, const Value& right) {
    65       return left < right;
    66     }
    67   };
    68 
    69   template <typename V>
    70   struct BellmanFordDefaultOperationTraits<V, false> {
    71     typedef V Value;
    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.
    90   /// \param GR The type of the digraph.
    91   /// \param LEN The type of the length map.
    92   template<typename GR, typename LEN>
    93   struct BellmanFordDefaultTraits {
    94     /// The type of the digraph the algorithm runs on. 
    95     typedef GR Digraph;
    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.
   100     /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
   101     typedef LEN LengthMap;
   102 
   103     /// The type of the arc lengths.
   104     typedef typename LEN::Value Value;
   105 
   106     /// \brief Operation traits for Bellman-Ford algorithm.
   107     ///
   108     /// It defines the used operations and the infinity value for the
   109     /// given \c Value type.
   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.
   118     /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
   119     typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
   120 
   121     /// \brief Instantiates a \c PredMap.
   122     /// 
   123     /// This function instantiates a \ref PredMap. 
   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);
   128     }
   129 
   130     /// \brief The type of the map that stores the distances of the nodes.
   131     ///
   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;
   135 
   136     /// \brief Instantiates a \c DistMap.
   137     ///
   138     /// This function instantiates a \ref DistMap. 
   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);
   143     }
   144 
   145   };
   146   
   147   /// \brief %BellmanFord algorithm class.
   148   ///
   149   /// \ingroup shortest_path
   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
   161   /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any 
   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.
   164   ///
   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.
   168   ///
   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>".
   174 #ifdef DOXYGEN
   175   template <typename GR, typename LEN, typename TR>
   176 #else
   177   template <typename GR=ListDigraph,
   178             typename LEN=typename GR::template ArcMap<int>,
   179             typename TR=BellmanFordDefaultTraits<GR,LEN> >
   180 #endif
   181   class BellmanFord {
   182   public:
   183 
   184     ///The type of the underlying digraph.
   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:
   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;
   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.
   217     PredMap *_pred;
   218     // Indicates if _pred is locally allocated (true) or not.
   219     bool _local_pred;
   220     // Pointer to the map of distances.
   221     DistMap *_dist;
   222     // Indicates if _dist is locally allocated (true) or not.
   223     bool _local_dist;
   224 
   225     typedef typename Digraph::template NodeMap<bool> MaskMap;
   226     MaskMap *_mask;
   227 
   228     std::vector<Node> _process;
   229 
   230     // Creates the maps if necessary.
   231     void create_maps() {
   232       if(!_pred) {
   233 	_local_pred = true;
   234 	_pred = Traits::createPredMap(*_gr);
   235       }
   236       if(!_dist) {
   237 	_local_dist = true;
   238 	_dist = Traits::createDistMap(*_gr);
   239       }
   240       if(!_mask) {
   241         _mask = new MaskMap(*_gr);
   242       }
   243     }
   244     
   245   public :
   246  
   247     typedef BellmanFord Create;
   248 
   249     /// \name Named Template Parameters
   250 
   251     ///@{
   252 
   253     template <class T>
   254     struct SetPredMapTraits : public Traits {
   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 
   262     /// \brief \ref named-templ-param "Named parameter" for setting
   263     /// \c PredMap type.
   264     ///
   265     /// \ref named-templ-param "Named parameter" for setting
   266     /// \c PredMap type.
   267     /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
   268     template <class T>
   269     struct SetPredMap 
   270       : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
   271       typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
   272     };
   273     
   274     template <class T>
   275     struct SetDistMapTraits : public Traits {
   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 
   283     /// \brief \ref named-templ-param "Named parameter" for setting
   284     /// \c DistMap type.
   285     ///
   286     /// \ref named-templ-param "Named parameter" for setting
   287     /// \c DistMap type.
   288     /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
   289     template <class T>
   290     struct SetDistMap 
   291       : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
   292       typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
   293     };
   294 
   295     template <class T>
   296     struct SetOperationTraitsTraits : public Traits {
   297       typedef T OperationTraits;
   298     };
   299     
   300     /// \brief \ref named-templ-param "Named parameter" for setting 
   301     /// \c OperationTraits type.
   302     ///
   303     /// \ref named-templ-param "Named parameter" for setting
   304     /// \c OperationTraits type.
   305     /// For more information, see \ref BellmanFordDefaultOperationTraits.
   306     template <class T>
   307     struct SetOperationTraits
   308       : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
   309       typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
   310       Create;
   311     };
   312     
   313     ///@}
   314 
   315   protected:
   316     
   317     BellmanFord() {}
   318 
   319   public:      
   320     
   321     /// \brief Constructor.
   322     ///
   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) {}
   330     
   331     ///Destructor.
   332     ~BellmanFord() {
   333       if(_local_pred) delete _pred;
   334       if(_local_dist) delete _dist;
   335       if(_mask) delete _mask;
   336     }
   337 
   338     /// \brief Sets the length map.
   339     ///
   340     /// Sets the length map.
   341     /// \return <tt>(*this)</tt>
   342     BellmanFord &lengthMap(const LengthMap &map) {
   343       _length = &map;
   344       return *this;
   345     }
   346 
   347     /// \brief Sets the map that stores the predecessor arcs.
   348     ///
   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) {
   357 	delete _pred;
   358 	_local_pred=false;
   359       }
   360       _pred = &map;
   361       return *this;
   362     }
   363 
   364     /// \brief Sets the map that stores the distances of the nodes.
   365     ///
   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) {
   375 	delete _dist;
   376 	_local_dist=false;
   377       }
   378       _dist = &map;
   379       return *this;
   380     }
   381 
   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().
   390 
   391     ///@{
   392 
   393     /// \brief Initializes the internal data structures.
   394     /// 
   395     /// Initializes the internal data structures. The optional parameter
   396     /// is the initial distance of each node.
   397     void init(const Value value = OperationTraits::infinity()) {
   398       create_maps();
   399       for (NodeIt it(*_gr); it != INVALID; ++it) {
   400 	_pred->set(it, INVALID);
   401 	_dist->set(it, value);
   402       }
   403       _process.clear();
   404       if (OperationTraits::less(value, OperationTraits::infinity())) {
   405 	for (NodeIt it(*_gr); it != INVALID; ++it) {
   406 	  _process.push_back(it);
   407 	  _mask->set(it, true);
   408 	}
   409       } else {
   410 	for (NodeIt it(*_gr); it != INVALID; ++it) {
   411 	  _mask->set(it, false);
   412 	}
   413       }
   414     }
   415     
   416     /// \brief Adds a new source node.
   417     ///
   418     /// This function adds a new source node. The optional second parameter
   419     /// is the initial distance of the node.
   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
   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.
   436     ///
   437     /// \warning The paths with limited arc number cannot be retrieved
   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.
   442     ///
   443     /// \return \c true when the algorithm have not found more shorter
   444     /// paths.
   445     ///
   446     /// \see ActiveIt
   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) {
   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]);
   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     ///
   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
   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) {
   494 	for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
   495 	  Node target = _gr->target(it);
   496 	  Value relaxed = 
   497 	    OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
   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     ///
   514     /// Executes the algorithm.
   515     ///
   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.
   525     void start() {
   526       int num = countNodes(*_gr) - 1;
   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     ///
   534     /// Executes the algorithm and checks the negative cycles.
   535     ///
   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).
   543     /// 
   544     /// \return \c false if there is a negative cycle in the digraph.
   545     ///
   546     /// \pre init() must be called and at least one root node should be
   547     /// added with addSource() before using this function. 
   548     bool checkedStart() {
   549       int num = countNodes(*_gr);
   550       for (int i = 0; i < num; ++i) {
   551 	if (processNextWeakRound()) return true;
   552       }
   553       return _process.empty();
   554     }
   555 
   556     /// \brief Executes the algorithm with arc number limit.
   557     ///
   558     /// Executes the algorithm with arc number limit.
   559     ///
   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.
   567     ///
   568     /// \warning The paths with limited arc number cannot be retrieved
   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.
   573     ///
   574     /// \pre init() must be called and at least one root node should be
   575     /// added with addSource() before using this function. 
   576     void limitedStart(int num) {
   577       for (int i = 0; i < num; ++i) {
   578 	if (processNextRound()) break;
   579       }
   580     }
   581     
   582     /// \brief Runs the algorithm from the given root node.
   583     ///    
   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.
   586     ///
   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
   597     void run(Node s) {
   598       init();
   599       addSource(s);
   600       start();
   601     }
   602     
   603     /// \brief Runs the algorithm from the given root node with arc
   604     /// number limit.
   605     ///    
   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.
   609     ///
   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
   626     void run(Node s, int num) {
   627       init();
   628       addSource(s);
   629       limitedStart(num);
   630     }
   631     
   632     ///@}
   633 
   634     /// \brief LEMON iterator for getting the active nodes.
   635     ///
   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.
   640     class ActiveIt {
   641     public:
   642 
   643       /// \brief Constructor.
   644       ///
   645       /// Constructor for getting the active nodes of the given BellmanFord
   646       /// instance. 
   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 
   657       /// \brief Conversion to \c Node.
   658       ///
   659       /// Conversion to \c Node.
   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     };
   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     ///@{
   693 
   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]; }
   717 
   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
   727     /// tree used in \ref predNode() and \ref predMap().
   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
   742     /// tree used in \ref predArc() and \ref predMap().
   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();
   778     }
   779 
   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.
   785     lemon::Path<Digraph> negativeCycle() const {
   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     }
   808     
   809     ///@}
   810   };
   811  
   812   /// \brief Default traits class of bellmanFord() function.
   813   ///
   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>
   818   struct BellmanFordWizardDefaultTraits {
   819     /// The type of the digraph the algorithm runs on. 
   820     typedef GR Digraph;
   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.
   826     typedef LEN LengthMap;
   827 
   828     /// The type of the arc lengths.
   829     typedef typename LEN::Value Value;
   830 
   831     /// \brief Operation traits for Bellman-Ford algorithm.
   832     ///
   833     /// It defines the used operations and the infinity value for the
   834     /// given \c Value type.
   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     /// 
   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;
   844 
   845     /// \brief Instantiates a \c PredMap.
   846     /// 
   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);
   852     }
   853 
   854     /// \brief The type of the map that stores the distances of the nodes.
   855     ///
   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.
   861     ///
   862     /// This function instantiates a \ref DistMap. 
   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);
   867     }
   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;
   874   };
   875   
   876   /// \brief Default traits class used by BellmanFordWizard.
   877   ///
   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>
   882   class BellmanFordWizardBase 
   883     : public BellmanFordWizardDefaultTraits<GR, LEN> {
   884 
   885     typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
   886   protected:
   887     // Type of the nodes in the digraph.
   888     typedef typename Base::Digraph::Node Node;
   889 
   890     // Pointer to the underlying digraph.
   891     void *_graph;
   892     // Pointer to the length map
   893     void *_length;
   894     // Pointer to the map of predecessors arcs.
   895     void *_pred;
   896     // Pointer to the map of distances.
   897     void *_dist;
   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;
   902 
   903     public:
   904     /// Constructor.
   905     
   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) {}
   910 
   911     /// Constructor.
   912     
   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) {}
   922 
   923   };
   924   
   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;
   939 
   940     typedef typename TR::Digraph Digraph;
   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     
   947     typedef typename TR::LengthMap LengthMap;
   948     typedef typename LengthMap::Value Value;
   949     typedef typename TR::PredMap PredMap;
   950     typedef typename TR::DistMap DistMap;
   951     typedef typename TR::Path Path;
   952 
   953   public:
   954     /// Constructor.
   955     BellmanFordWizard() : TR() {}
   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.
   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) {}
   965 
   966     /// \brief Copy constructor
   967     BellmanFordWizard(const TR &b) : TR(b) {}
   968 
   969     ~BellmanFordWizard() {}
   970 
   971     /// \brief Runs the Bellman-Ford algorithm from the given source node.
   972     ///    
   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> 
   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));
   981       bf.run(s);
   982     }
   983 
   984     /// \brief Runs the Bellman-Ford algorithm to find the shortest path
   985     /// between \c s and \c t.
   986     ///
   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);
  1004     }
  1005 
  1006     template<class T>
  1007     struct SetPredMapBase : public Base {
  1008       typedef T PredMap;
  1009       static PredMap *createPredMap(const Digraph &) { return 0; };
  1010       SetPredMapBase(const TR &b) : TR(b) {}
  1011     };
  1012     
  1013     /// \brief \ref named-templ-param "Named parameter" for setting
  1014     /// the predecessor map.
  1015     ///
  1016     /// \ref named-templ-param "Named parameter" for setting
  1017     /// the map that stores the predecessor arcs of the nodes.
  1018     template<class T>
  1019     BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
  1020       Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
  1021       return BellmanFordWizard<SetPredMapBase<T> >(*this);
  1022     }
  1023     
  1024     template<class T>
  1025     struct SetDistMapBase : public Base {
  1026       typedef T DistMap;
  1027       static DistMap *createDistMap(const Digraph &) { return 0; };
  1028       SetDistMapBase(const TR &b) : TR(b) {}
  1029     };
  1030     
  1031     /// \brief \ref named-templ-param "Named parameter" for setting
  1032     /// the distance map.
  1033     ///
  1034     /// \ref named-templ-param "Named parameter" for setting
  1035     /// the map that stores the distances of the nodes calculated
  1036     /// by the algorithm.
  1037     template<class T>
  1038     BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
  1039       Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
  1040       return BellmanFordWizard<SetDistMapBase<T> >(*this);
  1041     }
  1042 
  1043     template<class T>
  1044     struct SetPathBase : public Base {
  1045       typedef T Path;
  1046       SetPathBase(const TR &b) : TR(b) {}
  1047     };
  1048 
  1049     /// \brief \ref named-func-param "Named parameter" for getting
  1050     /// the shortest path to the target node.
  1051     ///
  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.
  1063     ///
  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));
  1069       return *this;
  1070     }
  1071     
  1072   };
  1073   
  1074   /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
  1075   /// algorithm.
  1076   ///
  1077   /// \ingroup shortest_path
  1078   /// Function type interface for the \ref BellmanFord "Bellman-Ford"
  1079   /// algorithm.
  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.
  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
  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
  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);
  1102   }
  1103 
  1104 } //END OF NAMESPACE LEMON
  1105 
  1106 #endif
  1107