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