kpeter@696: /* -*- C++ -*- kpeter@696: * kpeter@696: * This file is a part of LEMON, a generic C++ optimization library kpeter@696: * kpeter@696: * Copyright (C) 2003-2008 kpeter@696: * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport kpeter@696: * (Egervary Research Group on Combinatorial Optimization, EGRES). kpeter@696: * kpeter@696: * Permission to use, modify and distribute this software is granted kpeter@696: * provided that this copyright notice appears in all copies. For kpeter@696: * precise terms see the accompanying LICENSE file. kpeter@696: * kpeter@696: * This software is provided "AS IS" with no warranty of any kind, kpeter@696: * express or implied, and with no claim as to its suitability for any kpeter@696: * purpose. kpeter@696: * kpeter@696: */ kpeter@696: kpeter@696: #ifndef LEMON_BELMANN_FORD_H kpeter@696: #define LEMON_BELMANN_FORD_H kpeter@696: kpeter@696: /// \ingroup shortest_path kpeter@696: /// \file kpeter@696: /// \brief Bellman-Ford algorithm. kpeter@696: /// kpeter@696: kpeter@696: #include kpeter@696: #include kpeter@696: #include kpeter@696: #include kpeter@696: kpeter@696: #include kpeter@696: kpeter@696: namespace lemon { kpeter@696: kpeter@696: /// \brief Default OperationTraits for the BellmanFord algorithm class. kpeter@696: /// kpeter@696: /// It defines all computational operations and constants which are kpeter@696: /// used in the Bellman-Ford algorithm. The default implementation kpeter@696: /// is based on the numeric_limits class. If the numeric type does not kpeter@696: /// have infinity value then the maximum value is used as extremal kpeter@696: /// infinity value. kpeter@696: template < kpeter@696: typename Value, kpeter@696: bool has_infinity = std::numeric_limits::has_infinity> kpeter@696: struct BellmanFordDefaultOperationTraits { kpeter@696: /// \brief Gives back the zero value of the type. kpeter@696: static Value zero() { kpeter@696: return static_cast(0); kpeter@696: } kpeter@696: /// \brief Gives back the positive infinity value of the type. kpeter@696: static Value infinity() { kpeter@696: return std::numeric_limits::infinity(); kpeter@696: } kpeter@696: /// \brief Gives back the sum of the given two elements. kpeter@696: static Value plus(const Value& left, const Value& right) { kpeter@696: return left + right; kpeter@696: } kpeter@696: /// \brief Gives back true only if the first value less than the second. kpeter@696: static bool less(const Value& left, const Value& right) { kpeter@696: return left < right; kpeter@696: } kpeter@696: }; kpeter@696: kpeter@696: template kpeter@696: struct BellmanFordDefaultOperationTraits { kpeter@696: static Value zero() { kpeter@696: return static_cast(0); kpeter@696: } kpeter@696: static Value infinity() { kpeter@696: return std::numeric_limits::max(); kpeter@696: } kpeter@696: static Value plus(const Value& left, const Value& right) { kpeter@696: if (left == infinity() || right == infinity()) return infinity(); kpeter@696: return left + right; kpeter@696: } kpeter@696: static bool less(const Value& left, const Value& right) { kpeter@696: return left < right; kpeter@696: } kpeter@696: }; kpeter@696: kpeter@696: /// \brief Default traits class of BellmanFord class. kpeter@696: /// kpeter@696: /// Default traits class of BellmanFord class. kpeter@696: /// \param _Digraph Digraph type. kpeter@696: /// \param _LegthMap Type of length map. kpeter@696: template kpeter@696: struct BellmanFordDefaultTraits { kpeter@696: /// The digraph type the algorithm runs on. kpeter@696: typedef _Digraph Digraph; kpeter@696: kpeter@696: /// \brief The type of the map that stores the arc lengths. kpeter@696: /// kpeter@696: /// The type of the map that stores the arc lengths. kpeter@696: /// It must meet the \ref concepts::ReadMap "ReadMap" concept. kpeter@696: typedef _LengthMap LengthMap; kpeter@696: kpeter@696: // The type of the length of the arcs. kpeter@696: typedef typename _LengthMap::Value Value; kpeter@696: kpeter@696: /// \brief Operation traits for Bellman-Ford algorithm. kpeter@696: /// kpeter@696: /// It defines the infinity type on the given Value type kpeter@696: /// and the used operation. kpeter@696: /// \see BellmanFordDefaultOperationTraits kpeter@696: typedef BellmanFordDefaultOperationTraits OperationTraits; kpeter@696: kpeter@696: /// \brief The type of the map that stores the last arcs of the kpeter@696: /// shortest paths. kpeter@696: /// kpeter@696: /// The type of the map that stores the last kpeter@696: /// arcs of the shortest paths. kpeter@696: /// It must meet the \ref concepts::WriteMap "WriteMap" concept. kpeter@696: /// kpeter@696: typedef typename Digraph::template NodeMap PredMap; kpeter@696: kpeter@696: /// \brief Instantiates a PredMap. kpeter@696: /// kpeter@696: /// This function instantiates a \ref PredMap. kpeter@696: /// \param digraph is the digraph, to which we would like to define the PredMap. kpeter@696: static PredMap *createPredMap(const _Digraph& digraph) { kpeter@696: return new PredMap(digraph); kpeter@696: } kpeter@696: kpeter@696: /// \brief The type of the map that stores the dists of the nodes. kpeter@696: /// kpeter@696: /// The type of the map that stores the dists of the nodes. kpeter@696: /// It must meet the \ref concepts::WriteMap "WriteMap" concept. kpeter@696: /// kpeter@696: typedef typename Digraph::template NodeMap kpeter@696: DistMap; kpeter@696: kpeter@696: /// \brief Instantiates a DistMap. kpeter@696: /// kpeter@696: /// This function instantiates a \ref DistMap. kpeter@696: /// \param digraph is the digraph, to which we would like to define the kpeter@696: /// \ref DistMap kpeter@696: static DistMap *createDistMap(const _Digraph& digraph) { kpeter@696: return new DistMap(digraph); kpeter@696: } kpeter@696: kpeter@696: }; kpeter@696: kpeter@696: /// \brief %BellmanFord algorithm class. kpeter@696: /// kpeter@696: /// \ingroup shortest_path kpeter@696: /// This class provides an efficient implementation of \c Bellman-Ford kpeter@696: /// algorithm. The arc lengths are passed to the algorithm using a kpeter@696: /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any kpeter@696: /// kind of length. kpeter@696: /// kpeter@696: /// The Bellman-Ford algorithm solves the shortest path from one node kpeter@696: /// problem when the arcs can have negative length but the digraph should kpeter@696: /// not contain cycles with negative sum of length. If we can assume kpeter@696: /// that all arc is non-negative in the digraph then the dijkstra algorithm kpeter@696: /// should be used rather. kpeter@696: /// kpeter@696: /// The maximal time complexity of the algorithm is \f$ O(ne) \f$. kpeter@696: /// kpeter@696: /// The type of the length is determined by the kpeter@696: /// \ref concepts::ReadMap::Value "Value" of the length map. kpeter@696: /// kpeter@696: /// \param _Digraph The digraph type the algorithm runs on. The default value kpeter@696: /// is \ref ListDigraph. The value of _Digraph is not used directly by kpeter@696: /// BellmanFord, it is only passed to \ref BellmanFordDefaultTraits. kpeter@696: /// \param _LengthMap This read-only ArcMap determines the lengths of the kpeter@696: /// arcs. The default map type is \ref concepts::Digraph::ArcMap kpeter@696: /// "Digraph::ArcMap". The value of _LengthMap is not used directly kpeter@696: /// by BellmanFord, it is only passed to \ref BellmanFordDefaultTraits. kpeter@696: /// \param _Traits Traits class to set various data types used by the kpeter@696: /// algorithm. The default traits class is \ref BellmanFordDefaultTraits kpeter@696: /// "BellmanFordDefaultTraits<_Digraph,_LengthMap>". See \ref kpeter@696: /// BellmanFordDefaultTraits for the documentation of a BellmanFord traits kpeter@696: /// class. kpeter@696: #ifdef DOXYGEN kpeter@696: template kpeter@696: #else kpeter@696: template , kpeter@696: typename _Traits=BellmanFordDefaultTraits<_Digraph,_LengthMap> > kpeter@696: #endif kpeter@696: class BellmanFord { kpeter@696: public: kpeter@696: kpeter@696: typedef _Traits Traits; kpeter@696: ///The type of the underlying digraph. kpeter@696: typedef typename _Traits::Digraph Digraph; kpeter@696: kpeter@696: typedef typename Digraph::Node Node; kpeter@696: typedef typename Digraph::NodeIt NodeIt; kpeter@696: typedef typename Digraph::Arc Arc; kpeter@696: typedef typename Digraph::OutArcIt OutArcIt; kpeter@696: kpeter@696: /// \brief The type of the length of the arcs. kpeter@696: typedef typename _Traits::LengthMap::Value Value; kpeter@696: /// \brief The type of the map that stores the arc lengths. kpeter@696: typedef typename _Traits::LengthMap LengthMap; kpeter@696: /// \brief The type of the map that stores the last kpeter@696: /// arcs of the shortest paths. kpeter@696: typedef typename _Traits::PredMap PredMap; kpeter@696: /// \brief The type of the map that stores the dists of the nodes. kpeter@696: typedef typename _Traits::DistMap DistMap; kpeter@696: /// \brief The operation traits. kpeter@696: typedef typename _Traits::OperationTraits OperationTraits; kpeter@696: private: kpeter@696: /// Pointer to the underlying digraph. kpeter@696: const Digraph *digraph; kpeter@696: /// Pointer to the length map kpeter@696: const LengthMap *length; kpeter@696: ///Pointer to the map of predecessors arcs. kpeter@696: PredMap *_pred; kpeter@696: ///Indicates if \ref _pred is locally allocated (\c true) or not. kpeter@696: bool local_pred; kpeter@696: ///Pointer to the map of distances. kpeter@696: DistMap *_dist; kpeter@696: ///Indicates if \ref _dist is locally allocated (\c true) or not. kpeter@696: bool local_dist; kpeter@696: kpeter@696: typedef typename Digraph::template NodeMap MaskMap; kpeter@696: MaskMap *_mask; kpeter@696: kpeter@696: std::vector _process; kpeter@696: kpeter@696: /// Creates the maps if necessary. kpeter@696: void create_maps() { kpeter@696: if(!_pred) { kpeter@696: local_pred = true; kpeter@696: _pred = Traits::createPredMap(*digraph); kpeter@696: } kpeter@696: if(!_dist) { kpeter@696: local_dist = true; kpeter@696: _dist = Traits::createDistMap(*digraph); kpeter@696: } kpeter@696: _mask = new MaskMap(*digraph, false); kpeter@696: } kpeter@696: kpeter@696: public : kpeter@696: kpeter@696: typedef BellmanFord Create; kpeter@696: kpeter@696: /// \name Named template parameters kpeter@696: kpeter@696: ///@{ kpeter@696: kpeter@696: template kpeter@696: struct DefPredMapTraits : public Traits { kpeter@696: typedef T PredMap; kpeter@696: static PredMap *createPredMap(const Digraph&) { kpeter@696: LEMON_ASSERT(false, "PredMap is not initialized"); kpeter@696: return 0; // ignore warnings kpeter@696: } kpeter@696: }; kpeter@696: kpeter@696: /// \brief \ref named-templ-param "Named parameter" for setting PredMap kpeter@696: /// type kpeter@696: /// \ref named-templ-param "Named parameter" for setting PredMap type kpeter@696: /// kpeter@696: template kpeter@696: struct SetPredMap kpeter@696: : public BellmanFord< Digraph, LengthMap, DefPredMapTraits > { kpeter@696: typedef BellmanFord< Digraph, LengthMap, DefPredMapTraits > Create; kpeter@696: }; kpeter@696: kpeter@696: template kpeter@696: struct DefDistMapTraits : public Traits { kpeter@696: typedef T DistMap; kpeter@696: static DistMap *createDistMap(const Digraph&) { kpeter@696: LEMON_ASSERT(false, "DistMap is not initialized"); kpeter@696: return 0; // ignore warnings kpeter@696: } kpeter@696: }; kpeter@696: kpeter@696: /// \brief \ref named-templ-param "Named parameter" for setting DistMap kpeter@696: /// type kpeter@696: /// kpeter@696: /// \ref named-templ-param "Named parameter" for setting DistMap type kpeter@696: /// kpeter@696: template kpeter@696: struct SetDistMap kpeter@696: : public BellmanFord< Digraph, LengthMap, DefDistMapTraits > { kpeter@696: typedef BellmanFord< Digraph, LengthMap, DefDistMapTraits > Create; kpeter@696: }; kpeter@696: kpeter@696: template kpeter@696: struct DefOperationTraitsTraits : public Traits { kpeter@696: typedef T OperationTraits; kpeter@696: }; kpeter@696: kpeter@696: /// \brief \ref named-templ-param "Named parameter" for setting kpeter@696: /// OperationTraits type kpeter@696: /// kpeter@696: /// \ref named-templ-param "Named parameter" for setting OperationTraits kpeter@696: /// type kpeter@696: template kpeter@696: struct SetOperationTraits kpeter@696: : public BellmanFord< Digraph, LengthMap, DefOperationTraitsTraits > { kpeter@696: typedef BellmanFord< Digraph, LengthMap, DefOperationTraitsTraits > kpeter@696: Create; kpeter@696: }; kpeter@696: kpeter@696: ///@} kpeter@696: kpeter@696: protected: kpeter@696: kpeter@696: BellmanFord() {} kpeter@696: kpeter@696: public: kpeter@696: kpeter@696: /// \brief Constructor. kpeter@696: /// kpeter@696: /// \param _graph the digraph the algorithm will run on. kpeter@696: /// \param _length the length map used by the algorithm. kpeter@696: BellmanFord(const Digraph& _graph, const LengthMap& _length) : kpeter@696: digraph(&_graph), length(&_length), kpeter@696: _pred(0), local_pred(false), kpeter@696: _dist(0), local_dist(false), _mask(0) {} kpeter@696: kpeter@696: ///Destructor. kpeter@696: ~BellmanFord() { kpeter@696: if(local_pred) delete _pred; kpeter@696: if(local_dist) delete _dist; kpeter@696: if(_mask) delete _mask; kpeter@696: } kpeter@696: kpeter@696: /// \brief Sets the length map. kpeter@696: /// kpeter@696: /// Sets the length map. kpeter@696: /// \return \c (*this) kpeter@696: BellmanFord &lengthMap(const LengthMap &m) { kpeter@696: length = &m; kpeter@696: return *this; kpeter@696: } kpeter@696: kpeter@696: /// \brief Sets the map storing the predecessor arcs. kpeter@696: /// kpeter@696: /// Sets the map storing the predecessor arcs. kpeter@696: /// If you don't use this function before calling \ref run(), kpeter@696: /// it will allocate one. The destuctor deallocates this kpeter@696: /// automatically allocated map, of course. kpeter@696: /// \return \c (*this) kpeter@696: BellmanFord &predMap(PredMap &m) { kpeter@696: if(local_pred) { kpeter@696: delete _pred; kpeter@696: local_pred=false; kpeter@696: } kpeter@696: _pred = &m; kpeter@696: return *this; kpeter@696: } kpeter@696: kpeter@696: /// \brief Sets the map storing the distances calculated by the algorithm. kpeter@696: /// kpeter@696: /// Sets the map storing the distances calculated by the algorithm. kpeter@696: /// If you don't use this function before calling \ref run(), kpeter@696: /// it will allocate one. The destuctor deallocates this kpeter@696: /// automatically allocated map, of course. kpeter@696: /// \return \c (*this) kpeter@696: BellmanFord &distMap(DistMap &m) { kpeter@696: if(local_dist) { kpeter@696: delete _dist; kpeter@696: local_dist=false; kpeter@696: } kpeter@696: _dist = &m; kpeter@696: return *this; kpeter@696: } kpeter@696: kpeter@696: /// \name Execution control kpeter@696: /// The simplest way to execute the algorithm is to use kpeter@696: /// one of the member functions called \c run(...). kpeter@696: /// \n kpeter@696: /// If you need more control on the execution, kpeter@696: /// first you must call \ref init(), then you can add several source nodes kpeter@696: /// with \ref addSource(). kpeter@696: /// Finally \ref start() will perform the actual path kpeter@696: /// computation. kpeter@696: kpeter@696: ///@{ kpeter@696: kpeter@696: /// \brief Initializes the internal data structures. kpeter@696: /// kpeter@696: /// Initializes the internal data structures. kpeter@696: void init(const Value value = OperationTraits::infinity()) { kpeter@696: create_maps(); kpeter@696: for (NodeIt it(*digraph); it != INVALID; ++it) { kpeter@696: _pred->set(it, INVALID); kpeter@696: _dist->set(it, value); kpeter@696: } kpeter@696: _process.clear(); kpeter@696: if (OperationTraits::less(value, OperationTraits::infinity())) { kpeter@696: for (NodeIt it(*digraph); it != INVALID; ++it) { kpeter@696: _process.push_back(it); kpeter@696: _mask->set(it, true); kpeter@696: } kpeter@696: } kpeter@696: } kpeter@696: kpeter@696: /// \brief Adds a new source node. kpeter@696: /// kpeter@696: /// Adds a new source node. The optional second parameter is the kpeter@696: /// initial distance of the node. It just sets the distance of the kpeter@696: /// node to the given value. kpeter@696: void addSource(Node source, Value dst = OperationTraits::zero()) { kpeter@696: _dist->set(source, dst); kpeter@696: if (!(*_mask)[source]) { kpeter@696: _process.push_back(source); kpeter@696: _mask->set(source, true); kpeter@696: } kpeter@696: } kpeter@696: kpeter@696: /// \brief Executes one round from the Bellman-Ford algorithm. kpeter@696: /// kpeter@696: /// If the algoritm calculated the distances in the previous round kpeter@696: /// exactly for all at most \f$ k \f$ length path lengths then it will kpeter@696: /// calculate the distances exactly for all at most \f$ k + 1 \f$ kpeter@696: /// length path lengths. With \f$ k \f$ iteration this function kpeter@696: /// calculates the at most \f$ k \f$ length path lengths. kpeter@696: /// kpeter@696: /// \warning The paths with limited arc number cannot be retrieved kpeter@696: /// easily with \ref path() or \ref predArc() functions. If you kpeter@696: /// need the shortest path and not just the distance you should store kpeter@696: /// after each iteration the \ref predMap() map and manually build kpeter@696: /// the path. kpeter@696: /// kpeter@696: /// \return \c true when the algorithm have not found more shorter kpeter@696: /// paths. kpeter@696: bool processNextRound() { kpeter@696: for (int i = 0; i < int(_process.size()); ++i) { kpeter@696: _mask->set(_process[i], false); kpeter@696: } kpeter@696: std::vector nextProcess; kpeter@696: std::vector values(_process.size()); kpeter@696: for (int i = 0; i < int(_process.size()); ++i) { kpeter@696: values[i] = (*_dist)[_process[i]]; kpeter@696: } kpeter@696: for (int i = 0; i < int(_process.size()); ++i) { kpeter@696: for (OutArcIt it(*digraph, _process[i]); it != INVALID; ++it) { kpeter@696: Node target = digraph->target(it); kpeter@696: Value relaxed = OperationTraits::plus(values[i], (*length)[it]); kpeter@696: if (OperationTraits::less(relaxed, (*_dist)[target])) { kpeter@696: _pred->set(target, it); kpeter@696: _dist->set(target, relaxed); kpeter@696: if (!(*_mask)[target]) { kpeter@696: _mask->set(target, true); kpeter@696: nextProcess.push_back(target); kpeter@696: } kpeter@696: } kpeter@696: } kpeter@696: } kpeter@696: _process.swap(nextProcess); kpeter@696: return _process.empty(); kpeter@696: } kpeter@696: kpeter@696: /// \brief Executes one weak round from the Bellman-Ford algorithm. kpeter@696: /// kpeter@696: /// If the algorithm calculated the distances in the kpeter@696: /// previous round at least for all at most k length paths then it will kpeter@696: /// calculate the distances at least for all at most k + 1 length paths. kpeter@696: /// This function does not make it possible to calculate strictly the kpeter@696: /// at most k length minimal paths, this is why it is kpeter@696: /// called just weak round. kpeter@696: /// \return \c true when the algorithm have not found more shorter paths. kpeter@696: bool processNextWeakRound() { kpeter@696: for (int i = 0; i < int(_process.size()); ++i) { kpeter@696: _mask->set(_process[i], false); kpeter@696: } kpeter@696: std::vector nextProcess; kpeter@696: for (int i = 0; i < int(_process.size()); ++i) { kpeter@696: for (OutArcIt it(*digraph, _process[i]); it != INVALID; ++it) { kpeter@696: Node target = digraph->target(it); kpeter@696: Value relaxed = kpeter@696: OperationTraits::plus((*_dist)[_process[i]], (*length)[it]); kpeter@696: if (OperationTraits::less(relaxed, (*_dist)[target])) { kpeter@696: _pred->set(target, it); kpeter@696: _dist->set(target, relaxed); kpeter@696: if (!(*_mask)[target]) { kpeter@696: _mask->set(target, true); kpeter@696: nextProcess.push_back(target); kpeter@696: } kpeter@696: } kpeter@696: } kpeter@696: } kpeter@696: _process.swap(nextProcess); kpeter@696: return _process.empty(); kpeter@696: } kpeter@696: kpeter@696: /// \brief Executes the algorithm. kpeter@696: /// kpeter@696: /// \pre init() must be called and at least one node should be added kpeter@696: /// with addSource() before using this function. kpeter@696: /// kpeter@696: /// This method runs the %BellmanFord algorithm from the root node(s) kpeter@696: /// in order to compute the shortest path to each node. The algorithm kpeter@696: /// computes kpeter@696: /// - The shortest path tree. kpeter@696: /// - The distance of each node from the root(s). kpeter@696: void start() { kpeter@696: int num = countNodes(*digraph) - 1; kpeter@696: for (int i = 0; i < num; ++i) { kpeter@696: if (processNextWeakRound()) break; kpeter@696: } kpeter@696: } kpeter@696: kpeter@696: /// \brief Executes the algorithm and checks the negative cycles. kpeter@696: /// kpeter@696: /// \pre init() must be called and at least one node should be added kpeter@696: /// with addSource() before using this function. kpeter@696: /// kpeter@696: /// This method runs the %BellmanFord algorithm from the root node(s) kpeter@696: /// in order to compute the shortest path to each node. The algorithm kpeter@696: /// computes kpeter@696: /// - The shortest path tree. kpeter@696: /// - The distance of each node from the root(s). kpeter@696: /// kpeter@696: /// \return \c false if there is a negative cycle in the digraph. kpeter@696: bool checkedStart() { kpeter@696: int num = countNodes(*digraph); kpeter@696: for (int i = 0; i < num; ++i) { kpeter@696: if (processNextWeakRound()) return true; kpeter@696: } kpeter@696: return _process.empty(); kpeter@696: } kpeter@696: kpeter@696: /// \brief Executes the algorithm with path length limit. kpeter@696: /// kpeter@696: /// \pre init() must be called and at least one node should be added kpeter@696: /// with addSource() before using this function. kpeter@696: /// kpeter@696: /// This method runs the %BellmanFord algorithm from the root kpeter@696: /// node(s) in order to compute the shortest path lengths with at kpeter@696: /// most \c num arc. kpeter@696: /// kpeter@696: /// \warning The paths with limited arc number cannot be retrieved kpeter@696: /// easily with \ref path() or \ref predArc() functions. If you kpeter@696: /// need the shortest path and not just the distance you should store kpeter@696: /// after each iteration the \ref predMap() map and manually build kpeter@696: /// the path. kpeter@696: /// kpeter@696: /// The algorithm computes kpeter@696: /// - The predecessor arc from each node. kpeter@696: /// - The limited distance of each node from the root(s). kpeter@696: void limitedStart(int num) { kpeter@696: for (int i = 0; i < num; ++i) { kpeter@696: if (processNextRound()) break; kpeter@696: } kpeter@696: } kpeter@696: kpeter@696: /// \brief Runs %BellmanFord algorithm from node \c s. kpeter@696: /// kpeter@696: /// This method runs the %BellmanFord algorithm from a root node \c s kpeter@696: /// in order to compute the shortest path to each node. The algorithm kpeter@696: /// computes kpeter@696: /// - The shortest path tree. kpeter@696: /// - The distance of each node from the root. kpeter@696: /// kpeter@696: /// \note d.run(s) is just a shortcut of the following code. kpeter@696: ///\code kpeter@696: /// d.init(); kpeter@696: /// d.addSource(s); kpeter@696: /// d.start(); kpeter@696: ///\endcode kpeter@696: void run(Node s) { kpeter@696: init(); kpeter@696: addSource(s); kpeter@696: start(); kpeter@696: } kpeter@696: kpeter@696: /// \brief Runs %BellmanFord algorithm with limited path length kpeter@696: /// from node \c s. kpeter@696: /// kpeter@696: /// This method runs the %BellmanFord algorithm from a root node \c s kpeter@696: /// in order to compute the shortest path with at most \c len arcs kpeter@696: /// to each node. The algorithm computes kpeter@696: /// - The shortest path tree. kpeter@696: /// - The distance of each node from the root. kpeter@696: /// kpeter@696: /// \note d.run(s, num) is just a shortcut of the following code. kpeter@696: ///\code kpeter@696: /// d.init(); kpeter@696: /// d.addSource(s); kpeter@696: /// d.limitedStart(num); kpeter@696: ///\endcode kpeter@696: void run(Node s, int num) { kpeter@696: init(); kpeter@696: addSource(s); kpeter@696: limitedStart(num); kpeter@696: } kpeter@696: kpeter@696: ///@} kpeter@696: kpeter@696: /// \name Query Functions kpeter@696: /// The result of the %BellmanFord algorithm can be obtained using these kpeter@696: /// functions.\n kpeter@696: /// Before the use of these functions, kpeter@696: /// either run() or start() must be called. kpeter@696: kpeter@696: ///@{ kpeter@696: kpeter@696: /// \brief Lemon iterator for get the active nodes. kpeter@696: /// kpeter@696: /// Lemon iterator for get the active nodes. This class provides a kpeter@696: /// common style lemon iterator which gives back a subset of the kpeter@696: /// nodes. The iterated nodes are active in the algorithm after kpeter@696: /// the last phase so these should be checked in the next phase to kpeter@696: /// find augmenting arcs from these. kpeter@696: class ActiveIt { kpeter@696: public: kpeter@696: kpeter@696: /// \brief Constructor. kpeter@696: /// kpeter@696: /// Constructor for get the nodeset of the variable. kpeter@696: ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm) kpeter@696: { kpeter@696: _index = _algorithm->_process.size() - 1; kpeter@696: } kpeter@696: kpeter@696: /// \brief Invalid constructor. kpeter@696: /// kpeter@696: /// Invalid constructor. kpeter@696: ActiveIt(Invalid) : _algorithm(0), _index(-1) {} kpeter@696: kpeter@696: /// \brief Conversion to node. kpeter@696: /// kpeter@696: /// Conversion to node. kpeter@696: operator Node() const { kpeter@696: return _index >= 0 ? _algorithm->_process[_index] : INVALID; kpeter@696: } kpeter@696: kpeter@696: /// \brief Increment operator. kpeter@696: /// kpeter@696: /// Increment operator. kpeter@696: ActiveIt& operator++() { kpeter@696: --_index; kpeter@696: return *this; kpeter@696: } kpeter@696: kpeter@696: bool operator==(const ActiveIt& it) const { kpeter@696: return static_cast(*this) == static_cast(it); kpeter@696: } kpeter@696: bool operator!=(const ActiveIt& it) const { kpeter@696: return static_cast(*this) != static_cast(it); kpeter@696: } kpeter@696: bool operator<(const ActiveIt& it) const { kpeter@696: return static_cast(*this) < static_cast(it); kpeter@696: } kpeter@696: kpeter@696: private: kpeter@696: const BellmanFord* _algorithm; kpeter@696: int _index; kpeter@696: }; kpeter@696: kpeter@696: typedef PredMapPath Path; kpeter@696: kpeter@696: /// \brief Gives back the shortest path. kpeter@696: /// kpeter@696: /// Gives back the shortest path. kpeter@696: /// \pre The \c t should be reachable from the source. kpeter@696: Path path(Node t) kpeter@696: { kpeter@696: return Path(*digraph, *_pred, t); kpeter@696: } kpeter@696: kpeter@696: kpeter@696: // TODO : implement negative cycle kpeter@696: // /// \brief Gives back a negative cycle. kpeter@696: // /// kpeter@696: // /// This function gives back a negative cycle. kpeter@696: // /// If the algorithm have not found yet negative cycle it will give back kpeter@696: // /// an empty path. kpeter@696: // Path negativeCycle() { kpeter@696: // typename Digraph::template NodeMap state(*digraph, 0); kpeter@696: // for (ActiveIt it(*this); it != INVALID; ++it) { kpeter@696: // if (state[it] == 0) { kpeter@696: // for (Node t = it; predArc(t) != INVALID; t = predNode(t)) { kpeter@696: // if (state[t] == 0) { kpeter@696: // state[t] = 1; kpeter@696: // } else if (state[t] == 2) { kpeter@696: // break; kpeter@696: // } else { kpeter@696: // p.clear(); kpeter@696: // typename Path::Builder b(p); kpeter@696: // b.setStartNode(t); kpeter@696: // b.pushFront(predArc(t)); kpeter@696: // for(Node s = predNode(t); s != t; s = predNode(s)) { kpeter@696: // b.pushFront(predArc(s)); kpeter@696: // } kpeter@696: // b.commit(); kpeter@696: // return true; kpeter@696: // } kpeter@696: // } kpeter@696: // for (Node t = it; predArc(t) != INVALID; t = predNode(t)) { kpeter@696: // if (state[t] == 1) { kpeter@696: // state[t] = 2; kpeter@696: // } else { kpeter@696: // break; kpeter@696: // } kpeter@696: // } kpeter@696: // } kpeter@696: // } kpeter@696: // return false; kpeter@696: // } kpeter@696: kpeter@696: /// \brief The distance of a node from the root. kpeter@696: /// kpeter@696: /// Returns the distance of a node from the root. kpeter@696: /// \pre \ref run() must be called before using this function. kpeter@696: /// \warning If node \c v in unreachable from the root the return value kpeter@696: /// of this funcion is undefined. kpeter@696: Value dist(Node v) const { return (*_dist)[v]; } kpeter@696: kpeter@696: /// \brief Returns the 'previous arc' of the shortest path tree. kpeter@696: /// kpeter@696: /// For a node \c v it returns the 'previous arc' of the shortest path kpeter@696: /// tree, i.e. it returns the last arc of a shortest path from the root kpeter@696: /// to \c v. It is \ref INVALID if \c v is unreachable from the root or kpeter@696: /// if \c v=s. The shortest path tree used here is equal to the shortest kpeter@696: /// path tree used in \ref predNode(). kpeter@696: /// \pre \ref run() must be called before using kpeter@696: /// this function. kpeter@696: Arc predArc(Node v) const { return (*_pred)[v]; } kpeter@696: kpeter@696: /// \brief Returns the 'previous node' of the shortest path tree. kpeter@696: /// kpeter@696: /// For a node \c v it returns the 'previous node' of the shortest path kpeter@696: /// tree, i.e. it returns the last but one node from a shortest path from kpeter@696: /// the root to \c /v. It is INVALID if \c v is unreachable from the root kpeter@696: /// or if \c v=s. The shortest path tree used here is equal to the kpeter@696: /// shortest path tree used in \ref predArc(). \pre \ref run() must be kpeter@696: /// called before using this function. kpeter@696: Node predNode(Node v) const { kpeter@696: return (*_pred)[v] == INVALID ? INVALID : digraph->source((*_pred)[v]); kpeter@696: } kpeter@696: kpeter@696: /// \brief Returns a reference to the NodeMap of distances. kpeter@696: /// kpeter@696: /// Returns a reference to the NodeMap of distances. \pre \ref run() must kpeter@696: /// be called before using this function. kpeter@696: const DistMap &distMap() const { return *_dist;} kpeter@696: kpeter@696: /// \brief Returns a reference to the shortest path tree map. kpeter@696: /// kpeter@696: /// Returns a reference to the NodeMap of the arcs of the kpeter@696: /// shortest path tree. kpeter@696: /// \pre \ref run() must be called before using this function. kpeter@696: const PredMap &predMap() const { return *_pred; } kpeter@696: kpeter@696: /// \brief Checks if a node is reachable from the root. kpeter@696: /// kpeter@696: /// Returns \c true if \c v is reachable from the root. kpeter@696: /// \pre \ref run() must be called before using this function. kpeter@696: /// kpeter@696: bool reached(Node v) { return (*_dist)[v] != OperationTraits::infinity(); } kpeter@696: kpeter@696: ///@} kpeter@696: }; kpeter@696: kpeter@696: /// \brief Default traits class of BellmanFord function. kpeter@696: /// kpeter@696: /// Default traits class of BellmanFord function. kpeter@696: /// \param _Digraph Digraph type. kpeter@696: /// \param _LengthMap Type of length map. kpeter@696: template kpeter@696: struct BellmanFordWizardDefaultTraits { kpeter@696: /// \brief The digraph type the algorithm runs on. kpeter@696: typedef _Digraph Digraph; kpeter@696: kpeter@696: /// \brief The type of the map that stores the arc lengths. kpeter@696: /// kpeter@696: /// The type of the map that stores the arc lengths. kpeter@696: /// It must meet the \ref concepts::ReadMap "ReadMap" concept. kpeter@696: typedef _LengthMap LengthMap; kpeter@696: kpeter@696: /// \brief The value type of the length map. kpeter@696: typedef typename _LengthMap::Value Value; kpeter@696: kpeter@696: /// \brief Operation traits for Bellman-Ford algorithm. kpeter@696: /// kpeter@696: /// It defines the infinity type on the given Value type kpeter@696: /// and the used operation. kpeter@696: /// \see BellmanFordDefaultOperationTraits kpeter@696: typedef BellmanFordDefaultOperationTraits OperationTraits; kpeter@696: kpeter@696: /// \brief The type of the map that stores the last kpeter@696: /// arcs of the shortest paths. kpeter@696: /// kpeter@696: /// The type of the map that stores the last kpeter@696: /// arcs of the shortest paths. kpeter@696: /// It must meet the \ref concepts::WriteMap "WriteMap" concept. kpeter@696: typedef NullMap PredMap; kpeter@696: kpeter@696: /// \brief Instantiates a PredMap. kpeter@696: /// kpeter@696: /// This function instantiates a \ref PredMap. kpeter@696: static PredMap *createPredMap(const _Digraph &) { kpeter@696: return new PredMap(); kpeter@696: } kpeter@696: /// \brief The type of the map that stores the dists of the nodes. kpeter@696: /// kpeter@696: /// The type of the map that stores the dists of the nodes. kpeter@696: /// It must meet the \ref concepts::WriteMap "WriteMap" concept. kpeter@696: typedef NullMap DistMap; kpeter@696: /// \brief Instantiates a DistMap. kpeter@696: /// kpeter@696: /// This function instantiates a \ref DistMap. kpeter@696: static DistMap *createDistMap(const _Digraph &) { kpeter@696: return new DistMap(); kpeter@696: } kpeter@696: }; kpeter@696: kpeter@696: /// \brief Default traits used by \ref BellmanFordWizard kpeter@696: /// kpeter@696: /// To make it easier to use BellmanFord algorithm kpeter@696: /// we have created a wizard class. kpeter@696: /// This \ref BellmanFordWizard class needs default traits, kpeter@696: /// as well as the \ref BellmanFord class. kpeter@696: /// The \ref BellmanFordWizardBase is a class to be the default traits of the kpeter@696: /// \ref BellmanFordWizard class. kpeter@696: /// \todo More named parameters are required... kpeter@696: template kpeter@696: class BellmanFordWizardBase kpeter@696: : public BellmanFordWizardDefaultTraits<_Digraph,_LengthMap> { kpeter@696: kpeter@696: typedef BellmanFordWizardDefaultTraits<_Digraph,_LengthMap> Base; kpeter@696: protected: kpeter@696: /// Type of the nodes in the digraph. kpeter@696: typedef typename Base::Digraph::Node Node; kpeter@696: kpeter@696: /// Pointer to the underlying digraph. kpeter@696: void *_graph; kpeter@696: /// Pointer to the length map kpeter@696: void *_length; kpeter@696: ///Pointer to the map of predecessors arcs. kpeter@696: void *_pred; kpeter@696: ///Pointer to the map of distances. kpeter@696: void *_dist; kpeter@696: ///Pointer to the source node. kpeter@696: Node _source; kpeter@696: kpeter@696: public: kpeter@696: /// Constructor. kpeter@696: kpeter@696: /// This constructor does not require parameters, therefore it initiates kpeter@696: /// all of the attributes to default values (0, INVALID). kpeter@696: BellmanFordWizardBase() : _graph(0), _length(0), _pred(0), kpeter@696: _dist(0), _source(INVALID) {} kpeter@696: kpeter@696: /// Constructor. kpeter@696: kpeter@696: /// This constructor requires some parameters, kpeter@696: /// listed in the parameters list. kpeter@696: /// Others are initiated to 0. kpeter@696: /// \param digraph is the initial value of \ref _graph kpeter@696: /// \param length is the initial value of \ref _length kpeter@696: /// \param source is the initial value of \ref _source kpeter@696: BellmanFordWizardBase(const _Digraph& digraph, kpeter@696: const _LengthMap& length, kpeter@696: Node source = INVALID) : kpeter@696: _graph(reinterpret_cast(const_cast<_Digraph*>(&digraph))), kpeter@696: _length(reinterpret_cast(const_cast<_LengthMap*>(&length))), kpeter@696: _pred(0), _dist(0), _source(source) {} kpeter@696: kpeter@696: }; kpeter@696: kpeter@696: /// A class to make the usage of BellmanFord algorithm easier kpeter@696: kpeter@696: /// This class is created to make it easier to use BellmanFord algorithm. kpeter@696: /// It uses the functions and features of the plain \ref BellmanFord, kpeter@696: /// but it is much simpler to use it. kpeter@696: /// kpeter@696: /// Simplicity means that the way to change the types defined kpeter@696: /// in the traits class is based on functions that returns the new class kpeter@696: /// and not on templatable built-in classes. kpeter@696: /// When using the plain \ref BellmanFord kpeter@696: /// the new class with the modified type comes from kpeter@696: /// the original class by using the :: kpeter@696: /// operator. In the case of \ref BellmanFordWizard only kpeter@696: /// a function have to be called and it will kpeter@696: /// return the needed class. kpeter@696: /// kpeter@696: /// It does not have own \ref run method. When its \ref run method is called kpeter@696: /// it initiates a plain \ref BellmanFord class, and calls the \ref kpeter@696: /// BellmanFord::run method of it. kpeter@696: template kpeter@696: class BellmanFordWizard : public _Traits { kpeter@696: typedef _Traits Base; kpeter@696: kpeter@696: ///The type of the underlying digraph. kpeter@696: typedef typename _Traits::Digraph Digraph; kpeter@696: kpeter@696: typedef typename Digraph::Node Node; kpeter@696: typedef typename Digraph::NodeIt NodeIt; kpeter@696: typedef typename Digraph::Arc Arc; kpeter@696: typedef typename Digraph::OutArcIt ArcIt; kpeter@696: kpeter@696: ///The type of the map that stores the arc lengths. kpeter@696: typedef typename _Traits::LengthMap LengthMap; kpeter@696: kpeter@696: ///The type of the length of the arcs. kpeter@696: typedef typename LengthMap::Value Value; kpeter@696: kpeter@696: ///\brief The type of the map that stores the last kpeter@696: ///arcs of the shortest paths. kpeter@696: typedef typename _Traits::PredMap PredMap; kpeter@696: kpeter@696: ///The type of the map that stores the dists of the nodes. kpeter@696: typedef typename _Traits::DistMap DistMap; kpeter@696: kpeter@696: public: kpeter@696: /// Constructor. kpeter@696: BellmanFordWizard() : _Traits() {} kpeter@696: kpeter@696: /// \brief Constructor that requires parameters. kpeter@696: /// kpeter@696: /// Constructor that requires parameters. kpeter@696: /// These parameters will be the default values for the traits class. kpeter@696: BellmanFordWizard(const Digraph& digraph, const LengthMap& length, kpeter@696: Node src = INVALID) kpeter@696: : _Traits(digraph, length, src) {} kpeter@696: kpeter@696: /// \brief Copy constructor kpeter@696: BellmanFordWizard(const _Traits &b) : _Traits(b) {} kpeter@696: kpeter@696: ~BellmanFordWizard() {} kpeter@696: kpeter@696: /// \brief Runs BellmanFord algorithm from a given node. kpeter@696: /// kpeter@696: /// Runs BellmanFord algorithm from a given node. kpeter@696: /// The node can be given by the \ref source function. kpeter@696: void run() { kpeter@696: LEMON_ASSERT(Base::_source != INVALID, "Source node is not given"); kpeter@696: BellmanFord kpeter@696: bf(*reinterpret_cast(Base::_graph), kpeter@696: *reinterpret_cast(Base::_length)); kpeter@696: if (Base::_pred) bf.predMap(*reinterpret_cast(Base::_pred)); kpeter@696: if (Base::_dist) bf.distMap(*reinterpret_cast(Base::_dist)); kpeter@696: bf.run(Base::_source); kpeter@696: } kpeter@696: kpeter@696: /// \brief Runs BellmanFord algorithm from the given node. kpeter@696: /// kpeter@696: /// Runs BellmanFord algorithm from the given node. kpeter@696: /// \param src is the given source. kpeter@696: void run(Node src) { kpeter@696: Base::_source = src; kpeter@696: run(); kpeter@696: } kpeter@696: kpeter@696: template kpeter@696: struct DefPredMapBase : public Base { kpeter@696: typedef T PredMap; kpeter@696: static PredMap *createPredMap(const Digraph &) { return 0; }; kpeter@696: DefPredMapBase(const _Traits &b) : _Traits(b) {} kpeter@696: }; kpeter@696: kpeter@696: ///\brief \ref named-templ-param "Named parameter" kpeter@696: ///function for setting PredMap type kpeter@696: /// kpeter@696: /// \ref named-templ-param "Named parameter" kpeter@696: ///function for setting PredMap type kpeter@696: /// kpeter@696: template kpeter@696: BellmanFordWizard > predMap(const T &t) kpeter@696: { kpeter@696: Base::_pred=reinterpret_cast(const_cast(&t)); kpeter@696: return BellmanFordWizard >(*this); kpeter@696: } kpeter@696: kpeter@696: template kpeter@696: struct DefDistMapBase : public Base { kpeter@696: typedef T DistMap; kpeter@696: static DistMap *createDistMap(const Digraph &) { return 0; }; kpeter@696: DefDistMapBase(const _Traits &b) : _Traits(b) {} kpeter@696: }; kpeter@696: kpeter@696: ///\brief \ref named-templ-param "Named parameter" kpeter@696: ///function for setting DistMap type kpeter@696: /// kpeter@696: /// \ref named-templ-param "Named parameter" kpeter@696: ///function for setting DistMap type kpeter@696: /// kpeter@696: template kpeter@696: BellmanFordWizard > distMap(const T &t) { kpeter@696: Base::_dist=reinterpret_cast(const_cast(&t)); kpeter@696: return BellmanFordWizard >(*this); kpeter@696: } kpeter@696: kpeter@696: template kpeter@696: struct DefOperationTraitsBase : public Base { kpeter@696: typedef T OperationTraits; kpeter@696: DefOperationTraitsBase(const _Traits &b) : _Traits(b) {} kpeter@696: }; kpeter@696: kpeter@696: ///\brief \ref named-templ-param "Named parameter" kpeter@696: ///function for setting OperationTraits type kpeter@696: /// kpeter@696: /// \ref named-templ-param "Named parameter" kpeter@696: ///function for setting OperationTraits type kpeter@696: /// kpeter@696: template kpeter@696: BellmanFordWizard > distMap() { kpeter@696: return BellmanFordWizard >(*this); kpeter@696: } kpeter@696: kpeter@696: /// \brief Sets the source node, from which the BellmanFord algorithm runs. kpeter@696: /// kpeter@696: /// Sets the source node, from which the BellmanFord algorithm runs. kpeter@696: /// \param src is the source node. kpeter@696: BellmanFordWizard<_Traits>& source(Node src) { kpeter@696: Base::_source = src; kpeter@696: return *this; kpeter@696: } kpeter@696: kpeter@696: }; kpeter@696: kpeter@696: /// \brief Function type interface for BellmanFord algorithm. kpeter@696: /// kpeter@696: /// \ingroup shortest_path kpeter@696: /// Function type interface for BellmanFord algorithm. kpeter@696: /// kpeter@696: /// This function also has several \ref named-templ-func-param kpeter@696: /// "named parameters", they are declared as the members of class kpeter@696: /// \ref BellmanFordWizard. kpeter@696: /// The following kpeter@696: /// example shows how to use these parameters. kpeter@696: ///\code kpeter@696: /// bellmanford(g,length,source).predMap(preds).run(); kpeter@696: ///\endcode kpeter@696: /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()" kpeter@696: /// to the end of the parameter list. kpeter@696: /// \sa BellmanFordWizard kpeter@696: /// \sa BellmanFord kpeter@696: template kpeter@696: BellmanFordWizard > kpeter@696: bellmanFord(const _Digraph& digraph, kpeter@696: const _LengthMap& length, kpeter@696: typename _Digraph::Node source = INVALID) { kpeter@696: return BellmanFordWizard > kpeter@696: (digraph, length, source); kpeter@696: } kpeter@696: kpeter@696: } //END OF NAMESPACE LEMON kpeter@696: kpeter@696: #endif kpeter@696: