1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/lemon/karp_mmc.h Tue Dec 20 18:15:14 2011 +0100
1.3 @@ -0,0 +1,590 @@
1.4 +/* -*- mode: C++; indent-tabs-mode: nil; -*-
1.5 + *
1.6 + * This file is a part of LEMON, a generic C++ optimization library.
1.7 + *
1.8 + * Copyright (C) 2003-2010
1.9 + * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
1.10 + * (Egervary Research Group on Combinatorial Optimization, EGRES).
1.11 + *
1.12 + * Permission to use, modify and distribute this software is granted
1.13 + * provided that this copyright notice appears in all copies. For
1.14 + * precise terms see the accompanying LICENSE file.
1.15 + *
1.16 + * This software is provided "AS IS" with no warranty of any kind,
1.17 + * express or implied, and with no claim as to its suitability for any
1.18 + * purpose.
1.19 + *
1.20 + */
1.21 +
1.22 +#ifndef LEMON_KARP_MMC_H
1.23 +#define LEMON_KARP_MMC_H
1.24 +
1.25 +/// \ingroup min_mean_cycle
1.26 +///
1.27 +/// \file
1.28 +/// \brief Karp's algorithm for finding a minimum mean cycle.
1.29 +
1.30 +#include <vector>
1.31 +#include <limits>
1.32 +#include <lemon/core.h>
1.33 +#include <lemon/path.h>
1.34 +#include <lemon/tolerance.h>
1.35 +#include <lemon/connectivity.h>
1.36 +
1.37 +namespace lemon {
1.38 +
1.39 + /// \brief Default traits class of KarpMmc class.
1.40 + ///
1.41 + /// Default traits class of KarpMmc class.
1.42 + /// \tparam GR The type of the digraph.
1.43 + /// \tparam CM The type of the cost map.
1.44 + /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
1.45 +#ifdef DOXYGEN
1.46 + template <typename GR, typename CM>
1.47 +#else
1.48 + template <typename GR, typename CM,
1.49 + bool integer = std::numeric_limits<typename CM::Value>::is_integer>
1.50 +#endif
1.51 + struct KarpMmcDefaultTraits
1.52 + {
1.53 + /// The type of the digraph
1.54 + typedef GR Digraph;
1.55 + /// The type of the cost map
1.56 + typedef CM CostMap;
1.57 + /// The type of the arc costs
1.58 + typedef typename CostMap::Value Cost;
1.59 +
1.60 + /// \brief The large cost type used for internal computations
1.61 + ///
1.62 + /// The large cost type used for internal computations.
1.63 + /// It is \c long \c long if the \c Cost type is integer,
1.64 + /// otherwise it is \c double.
1.65 + /// \c Cost must be convertible to \c LargeCost.
1.66 + typedef double LargeCost;
1.67 +
1.68 + /// The tolerance type used for internal computations
1.69 + typedef lemon::Tolerance<LargeCost> Tolerance;
1.70 +
1.71 + /// \brief The path type of the found cycles
1.72 + ///
1.73 + /// The path type of the found cycles.
1.74 + /// It must conform to the \ref lemon::concepts::Path "Path" concept
1.75 + /// and it must have an \c addFront() function.
1.76 + typedef lemon::Path<Digraph> Path;
1.77 + };
1.78 +
1.79 + // Default traits class for integer cost types
1.80 + template <typename GR, typename CM>
1.81 + struct KarpMmcDefaultTraits<GR, CM, true>
1.82 + {
1.83 + typedef GR Digraph;
1.84 + typedef CM CostMap;
1.85 + typedef typename CostMap::Value Cost;
1.86 +#ifdef LEMON_HAVE_LONG_LONG
1.87 + typedef long long LargeCost;
1.88 +#else
1.89 + typedef long LargeCost;
1.90 +#endif
1.91 + typedef lemon::Tolerance<LargeCost> Tolerance;
1.92 + typedef lemon::Path<Digraph> Path;
1.93 + };
1.94 +
1.95 +
1.96 + /// \addtogroup min_mean_cycle
1.97 + /// @{
1.98 +
1.99 + /// \brief Implementation of Karp's algorithm for finding a minimum
1.100 + /// mean cycle.
1.101 + ///
1.102 + /// This class implements Karp's algorithm for finding a directed
1.103 + /// cycle of minimum mean cost in a digraph
1.104 + /// \ref amo93networkflows, \ref dasdan98minmeancycle.
1.105 + /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
1.106 + ///
1.107 + /// \tparam GR The type of the digraph the algorithm runs on.
1.108 + /// \tparam CM The type of the cost map. The default
1.109 + /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
1.110 + /// \tparam TR The traits class that defines various types used by the
1.111 + /// algorithm. By default, it is \ref KarpMmcDefaultTraits
1.112 + /// "KarpMmcDefaultTraits<GR, CM>".
1.113 + /// In most cases, this parameter should not be set directly,
1.114 + /// consider to use the named template parameters instead.
1.115 +#ifdef DOXYGEN
1.116 + template <typename GR, typename CM, typename TR>
1.117 +#else
1.118 + template < typename GR,
1.119 + typename CM = typename GR::template ArcMap<int>,
1.120 + typename TR = KarpMmcDefaultTraits<GR, CM> >
1.121 +#endif
1.122 + class KarpMmc
1.123 + {
1.124 + public:
1.125 +
1.126 + /// The type of the digraph
1.127 + typedef typename TR::Digraph Digraph;
1.128 + /// The type of the cost map
1.129 + typedef typename TR::CostMap CostMap;
1.130 + /// The type of the arc costs
1.131 + typedef typename TR::Cost Cost;
1.132 +
1.133 + /// \brief The large cost type
1.134 + ///
1.135 + /// The large cost type used for internal computations.
1.136 + /// By default, it is \c long \c long if the \c Cost type is integer,
1.137 + /// otherwise it is \c double.
1.138 + typedef typename TR::LargeCost LargeCost;
1.139 +
1.140 + /// The tolerance type
1.141 + typedef typename TR::Tolerance Tolerance;
1.142 +
1.143 + /// \brief The path type of the found cycles
1.144 + ///
1.145 + /// The path type of the found cycles.
1.146 + /// Using the \ref KarpMmcDefaultTraits "default traits class",
1.147 + /// it is \ref lemon::Path "Path<Digraph>".
1.148 + typedef typename TR::Path Path;
1.149 +
1.150 + /// The \ref KarpMmcDefaultTraits "traits class" of the algorithm
1.151 + typedef TR Traits;
1.152 +
1.153 + private:
1.154 +
1.155 + TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
1.156 +
1.157 + // Data sturcture for path data
1.158 + struct PathData
1.159 + {
1.160 + LargeCost dist;
1.161 + Arc pred;
1.162 + PathData(LargeCost d, Arc p = INVALID) :
1.163 + dist(d), pred(p) {}
1.164 + };
1.165 +
1.166 + typedef typename Digraph::template NodeMap<std::vector<PathData> >
1.167 + PathDataNodeMap;
1.168 +
1.169 + private:
1.170 +
1.171 + // The digraph the algorithm runs on
1.172 + const Digraph &_gr;
1.173 + // The cost of the arcs
1.174 + const CostMap &_cost;
1.175 +
1.176 + // Data for storing the strongly connected components
1.177 + int _comp_num;
1.178 + typename Digraph::template NodeMap<int> _comp;
1.179 + std::vector<std::vector<Node> > _comp_nodes;
1.180 + std::vector<Node>* _nodes;
1.181 + typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
1.182 +
1.183 + // Data for the found cycle
1.184 + LargeCost _cycle_cost;
1.185 + int _cycle_size;
1.186 + Node _cycle_node;
1.187 +
1.188 + Path *_cycle_path;
1.189 + bool _local_path;
1.190 +
1.191 + // Node map for storing path data
1.192 + PathDataNodeMap _data;
1.193 + // The processed nodes in the last round
1.194 + std::vector<Node> _process;
1.195 +
1.196 + Tolerance _tolerance;
1.197 +
1.198 + // Infinite constant
1.199 + const LargeCost INF;
1.200 +
1.201 + public:
1.202 +
1.203 + /// \name Named Template Parameters
1.204 + /// @{
1.205 +
1.206 + template <typename T>
1.207 + struct SetLargeCostTraits : public Traits {
1.208 + typedef T LargeCost;
1.209 + typedef lemon::Tolerance<T> Tolerance;
1.210 + };
1.211 +
1.212 + /// \brief \ref named-templ-param "Named parameter" for setting
1.213 + /// \c LargeCost type.
1.214 + ///
1.215 + /// \ref named-templ-param "Named parameter" for setting \c LargeCost
1.216 + /// type. It is used for internal computations in the algorithm.
1.217 + template <typename T>
1.218 + struct SetLargeCost
1.219 + : public KarpMmc<GR, CM, SetLargeCostTraits<T> > {
1.220 + typedef KarpMmc<GR, CM, SetLargeCostTraits<T> > Create;
1.221 + };
1.222 +
1.223 + template <typename T>
1.224 + struct SetPathTraits : public Traits {
1.225 + typedef T Path;
1.226 + };
1.227 +
1.228 + /// \brief \ref named-templ-param "Named parameter" for setting
1.229 + /// \c %Path type.
1.230 + ///
1.231 + /// \ref named-templ-param "Named parameter" for setting the \c %Path
1.232 + /// type of the found cycles.
1.233 + /// It must conform to the \ref lemon::concepts::Path "Path" concept
1.234 + /// and it must have an \c addFront() function.
1.235 + template <typename T>
1.236 + struct SetPath
1.237 + : public KarpMmc<GR, CM, SetPathTraits<T> > {
1.238 + typedef KarpMmc<GR, CM, SetPathTraits<T> > Create;
1.239 + };
1.240 +
1.241 + /// @}
1.242 +
1.243 + protected:
1.244 +
1.245 + KarpMmc() {}
1.246 +
1.247 + public:
1.248 +
1.249 + /// \brief Constructor.
1.250 + ///
1.251 + /// The constructor of the class.
1.252 + ///
1.253 + /// \param digraph The digraph the algorithm runs on.
1.254 + /// \param cost The costs of the arcs.
1.255 + KarpMmc( const Digraph &digraph,
1.256 + const CostMap &cost ) :
1.257 + _gr(digraph), _cost(cost), _comp(digraph), _out_arcs(digraph),
1.258 + _cycle_cost(0), _cycle_size(1), _cycle_node(INVALID),
1.259 + _cycle_path(NULL), _local_path(false), _data(digraph),
1.260 + INF(std::numeric_limits<LargeCost>::has_infinity ?
1.261 + std::numeric_limits<LargeCost>::infinity() :
1.262 + std::numeric_limits<LargeCost>::max())
1.263 + {}
1.264 +
1.265 + /// Destructor.
1.266 + ~KarpMmc() {
1.267 + if (_local_path) delete _cycle_path;
1.268 + }
1.269 +
1.270 + /// \brief Set the path structure for storing the found cycle.
1.271 + ///
1.272 + /// This function sets an external path structure for storing the
1.273 + /// found cycle.
1.274 + ///
1.275 + /// If you don't call this function before calling \ref run() or
1.276 + /// \ref findCycleMean(), it will allocate a local \ref Path "path"
1.277 + /// structure. The destuctor deallocates this automatically
1.278 + /// allocated object, of course.
1.279 + ///
1.280 + /// \note The algorithm calls only the \ref lemon::Path::addFront()
1.281 + /// "addFront()" function of the given path structure.
1.282 + ///
1.283 + /// \return <tt>(*this)</tt>
1.284 + KarpMmc& cycle(Path &path) {
1.285 + if (_local_path) {
1.286 + delete _cycle_path;
1.287 + _local_path = false;
1.288 + }
1.289 + _cycle_path = &path;
1.290 + return *this;
1.291 + }
1.292 +
1.293 + /// \brief Set the tolerance used by the algorithm.
1.294 + ///
1.295 + /// This function sets the tolerance object used by the algorithm.
1.296 + ///
1.297 + /// \return <tt>(*this)</tt>
1.298 + KarpMmc& tolerance(const Tolerance& tolerance) {
1.299 + _tolerance = tolerance;
1.300 + return *this;
1.301 + }
1.302 +
1.303 + /// \brief Return a const reference to the tolerance.
1.304 + ///
1.305 + /// This function returns a const reference to the tolerance object
1.306 + /// used by the algorithm.
1.307 + const Tolerance& tolerance() const {
1.308 + return _tolerance;
1.309 + }
1.310 +
1.311 + /// \name Execution control
1.312 + /// The simplest way to execute the algorithm is to call the \ref run()
1.313 + /// function.\n
1.314 + /// If you only need the minimum mean cost, you may call
1.315 + /// \ref findCycleMean().
1.316 +
1.317 + /// @{
1.318 +
1.319 + /// \brief Run the algorithm.
1.320 + ///
1.321 + /// This function runs the algorithm.
1.322 + /// It can be called more than once (e.g. if the underlying digraph
1.323 + /// and/or the arc costs have been modified).
1.324 + ///
1.325 + /// \return \c true if a directed cycle exists in the digraph.
1.326 + ///
1.327 + /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
1.328 + /// \code
1.329 + /// return mmc.findCycleMean() && mmc.findCycle();
1.330 + /// \endcode
1.331 + bool run() {
1.332 + return findCycleMean() && findCycle();
1.333 + }
1.334 +
1.335 + /// \brief Find the minimum cycle mean.
1.336 + ///
1.337 + /// This function finds the minimum mean cost of the directed
1.338 + /// cycles in the digraph.
1.339 + ///
1.340 + /// \return \c true if a directed cycle exists in the digraph.
1.341 + bool findCycleMean() {
1.342 + // Initialization and find strongly connected components
1.343 + init();
1.344 + findComponents();
1.345 +
1.346 + // Find the minimum cycle mean in the components
1.347 + for (int comp = 0; comp < _comp_num; ++comp) {
1.348 + if (!initComponent(comp)) continue;
1.349 + processRounds();
1.350 + updateMinMean();
1.351 + }
1.352 + return (_cycle_node != INVALID);
1.353 + }
1.354 +
1.355 + /// \brief Find a minimum mean directed cycle.
1.356 + ///
1.357 + /// This function finds a directed cycle of minimum mean cost
1.358 + /// in the digraph using the data computed by findCycleMean().
1.359 + ///
1.360 + /// \return \c true if a directed cycle exists in the digraph.
1.361 + ///
1.362 + /// \pre \ref findCycleMean() must be called before using this function.
1.363 + bool findCycle() {
1.364 + if (_cycle_node == INVALID) return false;
1.365 + IntNodeMap reached(_gr, -1);
1.366 + int r = _data[_cycle_node].size();
1.367 + Node u = _cycle_node;
1.368 + while (reached[u] < 0) {
1.369 + reached[u] = --r;
1.370 + u = _gr.source(_data[u][r].pred);
1.371 + }
1.372 + r = reached[u];
1.373 + Arc e = _data[u][r].pred;
1.374 + _cycle_path->addFront(e);
1.375 + _cycle_cost = _cost[e];
1.376 + _cycle_size = 1;
1.377 + Node v;
1.378 + while ((v = _gr.source(e)) != u) {
1.379 + e = _data[v][--r].pred;
1.380 + _cycle_path->addFront(e);
1.381 + _cycle_cost += _cost[e];
1.382 + ++_cycle_size;
1.383 + }
1.384 + return true;
1.385 + }
1.386 +
1.387 + /// @}
1.388 +
1.389 + /// \name Query Functions
1.390 + /// The results of the algorithm can be obtained using these
1.391 + /// functions.\n
1.392 + /// The algorithm should be executed before using them.
1.393 +
1.394 + /// @{
1.395 +
1.396 + /// \brief Return the total cost of the found cycle.
1.397 + ///
1.398 + /// This function returns the total cost of the found cycle.
1.399 + ///
1.400 + /// \pre \ref run() or \ref findCycleMean() must be called before
1.401 + /// using this function.
1.402 + Cost cycleCost() const {
1.403 + return static_cast<Cost>(_cycle_cost);
1.404 + }
1.405 +
1.406 + /// \brief Return the number of arcs on the found cycle.
1.407 + ///
1.408 + /// This function returns the number of arcs on the found cycle.
1.409 + ///
1.410 + /// \pre \ref run() or \ref findCycleMean() must be called before
1.411 + /// using this function.
1.412 + int cycleSize() const {
1.413 + return _cycle_size;
1.414 + }
1.415 +
1.416 + /// \brief Return the mean cost of the found cycle.
1.417 + ///
1.418 + /// This function returns the mean cost of the found cycle.
1.419 + ///
1.420 + /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
1.421 + /// following code.
1.422 + /// \code
1.423 + /// return static_cast<double>(alg.cycleCost()) / alg.cycleSize();
1.424 + /// \endcode
1.425 + ///
1.426 + /// \pre \ref run() or \ref findCycleMean() must be called before
1.427 + /// using this function.
1.428 + double cycleMean() const {
1.429 + return static_cast<double>(_cycle_cost) / _cycle_size;
1.430 + }
1.431 +
1.432 + /// \brief Return the found cycle.
1.433 + ///
1.434 + /// This function returns a const reference to the path structure
1.435 + /// storing the found cycle.
1.436 + ///
1.437 + /// \pre \ref run() or \ref findCycle() must be called before using
1.438 + /// this function.
1.439 + const Path& cycle() const {
1.440 + return *_cycle_path;
1.441 + }
1.442 +
1.443 + ///@}
1.444 +
1.445 + private:
1.446 +
1.447 + // Initialization
1.448 + void init() {
1.449 + if (!_cycle_path) {
1.450 + _local_path = true;
1.451 + _cycle_path = new Path;
1.452 + }
1.453 + _cycle_path->clear();
1.454 + _cycle_cost = 0;
1.455 + _cycle_size = 1;
1.456 + _cycle_node = INVALID;
1.457 + for (NodeIt u(_gr); u != INVALID; ++u)
1.458 + _data[u].clear();
1.459 + }
1.460 +
1.461 + // Find strongly connected components and initialize _comp_nodes
1.462 + // and _out_arcs
1.463 + void findComponents() {
1.464 + _comp_num = stronglyConnectedComponents(_gr, _comp);
1.465 + _comp_nodes.resize(_comp_num);
1.466 + if (_comp_num == 1) {
1.467 + _comp_nodes[0].clear();
1.468 + for (NodeIt n(_gr); n != INVALID; ++n) {
1.469 + _comp_nodes[0].push_back(n);
1.470 + _out_arcs[n].clear();
1.471 + for (OutArcIt a(_gr, n); a != INVALID; ++a) {
1.472 + _out_arcs[n].push_back(a);
1.473 + }
1.474 + }
1.475 + } else {
1.476 + for (int i = 0; i < _comp_num; ++i)
1.477 + _comp_nodes[i].clear();
1.478 + for (NodeIt n(_gr); n != INVALID; ++n) {
1.479 + int k = _comp[n];
1.480 + _comp_nodes[k].push_back(n);
1.481 + _out_arcs[n].clear();
1.482 + for (OutArcIt a(_gr, n); a != INVALID; ++a) {
1.483 + if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
1.484 + }
1.485 + }
1.486 + }
1.487 + }
1.488 +
1.489 + // Initialize path data for the current component
1.490 + bool initComponent(int comp) {
1.491 + _nodes = &(_comp_nodes[comp]);
1.492 + int n = _nodes->size();
1.493 + if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
1.494 + return false;
1.495 + }
1.496 + for (int i = 0; i < n; ++i) {
1.497 + _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
1.498 + }
1.499 + return true;
1.500 + }
1.501 +
1.502 + // Process all rounds of computing path data for the current component.
1.503 + // _data[v][k] is the cost of a shortest directed walk from the root
1.504 + // node to node v containing exactly k arcs.
1.505 + void processRounds() {
1.506 + Node start = (*_nodes)[0];
1.507 + _data[start][0] = PathData(0);
1.508 + _process.clear();
1.509 + _process.push_back(start);
1.510 +
1.511 + int k, n = _nodes->size();
1.512 + for (k = 1; k <= n && int(_process.size()) < n; ++k) {
1.513 + processNextBuildRound(k);
1.514 + }
1.515 + for ( ; k <= n; ++k) {
1.516 + processNextFullRound(k);
1.517 + }
1.518 + }
1.519 +
1.520 + // Process one round and rebuild _process
1.521 + void processNextBuildRound(int k) {
1.522 + std::vector<Node> next;
1.523 + Node u, v;
1.524 + Arc e;
1.525 + LargeCost d;
1.526 + for (int i = 0; i < int(_process.size()); ++i) {
1.527 + u = _process[i];
1.528 + for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
1.529 + e = _out_arcs[u][j];
1.530 + v = _gr.target(e);
1.531 + d = _data[u][k-1].dist + _cost[e];
1.532 + if (_tolerance.less(d, _data[v][k].dist)) {
1.533 + if (_data[v][k].dist == INF) next.push_back(v);
1.534 + _data[v][k] = PathData(d, e);
1.535 + }
1.536 + }
1.537 + }
1.538 + _process.swap(next);
1.539 + }
1.540 +
1.541 + // Process one round using _nodes instead of _process
1.542 + void processNextFullRound(int k) {
1.543 + Node u, v;
1.544 + Arc e;
1.545 + LargeCost d;
1.546 + for (int i = 0; i < int(_nodes->size()); ++i) {
1.547 + u = (*_nodes)[i];
1.548 + for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
1.549 + e = _out_arcs[u][j];
1.550 + v = _gr.target(e);
1.551 + d = _data[u][k-1].dist + _cost[e];
1.552 + if (_tolerance.less(d, _data[v][k].dist)) {
1.553 + _data[v][k] = PathData(d, e);
1.554 + }
1.555 + }
1.556 + }
1.557 + }
1.558 +
1.559 + // Update the minimum cycle mean
1.560 + void updateMinMean() {
1.561 + int n = _nodes->size();
1.562 + for (int i = 0; i < n; ++i) {
1.563 + Node u = (*_nodes)[i];
1.564 + if (_data[u][n].dist == INF) continue;
1.565 + LargeCost cost, max_cost = 0;
1.566 + int size, max_size = 1;
1.567 + bool found_curr = false;
1.568 + for (int k = 0; k < n; ++k) {
1.569 + if (_data[u][k].dist == INF) continue;
1.570 + cost = _data[u][n].dist - _data[u][k].dist;
1.571 + size = n - k;
1.572 + if (!found_curr || cost * max_size > max_cost * size) {
1.573 + found_curr = true;
1.574 + max_cost = cost;
1.575 + max_size = size;
1.576 + }
1.577 + }
1.578 + if ( found_curr && (_cycle_node == INVALID ||
1.579 + max_cost * _cycle_size < _cycle_cost * max_size) ) {
1.580 + _cycle_cost = max_cost;
1.581 + _cycle_size = max_size;
1.582 + _cycle_node = u;
1.583 + }
1.584 + }
1.585 + }
1.586 +
1.587 + }; //class KarpMmc
1.588 +
1.589 + ///@}
1.590 +
1.591 +} //namespace lemon
1.592 +
1.593 +#endif //LEMON_KARP_MMC_H