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