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