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