kpeter@765: /* -*- C++ -*- kpeter@765: * kpeter@765: * This file is a part of LEMON, a generic C++ optimization library kpeter@765: * kpeter@765: * Copyright (C) 2003-2008 kpeter@765: * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport kpeter@765: * (Egervary Research Group on Combinatorial Optimization, EGRES). kpeter@765: * kpeter@765: * Permission to use, modify and distribute this software is granted kpeter@765: * provided that this copyright notice appears in all copies. For kpeter@765: * precise terms see the accompanying LICENSE file. kpeter@765: * kpeter@765: * This software is provided "AS IS" with no warranty of any kind, kpeter@765: * express or implied, and with no claim as to its suitability for any kpeter@765: * purpose. kpeter@765: * kpeter@765: */ kpeter@765: kpeter@765: #ifndef LEMON_KARP_H kpeter@765: #define LEMON_KARP_H kpeter@765: kpeter@768: /// \ingroup min_mean_cycle kpeter@765: /// kpeter@765: /// \file kpeter@765: /// \brief Karp's algorithm for finding a minimum mean cycle. kpeter@765: kpeter@765: #include kpeter@765: #include kpeter@765: #include kpeter@765: #include kpeter@765: #include kpeter@765: #include kpeter@765: kpeter@765: namespace lemon { kpeter@765: kpeter@765: /// \brief Default traits class of Karp algorithm. kpeter@765: /// kpeter@765: /// Default traits class of Karp algorithm. kpeter@765: /// \tparam GR The type of the digraph. kpeter@765: /// \tparam LEN The type of the length map. kpeter@765: /// It must conform to the \ref concepts::ReadMap "ReadMap" concept. kpeter@765: #ifdef DOXYGEN kpeter@765: template kpeter@765: #else kpeter@765: template ::is_integer> kpeter@765: #endif kpeter@765: struct KarpDefaultTraits kpeter@765: { kpeter@765: /// The type of the digraph kpeter@765: typedef GR Digraph; kpeter@765: /// The type of the length map kpeter@765: typedef LEN LengthMap; kpeter@765: /// The type of the arc lengths kpeter@765: typedef typename LengthMap::Value Value; kpeter@765: kpeter@765: /// \brief The large value type used for internal computations kpeter@765: /// kpeter@765: /// The large value type used for internal computations. kpeter@765: /// It is \c long \c long if the \c Value type is integer, kpeter@765: /// otherwise it is \c double. kpeter@765: /// \c Value must be convertible to \c LargeValue. kpeter@765: typedef double LargeValue; kpeter@765: kpeter@765: /// The tolerance type used for internal computations kpeter@765: typedef lemon::Tolerance Tolerance; kpeter@765: kpeter@765: /// \brief The path type of the found cycles kpeter@765: /// kpeter@765: /// The path type of the found cycles. kpeter@765: /// It must conform to the \ref lemon::concepts::Path "Path" concept kpeter@772: /// and it must have an \c addFront() function. kpeter@765: typedef lemon::Path Path; kpeter@765: }; kpeter@765: kpeter@765: // Default traits class for integer value types kpeter@765: template kpeter@765: struct KarpDefaultTraits kpeter@765: { kpeter@765: typedef GR Digraph; kpeter@765: typedef LEN LengthMap; kpeter@765: typedef typename LengthMap::Value Value; kpeter@765: #ifdef LEMON_HAVE_LONG_LONG kpeter@765: typedef long long LargeValue; kpeter@765: #else kpeter@765: typedef long LargeValue; kpeter@765: #endif kpeter@765: typedef lemon::Tolerance Tolerance; kpeter@765: typedef lemon::Path Path; kpeter@765: }; kpeter@765: kpeter@765: kpeter@768: /// \addtogroup min_mean_cycle kpeter@765: /// @{ kpeter@765: kpeter@765: /// \brief Implementation of Karp's algorithm for finding a minimum kpeter@765: /// mean cycle. kpeter@765: /// kpeter@765: /// This class implements Karp's algorithm for finding a directed kpeter@771: /// cycle of minimum mean length (cost) in a digraph kpeter@771: /// \ref amo93networkflows, \ref dasdan98minmeancycle. kpeter@768: /// It runs in time O(ne) and uses space O(n2+e). kpeter@765: /// kpeter@765: /// \tparam GR The type of the digraph the algorithm runs on. kpeter@765: /// \tparam LEN The type of the length map. The default kpeter@765: /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap". kpeter@765: #ifdef DOXYGEN kpeter@765: template kpeter@765: #else kpeter@765: template < typename GR, kpeter@765: typename LEN = typename GR::template ArcMap, kpeter@765: typename TR = KarpDefaultTraits > kpeter@765: #endif kpeter@765: class Karp kpeter@765: { kpeter@765: public: kpeter@765: kpeter@765: /// The type of the digraph kpeter@765: typedef typename TR::Digraph Digraph; kpeter@765: /// The type of the length map kpeter@765: typedef typename TR::LengthMap LengthMap; kpeter@765: /// The type of the arc lengths kpeter@765: typedef typename TR::Value Value; kpeter@765: kpeter@765: /// \brief The large value type kpeter@765: /// kpeter@765: /// The large value type used for internal computations. kpeter@765: /// Using the \ref KarpDefaultTraits "default traits class", kpeter@765: /// it is \c long \c long if the \c Value type is integer, kpeter@765: /// otherwise it is \c double. kpeter@765: typedef typename TR::LargeValue LargeValue; kpeter@765: kpeter@765: /// The tolerance type kpeter@765: typedef typename TR::Tolerance Tolerance; kpeter@765: kpeter@765: /// \brief The path type of the found cycles kpeter@765: /// kpeter@765: /// The path type of the found cycles. kpeter@765: /// Using the \ref KarpDefaultTraits "default traits class", kpeter@765: /// it is \ref lemon::Path "Path". kpeter@765: typedef typename TR::Path Path; kpeter@765: kpeter@765: /// The \ref KarpDefaultTraits "traits class" of the algorithm kpeter@765: typedef TR Traits; kpeter@765: kpeter@765: private: kpeter@765: kpeter@765: TEMPLATE_DIGRAPH_TYPEDEFS(Digraph); kpeter@765: kpeter@765: // Data sturcture for path data kpeter@765: struct PathData kpeter@765: { kpeter@765: LargeValue dist; kpeter@765: Arc pred; kpeter@767: PathData(LargeValue d, Arc p = INVALID) : kpeter@767: dist(d), pred(p) {} kpeter@765: }; kpeter@765: kpeter@765: typedef typename Digraph::template NodeMap > kpeter@765: PathDataNodeMap; kpeter@765: kpeter@765: private: kpeter@765: kpeter@765: // The digraph the algorithm runs on kpeter@765: const Digraph &_gr; kpeter@765: // The length of the arcs kpeter@765: const LengthMap &_length; kpeter@765: kpeter@765: // Data for storing the strongly connected components kpeter@765: int _comp_num; kpeter@765: typename Digraph::template NodeMap _comp; kpeter@765: std::vector > _comp_nodes; kpeter@765: std::vector* _nodes; kpeter@765: typename Digraph::template NodeMap > _out_arcs; kpeter@765: kpeter@765: // Data for the found cycle kpeter@765: LargeValue _cycle_length; kpeter@765: int _cycle_size; kpeter@765: Node _cycle_node; kpeter@765: kpeter@765: Path *_cycle_path; kpeter@765: bool _local_path; kpeter@765: kpeter@765: // Node map for storing path data kpeter@765: PathDataNodeMap _data; kpeter@765: // The processed nodes in the last round kpeter@765: std::vector _process; kpeter@765: kpeter@765: Tolerance _tolerance; kpeter@767: kpeter@767: // Infinite constant kpeter@767: const LargeValue INF; kpeter@765: kpeter@765: public: kpeter@765: kpeter@765: /// \name Named Template Parameters kpeter@765: /// @{ kpeter@765: kpeter@765: template kpeter@765: struct SetLargeValueTraits : public Traits { kpeter@765: typedef T LargeValue; kpeter@765: typedef lemon::Tolerance Tolerance; kpeter@765: }; kpeter@765: kpeter@765: /// \brief \ref named-templ-param "Named parameter" for setting kpeter@765: /// \c LargeValue type. kpeter@765: /// kpeter@765: /// \ref named-templ-param "Named parameter" for setting \c LargeValue kpeter@765: /// type. It is used for internal computations in the algorithm. kpeter@765: template kpeter@765: struct SetLargeValue kpeter@765: : public Karp > { kpeter@765: typedef Karp > Create; kpeter@765: }; kpeter@765: kpeter@765: template kpeter@765: struct SetPathTraits : public Traits { kpeter@765: typedef T Path; kpeter@765: }; kpeter@765: kpeter@765: /// \brief \ref named-templ-param "Named parameter" for setting kpeter@765: /// \c %Path type. kpeter@765: /// kpeter@765: /// \ref named-templ-param "Named parameter" for setting the \c %Path kpeter@765: /// type of the found cycles. kpeter@765: /// It must conform to the \ref lemon::concepts::Path "Path" concept kpeter@765: /// and it must have an \c addFront() function. kpeter@765: template kpeter@765: struct SetPath kpeter@765: : public Karp > { kpeter@765: typedef Karp > Create; kpeter@765: }; kpeter@765: kpeter@765: /// @} kpeter@765: kpeter@765: public: kpeter@765: kpeter@765: /// \brief Constructor. kpeter@765: /// kpeter@765: /// The constructor of the class. kpeter@765: /// kpeter@765: /// \param digraph The digraph the algorithm runs on. kpeter@765: /// \param length The lengths (costs) of the arcs. kpeter@765: Karp( const Digraph &digraph, kpeter@765: const LengthMap &length ) : kpeter@765: _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph), kpeter@765: _cycle_length(0), _cycle_size(1), _cycle_node(INVALID), kpeter@767: _cycle_path(NULL), _local_path(false), _data(digraph), kpeter@767: INF(std::numeric_limits::has_infinity ? kpeter@767: std::numeric_limits::infinity() : kpeter@767: std::numeric_limits::max()) kpeter@765: {} kpeter@765: kpeter@765: /// Destructor. kpeter@765: ~Karp() { kpeter@765: if (_local_path) delete _cycle_path; kpeter@765: } kpeter@765: kpeter@765: /// \brief Set the path structure for storing the found cycle. kpeter@765: /// kpeter@765: /// This function sets an external path structure for storing the kpeter@765: /// found cycle. kpeter@765: /// kpeter@765: /// If you don't call this function before calling \ref run() or kpeter@765: /// \ref findMinMean(), it will allocate a local \ref Path "path" kpeter@765: /// structure. The destuctor deallocates this automatically kpeter@765: /// allocated object, of course. kpeter@765: /// kpeter@765: /// \note The algorithm calls only the \ref lemon::Path::addFront() kpeter@765: /// "addFront()" function of the given path structure. kpeter@765: /// kpeter@765: /// \return (*this) kpeter@765: Karp& cycle(Path &path) { kpeter@765: if (_local_path) { kpeter@765: delete _cycle_path; kpeter@765: _local_path = false; kpeter@765: } kpeter@765: _cycle_path = &path; kpeter@765: return *this; kpeter@765: } kpeter@765: kpeter@769: /// \brief Set the tolerance used by the algorithm. kpeter@769: /// kpeter@769: /// This function sets the tolerance object used by the algorithm. kpeter@769: /// kpeter@769: /// \return (*this) kpeter@769: Karp& tolerance(const Tolerance& tolerance) { kpeter@769: _tolerance = tolerance; kpeter@769: return *this; kpeter@769: } kpeter@769: kpeter@769: /// \brief Return a const reference to the tolerance. kpeter@769: /// kpeter@769: /// This function returns a const reference to the tolerance object kpeter@769: /// used by the algorithm. kpeter@769: const Tolerance& tolerance() const { kpeter@769: return _tolerance; kpeter@769: } kpeter@769: kpeter@765: /// \name Execution control kpeter@765: /// The simplest way to execute the algorithm is to call the \ref run() kpeter@765: /// function.\n kpeter@765: /// If you only need the minimum mean length, you may call kpeter@765: /// \ref findMinMean(). kpeter@765: kpeter@765: /// @{ kpeter@765: kpeter@765: /// \brief Run the algorithm. kpeter@765: /// kpeter@765: /// This function runs the algorithm. kpeter@765: /// It can be called more than once (e.g. if the underlying digraph kpeter@765: /// and/or the arc lengths have been modified). kpeter@765: /// kpeter@765: /// \return \c true if a directed cycle exists in the digraph. kpeter@765: /// kpeter@765: /// \note mmc.run() is just a shortcut of the following code. kpeter@765: /// \code kpeter@765: /// return mmc.findMinMean() && mmc.findCycle(); kpeter@765: /// \endcode kpeter@765: bool run() { kpeter@765: return findMinMean() && findCycle(); kpeter@765: } kpeter@765: kpeter@765: /// \brief Find the minimum cycle mean. kpeter@765: /// kpeter@765: /// This function finds the minimum mean length of the directed kpeter@765: /// cycles in the digraph. kpeter@765: /// kpeter@765: /// \return \c true if a directed cycle exists in the digraph. kpeter@765: bool findMinMean() { kpeter@765: // Initialization and find strongly connected components kpeter@765: init(); kpeter@765: findComponents(); kpeter@765: kpeter@765: // Find the minimum cycle mean in the components kpeter@765: for (int comp = 0; comp < _comp_num; ++comp) { kpeter@765: if (!initComponent(comp)) continue; kpeter@765: processRounds(); kpeter@765: updateMinMean(); kpeter@765: } kpeter@765: return (_cycle_node != INVALID); kpeter@765: } kpeter@765: kpeter@765: /// \brief Find a minimum mean directed cycle. kpeter@765: /// kpeter@765: /// This function finds a directed cycle of minimum mean length kpeter@765: /// in the digraph using the data computed by findMinMean(). kpeter@765: /// kpeter@765: /// \return \c true if a directed cycle exists in the digraph. kpeter@765: /// kpeter@765: /// \pre \ref findMinMean() must be called before using this function. kpeter@765: bool findCycle() { kpeter@765: if (_cycle_node == INVALID) return false; kpeter@765: IntNodeMap reached(_gr, -1); kpeter@765: int r = _data[_cycle_node].size(); kpeter@765: Node u = _cycle_node; kpeter@765: while (reached[u] < 0) { kpeter@765: reached[u] = --r; kpeter@765: u = _gr.source(_data[u][r].pred); kpeter@765: } kpeter@765: r = reached[u]; kpeter@765: Arc e = _data[u][r].pred; kpeter@765: _cycle_path->addFront(e); kpeter@765: _cycle_length = _length[e]; kpeter@765: _cycle_size = 1; kpeter@765: Node v; kpeter@765: while ((v = _gr.source(e)) != u) { kpeter@765: e = _data[v][--r].pred; kpeter@765: _cycle_path->addFront(e); kpeter@765: _cycle_length += _length[e]; kpeter@765: ++_cycle_size; kpeter@765: } kpeter@765: return true; kpeter@765: } kpeter@765: kpeter@765: /// @} kpeter@765: kpeter@765: /// \name Query Functions kpeter@765: /// The results of the algorithm can be obtained using these kpeter@765: /// functions.\n kpeter@765: /// The algorithm should be executed before using them. kpeter@765: kpeter@765: /// @{ kpeter@765: kpeter@765: /// \brief Return the total length of the found cycle. kpeter@765: /// kpeter@765: /// This function returns the total length of the found cycle. kpeter@765: /// kpeter@765: /// \pre \ref run() or \ref findMinMean() must be called before kpeter@765: /// using this function. kpeter@765: LargeValue cycleLength() const { kpeter@765: return _cycle_length; kpeter@765: } kpeter@765: kpeter@765: /// \brief Return the number of arcs on the found cycle. kpeter@765: /// kpeter@765: /// This function returns the number of arcs on the found cycle. kpeter@765: /// kpeter@765: /// \pre \ref run() or \ref findMinMean() must be called before kpeter@765: /// using this function. kpeter@765: int cycleArcNum() const { kpeter@765: return _cycle_size; kpeter@765: } kpeter@765: kpeter@765: /// \brief Return the mean length of the found cycle. kpeter@765: /// kpeter@765: /// This function returns the mean length of the found cycle. kpeter@765: /// kpeter@765: /// \note alg.cycleMean() is just a shortcut of the kpeter@765: /// following code. kpeter@765: /// \code kpeter@765: /// return static_cast(alg.cycleLength()) / alg.cycleArcNum(); kpeter@765: /// \endcode kpeter@765: /// kpeter@765: /// \pre \ref run() or \ref findMinMean() must be called before kpeter@765: /// using this function. kpeter@765: double cycleMean() const { kpeter@765: return static_cast(_cycle_length) / _cycle_size; kpeter@765: } kpeter@765: kpeter@765: /// \brief Return the found cycle. kpeter@765: /// kpeter@765: /// This function returns a const reference to the path structure kpeter@765: /// storing the found cycle. kpeter@765: /// kpeter@765: /// \pre \ref run() or \ref findCycle() must be called before using kpeter@765: /// this function. kpeter@765: const Path& cycle() const { kpeter@765: return *_cycle_path; kpeter@765: } kpeter@765: kpeter@765: ///@} kpeter@765: kpeter@765: private: kpeter@765: kpeter@765: // Initialization kpeter@765: void init() { kpeter@765: if (!_cycle_path) { kpeter@765: _local_path = true; kpeter@765: _cycle_path = new Path; kpeter@765: } kpeter@765: _cycle_path->clear(); kpeter@765: _cycle_length = 0; kpeter@765: _cycle_size = 1; kpeter@765: _cycle_node = INVALID; kpeter@765: for (NodeIt u(_gr); u != INVALID; ++u) kpeter@765: _data[u].clear(); kpeter@765: } kpeter@765: kpeter@765: // Find strongly connected components and initialize _comp_nodes kpeter@765: // and _out_arcs kpeter@765: void findComponents() { kpeter@765: _comp_num = stronglyConnectedComponents(_gr, _comp); kpeter@765: _comp_nodes.resize(_comp_num); kpeter@765: if (_comp_num == 1) { kpeter@765: _comp_nodes[0].clear(); kpeter@765: for (NodeIt n(_gr); n != INVALID; ++n) { kpeter@765: _comp_nodes[0].push_back(n); kpeter@765: _out_arcs[n].clear(); kpeter@765: for (OutArcIt a(_gr, n); a != INVALID; ++a) { kpeter@765: _out_arcs[n].push_back(a); kpeter@765: } kpeter@765: } kpeter@765: } else { kpeter@765: for (int i = 0; i < _comp_num; ++i) kpeter@765: _comp_nodes[i].clear(); kpeter@765: for (NodeIt n(_gr); n != INVALID; ++n) { kpeter@765: int k = _comp[n]; kpeter@765: _comp_nodes[k].push_back(n); kpeter@765: _out_arcs[n].clear(); kpeter@765: for (OutArcIt a(_gr, n); a != INVALID; ++a) { kpeter@765: if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a); kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: kpeter@765: // Initialize path data for the current component kpeter@765: bool initComponent(int comp) { kpeter@765: _nodes = &(_comp_nodes[comp]); kpeter@765: int n = _nodes->size(); kpeter@765: if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) { kpeter@765: return false; kpeter@765: } kpeter@765: for (int i = 0; i < n; ++i) { kpeter@767: _data[(*_nodes)[i]].resize(n + 1, PathData(INF)); kpeter@765: } kpeter@765: return true; kpeter@765: } kpeter@765: kpeter@765: // Process all rounds of computing path data for the current component. kpeter@765: // _data[v][k] is the length of a shortest directed walk from the root kpeter@765: // node to node v containing exactly k arcs. kpeter@765: void processRounds() { kpeter@765: Node start = (*_nodes)[0]; kpeter@767: _data[start][0] = PathData(0); kpeter@765: _process.clear(); kpeter@765: _process.push_back(start); kpeter@765: kpeter@765: int k, n = _nodes->size(); kpeter@765: for (k = 1; k <= n && int(_process.size()) < n; ++k) { kpeter@765: processNextBuildRound(k); kpeter@765: } kpeter@765: for ( ; k <= n; ++k) { kpeter@765: processNextFullRound(k); kpeter@765: } kpeter@765: } kpeter@765: kpeter@765: // Process one round and rebuild _process kpeter@765: void processNextBuildRound(int k) { kpeter@765: std::vector next; kpeter@765: Node u, v; kpeter@765: Arc e; kpeter@765: LargeValue d; kpeter@765: for (int i = 0; i < int(_process.size()); ++i) { kpeter@765: u = _process[i]; kpeter@765: for (int j = 0; j < int(_out_arcs[u].size()); ++j) { kpeter@765: e = _out_arcs[u][j]; kpeter@765: v = _gr.target(e); kpeter@765: d = _data[u][k-1].dist + _length[e]; kpeter@767: if (_tolerance.less(d, _data[v][k].dist)) { kpeter@767: if (_data[v][k].dist == INF) next.push_back(v); kpeter@767: _data[v][k] = PathData(d, e); kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: _process.swap(next); kpeter@765: } kpeter@765: kpeter@765: // Process one round using _nodes instead of _process kpeter@765: void processNextFullRound(int k) { kpeter@765: Node u, v; kpeter@765: Arc e; kpeter@765: LargeValue d; kpeter@765: for (int i = 0; i < int(_nodes->size()); ++i) { kpeter@765: u = (*_nodes)[i]; kpeter@765: for (int j = 0; j < int(_out_arcs[u].size()); ++j) { kpeter@765: e = _out_arcs[u][j]; kpeter@765: v = _gr.target(e); kpeter@765: d = _data[u][k-1].dist + _length[e]; kpeter@767: if (_tolerance.less(d, _data[v][k].dist)) { kpeter@767: _data[v][k] = PathData(d, e); kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: kpeter@765: // Update the minimum cycle mean kpeter@765: void updateMinMean() { kpeter@765: int n = _nodes->size(); kpeter@765: for (int i = 0; i < n; ++i) { kpeter@765: Node u = (*_nodes)[i]; kpeter@767: if (_data[u][n].dist == INF) continue; kpeter@765: LargeValue length, max_length = 0; kpeter@765: int size, max_size = 1; kpeter@765: bool found_curr = false; kpeter@765: for (int k = 0; k < n; ++k) { kpeter@767: if (_data[u][k].dist == INF) continue; kpeter@765: length = _data[u][n].dist - _data[u][k].dist; kpeter@765: size = n - k; kpeter@765: if (!found_curr || length * max_size > max_length * size) { kpeter@765: found_curr = true; kpeter@765: max_length = length; kpeter@765: max_size = size; kpeter@765: } kpeter@765: } kpeter@765: if ( found_curr && (_cycle_node == INVALID || kpeter@765: max_length * _cycle_size < _cycle_length * max_size) ) { kpeter@765: _cycle_length = max_length; kpeter@765: _cycle_size = max_size; kpeter@765: _cycle_node = u; kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: kpeter@765: }; //class Karp kpeter@765: kpeter@765: ///@} kpeter@765: kpeter@765: } //namespace lemon kpeter@765: kpeter@765: #endif //LEMON_KARP_H