alpar@877: /* -*- mode: C++; indent-tabs-mode: nil; -*- kpeter@765: * alpar@877: * This file is a part of LEMON, a generic C++ optimization library. kpeter@765: * alpar@877: * Copyright (C) 2003-2010 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@864: #ifndef LEMON_KARP_MMC_H kpeter@864: #define LEMON_KARP_MMC_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@864: /// \brief Default traits class of KarpMmc class. kpeter@765: /// kpeter@864: /// Default traits class of KarpMmc class. kpeter@765: /// \tparam GR The type of the digraph. kpeter@864: /// \tparam CM The type of the cost map. kpeter@765: /// It must conform to the \ref concepts::ReadMap "ReadMap" concept. kpeter@765: #ifdef DOXYGEN kpeter@864: template kpeter@765: #else kpeter@864: template ::is_integer> kpeter@765: #endif kpeter@864: struct KarpMmcDefaultTraits kpeter@765: { kpeter@765: /// The type of the digraph kpeter@765: typedef GR Digraph; kpeter@864: /// The type of the cost map kpeter@864: typedef CM CostMap; kpeter@864: /// The type of the arc costs kpeter@864: typedef typename CostMap::Value Cost; kpeter@765: kpeter@864: /// \brief The large cost type used for internal computations kpeter@765: /// kpeter@864: /// The large cost type used for internal computations. kpeter@864: /// It is \c long \c long if the \c Cost type is integer, kpeter@765: /// otherwise it is \c double. kpeter@864: /// \c Cost must be convertible to \c LargeCost. kpeter@864: typedef double LargeCost; kpeter@765: kpeter@765: /// The tolerance type used for internal computations kpeter@864: 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@864: // Default traits class for integer cost types kpeter@864: template kpeter@864: struct KarpMmcDefaultTraits kpeter@765: { kpeter@765: typedef GR Digraph; kpeter@864: typedef CM CostMap; kpeter@864: typedef typename CostMap::Value Cost; kpeter@765: #ifdef LEMON_HAVE_LONG_LONG kpeter@864: typedef long long LargeCost; kpeter@765: #else kpeter@864: typedef long LargeCost; kpeter@765: #endif kpeter@864: 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@864: /// cycle of minimum mean cost in a digraph kpeter@1002: /// \ref karp78characterization, \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@864: /// \tparam CM The type of the cost map. The default kpeter@765: /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap". kpeter@825: /// \tparam TR The traits class that defines various types used by the kpeter@864: /// algorithm. By default, it is \ref KarpMmcDefaultTraits kpeter@864: /// "KarpMmcDefaultTraits". kpeter@825: /// In most cases, this parameter should not be set directly, kpeter@825: /// consider to use the named template parameters instead. kpeter@765: #ifdef DOXYGEN kpeter@864: template kpeter@765: #else kpeter@765: template < typename GR, kpeter@864: typename CM = typename GR::template ArcMap, kpeter@864: typename TR = KarpMmcDefaultTraits > kpeter@765: #endif kpeter@864: class KarpMmc kpeter@765: { kpeter@765: public: kpeter@765: kpeter@765: /// The type of the digraph kpeter@765: typedef typename TR::Digraph Digraph; kpeter@864: /// The type of the cost map kpeter@864: typedef typename TR::CostMap CostMap; kpeter@864: /// The type of the arc costs kpeter@864: typedef typename TR::Cost Cost; kpeter@765: kpeter@864: /// \brief The large cost type kpeter@765: /// kpeter@864: /// The large cost type used for internal computations. kpeter@864: /// By default, it is \c long \c long if the \c Cost type is integer, kpeter@765: /// otherwise it is \c double. kpeter@864: typedef typename TR::LargeCost LargeCost; 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@864: /// Using the \ref KarpMmcDefaultTraits "default traits class", kpeter@765: /// it is \ref lemon::Path "Path". kpeter@765: typedef typename TR::Path Path; kpeter@765: kpeter@864: /// The \ref KarpMmcDefaultTraits "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@864: LargeCost dist; kpeter@765: Arc pred; kpeter@864: PathData(LargeCost 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@864: // The cost of the arcs kpeter@864: const CostMap &_cost; 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@864: LargeCost _cycle_cost; 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; alpar@877: kpeter@767: // Infinite constant kpeter@864: const LargeCost INF; kpeter@765: kpeter@765: public: kpeter@765: kpeter@765: /// \name Named Template Parameters kpeter@765: /// @{ kpeter@765: kpeter@765: template kpeter@864: struct SetLargeCostTraits : public Traits { kpeter@864: typedef T LargeCost; kpeter@765: typedef lemon::Tolerance Tolerance; kpeter@765: }; kpeter@765: kpeter@765: /// \brief \ref named-templ-param "Named parameter" for setting kpeter@864: /// \c LargeCost type. kpeter@765: /// kpeter@864: /// \ref named-templ-param "Named parameter" for setting \c LargeCost kpeter@765: /// type. It is used for internal computations in the algorithm. kpeter@765: template kpeter@864: struct SetLargeCost kpeter@864: : public KarpMmc > { kpeter@864: typedef KarpMmc > 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@864: : public KarpMmc > { kpeter@864: typedef KarpMmc > Create; kpeter@765: }; kpeter@765: kpeter@765: /// @} kpeter@765: kpeter@863: protected: kpeter@863: kpeter@864: KarpMmc() {} kpeter@863: 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@864: /// \param cost The costs of the arcs. kpeter@864: KarpMmc( const Digraph &digraph, kpeter@864: const CostMap &cost ) : kpeter@864: _gr(digraph), _cost(cost), _comp(digraph), _out_arcs(digraph), kpeter@864: _cycle_cost(0), _cycle_size(1), _cycle_node(INVALID), kpeter@767: _cycle_path(NULL), _local_path(false), _data(digraph), kpeter@864: INF(std::numeric_limits::has_infinity ? kpeter@864: std::numeric_limits::infinity() : kpeter@864: std::numeric_limits::max()) kpeter@765: {} kpeter@765: kpeter@765: /// Destructor. kpeter@864: ~KarpMmc() { 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@864: /// \ref findCycleMean(), 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@864: KarpMmc& 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@864: KarpMmc& 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@864: /// If you only need the minimum mean cost, you may call kpeter@864: /// \ref findCycleMean(). 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@864: /// and/or the arc costs 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@864: /// return mmc.findCycleMean() && mmc.findCycle(); kpeter@765: /// \endcode kpeter@765: bool run() { kpeter@864: return findCycleMean() && findCycle(); kpeter@765: } kpeter@765: kpeter@765: /// \brief Find the minimum cycle mean. kpeter@765: /// kpeter@864: /// This function finds the minimum mean cost 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@864: bool findCycleMean() { kpeter@765: // Initialization and find strongly connected components kpeter@765: init(); kpeter@765: findComponents(); alpar@877: 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@864: /// This function finds a directed cycle of minimum mean cost kpeter@864: /// in the digraph using the data computed by findCycleMean(). kpeter@765: /// kpeter@765: /// \return \c true if a directed cycle exists in the digraph. kpeter@765: /// kpeter@864: /// \pre \ref findCycleMean() 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@864: _cycle_cost = _cost[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@864: _cycle_cost += _cost[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@864: /// \brief Return the total cost of the found cycle. kpeter@765: /// kpeter@864: /// This function returns the total cost of the found cycle. kpeter@765: /// kpeter@864: /// \pre \ref run() or \ref findCycleMean() must be called before kpeter@765: /// using this function. kpeter@864: Cost cycleCost() const { kpeter@864: return static_cast(_cycle_cost); 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@864: /// \pre \ref run() or \ref findCycleMean() must be called before kpeter@765: /// using this function. kpeter@864: int cycleSize() const { kpeter@765: return _cycle_size; kpeter@765: } kpeter@765: kpeter@864: /// \brief Return the mean cost of the found cycle. kpeter@765: /// kpeter@864: /// This function returns the mean cost 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@864: /// return static_cast(alg.cycleCost()) / alg.cycleSize(); kpeter@765: /// \endcode kpeter@765: /// kpeter@864: /// \pre \ref run() or \ref findCycleMean() must be called before kpeter@765: /// using this function. kpeter@765: double cycleMean() const { kpeter@864: return static_cast(_cycle_cost) / _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@864: _cycle_cost = 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; alpar@877: } 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@864: // _data[v][k] is the cost 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@864: LargeCost 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@864: d = _data[u][k-1].dist + _cost[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@864: LargeCost 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@864: d = _data[u][k-1].dist + _cost[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@864: LargeCost cost, max_cost = 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@864: cost = _data[u][n].dist - _data[u][k].dist; kpeter@765: size = n - k; kpeter@864: if (!found_curr || cost * max_size > max_cost * size) { kpeter@765: found_curr = true; kpeter@864: max_cost = cost; kpeter@765: max_size = size; kpeter@765: } kpeter@765: } kpeter@765: if ( found_curr && (_cycle_node == INVALID || kpeter@864: max_cost * _cycle_size < _cycle_cost * max_size) ) { kpeter@864: _cycle_cost = max_cost; kpeter@765: _cycle_size = max_size; kpeter@765: _cycle_node = u; kpeter@765: } kpeter@765: } kpeter@765: } kpeter@765: kpeter@864: }; //class KarpMmc kpeter@765: kpeter@765: ///@} kpeter@765: kpeter@765: } //namespace lemon kpeter@765: kpeter@864: #endif //LEMON_KARP_MMC_H