deba@1699: /* -*- C++ -*- deba@1699: * alpar@1956: * This file is a part of LEMON, a generic C++ optimization library alpar@1956: * alpar@1956: * Copyright (C) 2003-2006 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_FLOYD_WARSHALL_H deba@1699: #define LEMON_FLOYD_WARSHALL_H deba@1699: deba@1699: ///\ingroup flowalgs deba@1699: /// \file deba@1699: /// \brief FloydWarshall algorithm. deba@1699: /// deba@1699: deba@1699: #include deba@1699: #include deba@1993: #include deba@1699: #include deba@1723: #include deba@1699: #include deba@1699: deba@1699: #include deba@1699: deba@1699: namespace lemon { deba@1699: deba@1699: /// \brief Default OperationTraits for the FloydWarshall algorithm class. deba@1699: /// deba@1699: /// It defines all computational operations and constants which are deba@1699: /// used in the Floyd-Warshall 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@1699: struct FloydWarshallDefaultOperationTraits { 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@1699: struct FloydWarshallDefaultOperationTraits { 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@1699: /// \brief Default traits class of FloydWarshall class. deba@1699: /// deba@1699: /// Default traits class of FloydWarshall class. deba@1699: /// \param _Graph Graph type. deba@1699: /// \param _LegthMap Type of length map. deba@1699: template deba@1699: struct FloydWarshallDefaultTraits { 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@1865: /// \brief Operation traits for floyd-warshall algorithm. deba@1699: /// deba@1699: /// It defines the infinity type on the given Value type deba@1699: /// and the used operation. deba@1699: /// \see FloydWarshallDefaultOperationTraits deba@1699: typedef FloydWarshallDefaultOperationTraits OperationTraits; deba@1699: deba@1723: /// \brief The type of the matrix map that stores the last edges of the deba@1699: /// shortest paths. deba@1699: /// deba@1723: /// The type of the map that stores the last edges of the shortest paths. deba@1699: /// It must be a matrix map with \c Graph::Edge value type. deba@1699: /// deba@1723: typedef DynamicMatrixMap PredMap; deba@1699: deba@1699: /// \brief Instantiates a PredMap. deba@1699: /// deba@1699: /// This function instantiates a \ref PredMap. alpar@1946: /// \param graph is the graph, alpar@1946: /// to which we would like to define the PredMap. deba@1699: /// \todo The graph alone may be insufficient for the initialization 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::WriteMatrixMap "WriteMatrixMap" concept. deba@1699: /// deba@1723: typedef DynamicMatrixMap DistMap; deba@1699: deba@1699: /// \brief Instantiates a DistMap. deba@1699: /// deba@1699: /// This function instantiates a \ref DistMap. alpar@1946: /// \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@1754: /// \brief %FloydWarshall algorithm class. deba@1699: /// deba@1699: /// \ingroup flowalgs deba@1754: /// This class provides an efficient implementation of \c Floyd-Warshall 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: /// alpar@1757: /// The algorithm solves the shortest path problem for each pair deba@1723: /// of node 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 from each node rather and if the graph is sparse and deba@1754: /// there are negative circles then the johnson algorithm. deba@1723: /// deba@2042: /// The complexity of this algorithm is \f$ O(n^3+e) \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@1699: /// FloydWarshall, it is only passed to \ref FloydWarshallDefaultTraits. deba@1699: /// \param _LengthMap This read-only EdgeMap determines the lengths of the deba@1699: /// edges. It is read once for each edge, so the map may involve in deba@1699: /// relatively time consuming process to compute the edge length if deba@1699: /// it is necessary. The default map type is \ref alpar@2260: /// concepts::Graph::EdgeMap "Graph::EdgeMap". The value deba@1699: /// of _LengthMap is not used directly by FloydWarshall, it is only passed deba@1699: /// to \ref FloydWarshallDefaultTraits. \param _Traits Traits class to set deba@1699: /// various data types used by the algorithm. The default traits deba@1699: /// class is \ref FloydWarshallDefaultTraits deba@1699: /// "FloydWarshallDefaultTraits<_Graph,_LengthMap>". See \ref deba@1699: /// FloydWarshallDefaultTraits for the documentation of a FloydWarshall deba@1699: /// traits class. deba@1699: /// deba@1699: /// \author Balazs Dezso alpar@2184: /// \todo A function type interface would be nice. alpar@2184: /// \todo Implement \c nextNode() and \c nextEdge() deba@1710: #ifdef DOXYGEN alpar@2184: template deba@1710: #else deba@1699: template , deba@1699: typename _Traits=FloydWarshallDefaultTraits<_Graph,_LengthMap> > deba@1710: #endif deba@1699: class FloydWarshall { 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@1699: return "lemon::FloydWarshall::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@1699: typedef typename Graph::EdgeIt EdgeIt; 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. The type of the PredMap deba@1699: /// is a matrix map for Edges deba@1699: typedef typename _Traits::PredMap PredMap; deba@1699: /// \brief The type of the map that stores the dists of the nodes. deba@1699: /// The type of the DistMap is a matrix map for Values alpar@2184: /// alpar@2184: /// \todo It should rather be alpar@2184: /// called \c DistMatrix 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@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@1699: } deba@1699: deba@1699: public : deba@1699: 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@1699: static PredMap *createPredMap(const Graph& 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@1710: struct DefPredMap deba@1710: : public FloydWarshall< Graph, LengthMap, DefPredMapTraits > { deba@1710: typedef FloydWarshall< Graph, LengthMap, DefPredMapTraits > Create; deba@1710: }; deba@1699: deba@1699: template deba@1699: struct DefDistMapTraits : public Traits { deba@1699: typedef T DistMap; deba@1699: static DistMap *createDistMap(const Graph& graph) { deba@1699: throw UninitializedParameter(); 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@1710: : public FloydWarshall< Graph, LengthMap, DefDistMapTraits > { deba@1710: typedef FloydWarshall< 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@1699: /// \ref named-templ-param "Named parameter" for setting PredMap type deba@1699: template deba@1710: struct DefOperationTraits deba@1699: : public FloydWarshall< Graph, LengthMap, DefOperationTraitsTraits > { deba@1710: typedef FloydWarshall< Graph, LengthMap, DefOperationTraitsTraits > deba@1710: Create; deba@1699: }; deba@1699: deba@1699: ///@} deba@1699: deba@1710: protected: deba@1710: deba@1710: FloydWarshall() {} deba@1710: deba@1699: public: deba@1710: deba@1710: typedef FloydWarshall Create; 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@1699: FloydWarshall(const Graph& _graph, const LengthMap& _length) : deba@1699: graph(&_graph), length(&_length), deba@1699: _pred(0), local_pred(false), deba@1699: _dist(0), local_dist(false) {} deba@1699: deba@1699: ///Destructor. deba@1699: ~FloydWarshall() { deba@1699: if(local_pred) delete _pred; deba@1699: if(local_dist) delete _dist; 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@1699: FloydWarshall &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@1699: FloydWarshall &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@1699: FloydWarshall &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: /// 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@1699: void init() { deba@1699: create_maps(); deba@1699: for (NodeIt it(*graph); it != INVALID; ++it) { deba@1699: for (NodeIt jt(*graph); jt != INVALID; ++jt) { deba@1699: _pred->set(it, jt, INVALID); deba@1741: _dist->set(it, jt, OperationTraits::infinity()); deba@1699: } deba@1741: _dist->set(it, it, OperationTraits::zero()); deba@1699: } deba@1699: for (EdgeIt it(*graph); it != INVALID; ++it) { deba@1699: Node source = graph->source(it); deba@1699: Node target = graph->target(it); deba@1699: if (OperationTraits::less((*length)[it], (*_dist)(source, target))) { deba@1699: _dist->set(source, target, (*length)[it]); deba@1699: _pred->set(source, target, it); deba@1699: } deba@1699: } deba@1699: } deba@1699: deba@1699: /// \brief Executes the algorithm. deba@1699: /// deba@1699: /// This method runs the %FloydWarshall algorithm in order to compute deba@1699: /// the shortest path to each node pairs. The algorithm deba@1699: /// computes deba@1699: /// - The shortest path tree for each node. deba@1699: /// - The distance between each node pairs. deba@1699: void start() { deba@1699: for (NodeIt kt(*graph); kt != INVALID; ++kt) { deba@1699: for (NodeIt it(*graph); it != INVALID; ++it) { deba@1699: for (NodeIt jt(*graph); jt != INVALID; ++jt) { deba@1699: Value relaxed = OperationTraits::plus((*_dist)(it, kt), deba@1699: (*_dist)(kt, jt)); deba@1699: if (OperationTraits::less(relaxed, (*_dist)(it, jt))) { deba@1699: _dist->set(it, jt, relaxed); deba@1699: _pred->set(it, jt, (*_pred)(kt, jt)); deba@1699: } deba@1699: } deba@1699: } deba@1699: } deba@1699: } deba@1741: deba@1754: /// \brief Executes the algorithm and checks the negative cycles. deba@1741: /// deba@1741: /// This method runs the %FloydWarshall algorithm in order to compute deba@1754: /// the shortest path to each node pairs. If there is a negative cycle deba@1741: /// in the graph it gives back false. deba@1741: /// The algorithm computes deba@1741: /// - The shortest path tree for each node. deba@1741: /// - The distance between each node pairs. deba@1741: bool checkedStart() { deba@1741: start(); deba@1741: for (NodeIt it(*graph); it != INVALID; ++it) { deba@1741: if (OperationTraits::less((*dist)(it, it), OperationTraits::zero())) { deba@1741: return false; deba@1741: } deba@1741: } deba@1741: return true; deba@1741: } deba@1699: deba@1699: /// \brief Runs %FloydWarshall algorithm. deba@1699: /// deba@1699: /// This method runs the %FloydWarshall algorithm from a each node deba@1699: /// in order to compute the shortest path to each node pairs. deba@1699: /// The algorithm computes deba@1699: /// - The shortest path tree for each node. deba@1699: /// - The distance between each node pairs. 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.start(); alpar@1946: ///\endcode deba@1699: void run() { deba@1699: init(); deba@1699: start(); deba@1699: } deba@1699: deba@1699: ///@} deba@1699: deba@1699: /// \name Query Functions deba@1699: /// The result of the %FloydWarshall 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@1699: /// \brief Copies the shortest path to \c t into \c p deba@1699: /// deba@1699: /// This function copies the shortest path to \c t into \c p. deba@1699: /// If it \c t is a source itself or unreachable, then it does not deba@1699: /// alter \c p. deba@1699: /// \return Returns \c true if a path to \c t was actually copied to \c p, deba@1699: /// \c false otherwise. deba@1699: /// \sa DirPath deba@1699: template deba@1699: bool getPath(Path &p, Node source, Node target) { deba@1699: if (connected(source, target)) { deba@1699: p.clear(); deba@1699: typename Path::Builder b(target); deba@1763: for(b.setStartNode(target); predEdge(source, target) != INVALID; deba@1699: target = predNode(target)) { deba@1763: b.pushFront(predEdge(source, target)); deba@1699: } deba@1699: b.commit(); deba@1699: return true; deba@1699: } deba@1699: return false; deba@1699: } deba@1699: deba@1699: /// \brief The distance between two nodes. deba@1699: /// deba@1699: /// Returns the distance between two nodes. 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 source, Node target) const { deba@1699: return (*_dist)(source, target); deba@1699: } deba@1699: deba@1699: /// \brief Returns the 'previous edge' of the shortest path tree. deba@1699: /// deba@1699: /// For the node \c node it returns the 'previous edge' of the shortest deba@1699: /// path tree to direction of the node \c root deba@1699: /// i.e. it returns the last edge of a shortest path from the node \c root deba@1699: /// to \c node. It is \ref INVALID if \c node is unreachable from the root deba@1699: /// or if \c node=root. The shortest path tree used here is equal to the deba@1699: /// shortest path tree used in \ref predNode(). deba@1699: /// \pre \ref run() must be called before using this function. deba@1763: Edge predEdge(Node root, Node node) const { deba@1699: return (*_pred)(root, node); deba@1699: } deba@1699: deba@1699: /// \brief Returns the 'previous node' of the shortest path tree. deba@1699: /// deba@1699: /// For a node \c node it returns the 'previous node' of the shortest path deba@1699: /// tree to direction of the node \c root, i.e. it returns the last but deba@1699: /// one node from a shortest path from the \c root to \c node. It is deba@1699: /// INVALID if \c node is unreachable from the root or if \c node=root. deba@1699: /// The shortest path tree used here is equal to the deba@1763: /// shortest path tree used in \ref predEdge(). deba@1699: /// \pre \ref run() must be called before using this function. deba@1699: Node predNode(Node root, Node node) const { deba@1699: return (*_pred)(root, node) == INVALID ? deba@1699: INVALID : graph->source((*_pred)(root, node)); deba@1699: } deba@1699: deba@1699: /// \brief Returns a reference to the matrix node map of distances. deba@1699: /// deba@1699: /// Returns a reference to the matrix node map of distances. deba@1699: /// deba@1699: /// \pre \ref run() must 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 matrix node map 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 connected(Node source, Node target) { deba@1699: return (*_dist)(source, target) != OperationTraits::infinity(); deba@1699: } deba@1699: deba@1699: ///@} deba@1699: }; deba@1699: deba@1699: } //END OF NAMESPACE LEMON deba@1699: deba@1699: #endif deba@1699: