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