3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
22 /// \ingroup min_mean_cycle
25 /// \brief Karp's algorithm for finding a minimum mean cycle.
29 #include <lemon/core.h>
30 #include <lemon/path.h>
31 #include <lemon/tolerance.h>
32 #include <lemon/connectivity.h>
36 /// \brief Default traits class of Karp algorithm.
38 /// Default traits class of Karp algorithm.
39 /// \tparam GR The type of the digraph.
40 /// \tparam LEN The type of the length map.
41 /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
43 template <typename GR, typename LEN>
45 template <typename GR, typename LEN,
46 bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
48 struct KarpDefaultTraits
50 /// The type of the digraph
52 /// The type of the length map
53 typedef LEN LengthMap;
54 /// The type of the arc lengths
55 typedef typename LengthMap::Value Value;
57 /// \brief The large value type used for internal computations
59 /// The large value type used for internal computations.
60 /// It is \c long \c long if the \c Value type is integer,
61 /// otherwise it is \c double.
62 /// \c Value must be convertible to \c LargeValue.
63 typedef double LargeValue;
65 /// The tolerance type used for internal computations
66 typedef lemon::Tolerance<LargeValue> Tolerance;
68 /// \brief The path type of the found cycles
70 /// The path type of the found cycles.
71 /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 /// and it must have an \c addBack() function.
73 typedef lemon::Path<Digraph> Path;
76 // Default traits class for integer value types
77 template <typename GR, typename LEN>
78 struct KarpDefaultTraits<GR, LEN, true>
81 typedef LEN LengthMap;
82 typedef typename LengthMap::Value Value;
83 #ifdef LEMON_HAVE_LONG_LONG
84 typedef long long LargeValue;
86 typedef long LargeValue;
88 typedef lemon::Tolerance<LargeValue> Tolerance;
89 typedef lemon::Path<Digraph> Path;
93 /// \addtogroup min_mean_cycle
96 /// \brief Implementation of Karp's algorithm for finding a minimum
99 /// This class implements Karp's algorithm for finding a directed
100 /// cycle of minimum mean length (cost) in a digraph.
101 /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
103 /// \tparam GR The type of the digraph the algorithm runs on.
104 /// \tparam LEN The type of the length map. The default
105 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
107 template <typename GR, typename LEN, typename TR>
109 template < typename GR,
110 typename LEN = typename GR::template ArcMap<int>,
111 typename TR = KarpDefaultTraits<GR, LEN> >
117 /// The type of the digraph
118 typedef typename TR::Digraph Digraph;
119 /// The type of the length map
120 typedef typename TR::LengthMap LengthMap;
121 /// The type of the arc lengths
122 typedef typename TR::Value Value;
124 /// \brief The large value type
126 /// The large value type used for internal computations.
127 /// Using the \ref KarpDefaultTraits "default traits class",
128 /// it is \c long \c long if the \c Value type is integer,
129 /// otherwise it is \c double.
130 typedef typename TR::LargeValue LargeValue;
132 /// The tolerance type
133 typedef typename TR::Tolerance Tolerance;
135 /// \brief The path type of the found cycles
137 /// The path type of the found cycles.
138 /// Using the \ref KarpDefaultTraits "default traits class",
139 /// it is \ref lemon::Path "Path<Digraph>".
140 typedef typename TR::Path Path;
142 /// The \ref KarpDefaultTraits "traits class" of the algorithm
147 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
149 // Data sturcture for path data
154 PathData(LargeValue d, Arc p = INVALID) :
158 typedef typename Digraph::template NodeMap<std::vector<PathData> >
163 // The digraph the algorithm runs on
165 // The length of the arcs
166 const LengthMap &_length;
168 // Data for storing the strongly connected components
170 typename Digraph::template NodeMap<int> _comp;
171 std::vector<std::vector<Node> > _comp_nodes;
172 std::vector<Node>* _nodes;
173 typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
175 // Data for the found cycle
176 LargeValue _cycle_length;
183 // Node map for storing path data
184 PathDataNodeMap _data;
185 // The processed nodes in the last round
186 std::vector<Node> _process;
188 Tolerance _tolerance;
191 const LargeValue INF;
195 /// \name Named Template Parameters
198 template <typename T>
199 struct SetLargeValueTraits : public Traits {
200 typedef T LargeValue;
201 typedef lemon::Tolerance<T> Tolerance;
204 /// \brief \ref named-templ-param "Named parameter" for setting
205 /// \c LargeValue type.
207 /// \ref named-templ-param "Named parameter" for setting \c LargeValue
208 /// type. It is used for internal computations in the algorithm.
209 template <typename T>
211 : public Karp<GR, LEN, SetLargeValueTraits<T> > {
212 typedef Karp<GR, LEN, SetLargeValueTraits<T> > Create;
215 template <typename T>
216 struct SetPathTraits : public Traits {
220 /// \brief \ref named-templ-param "Named parameter" for setting
223 /// \ref named-templ-param "Named parameter" for setting the \c %Path
224 /// type of the found cycles.
225 /// It must conform to the \ref lemon::concepts::Path "Path" concept
226 /// and it must have an \c addFront() function.
227 template <typename T>
229 : public Karp<GR, LEN, SetPathTraits<T> > {
230 typedef Karp<GR, LEN, SetPathTraits<T> > Create;
237 /// \brief Constructor.
239 /// The constructor of the class.
241 /// \param digraph The digraph the algorithm runs on.
242 /// \param length The lengths (costs) of the arcs.
243 Karp( const Digraph &digraph,
244 const LengthMap &length ) :
245 _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
246 _cycle_length(0), _cycle_size(1), _cycle_node(INVALID),
247 _cycle_path(NULL), _local_path(false), _data(digraph),
248 INF(std::numeric_limits<LargeValue>::has_infinity ?
249 std::numeric_limits<LargeValue>::infinity() :
250 std::numeric_limits<LargeValue>::max())
255 if (_local_path) delete _cycle_path;
258 /// \brief Set the path structure for storing the found cycle.
260 /// This function sets an external path structure for storing the
263 /// If you don't call this function before calling \ref run() or
264 /// \ref findMinMean(), it will allocate a local \ref Path "path"
265 /// structure. The destuctor deallocates this automatically
266 /// allocated object, of course.
268 /// \note The algorithm calls only the \ref lemon::Path::addFront()
269 /// "addFront()" function of the given path structure.
271 /// \return <tt>(*this)</tt>
272 Karp& cycle(Path &path) {
281 /// \brief Set the tolerance used by the algorithm.
283 /// This function sets the tolerance object used by the algorithm.
285 /// \return <tt>(*this)</tt>
286 Karp& tolerance(const Tolerance& tolerance) {
287 _tolerance = tolerance;
291 /// \brief Return a const reference to the tolerance.
293 /// This function returns a const reference to the tolerance object
294 /// used by the algorithm.
295 const Tolerance& tolerance() const {
299 /// \name Execution control
300 /// The simplest way to execute the algorithm is to call the \ref run()
302 /// If you only need the minimum mean length, you may call
303 /// \ref findMinMean().
307 /// \brief Run the algorithm.
309 /// This function runs the algorithm.
310 /// It can be called more than once (e.g. if the underlying digraph
311 /// and/or the arc lengths have been modified).
313 /// \return \c true if a directed cycle exists in the digraph.
315 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
317 /// return mmc.findMinMean() && mmc.findCycle();
320 return findMinMean() && findCycle();
323 /// \brief Find the minimum cycle mean.
325 /// This function finds the minimum mean length of the directed
326 /// cycles in the digraph.
328 /// \return \c true if a directed cycle exists in the digraph.
330 // Initialization and find strongly connected components
334 // Find the minimum cycle mean in the components
335 for (int comp = 0; comp < _comp_num; ++comp) {
336 if (!initComponent(comp)) continue;
340 return (_cycle_node != INVALID);
343 /// \brief Find a minimum mean directed cycle.
345 /// This function finds a directed cycle of minimum mean length
346 /// in the digraph using the data computed by findMinMean().
348 /// \return \c true if a directed cycle exists in the digraph.
350 /// \pre \ref findMinMean() must be called before using this function.
352 if (_cycle_node == INVALID) return false;
353 IntNodeMap reached(_gr, -1);
354 int r = _data[_cycle_node].size();
355 Node u = _cycle_node;
356 while (reached[u] < 0) {
358 u = _gr.source(_data[u][r].pred);
361 Arc e = _data[u][r].pred;
362 _cycle_path->addFront(e);
363 _cycle_length = _length[e];
366 while ((v = _gr.source(e)) != u) {
367 e = _data[v][--r].pred;
368 _cycle_path->addFront(e);
369 _cycle_length += _length[e];
377 /// \name Query Functions
378 /// The results of the algorithm can be obtained using these
380 /// The algorithm should be executed before using them.
384 /// \brief Return the total length of the found cycle.
386 /// This function returns the total length of the found cycle.
388 /// \pre \ref run() or \ref findMinMean() must be called before
389 /// using this function.
390 LargeValue cycleLength() const {
391 return _cycle_length;
394 /// \brief Return the number of arcs on the found cycle.
396 /// This function returns the number of arcs on the found cycle.
398 /// \pre \ref run() or \ref findMinMean() must be called before
399 /// using this function.
400 int cycleArcNum() const {
404 /// \brief Return the mean length of the found cycle.
406 /// This function returns the mean length of the found cycle.
408 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
411 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
414 /// \pre \ref run() or \ref findMinMean() must be called before
415 /// using this function.
416 double cycleMean() const {
417 return static_cast<double>(_cycle_length) / _cycle_size;
420 /// \brief Return the found cycle.
422 /// This function returns a const reference to the path structure
423 /// storing the found cycle.
425 /// \pre \ref run() or \ref findCycle() must be called before using
427 const Path& cycle() const {
439 _cycle_path = new Path;
441 _cycle_path->clear();
444 _cycle_node = INVALID;
445 for (NodeIt u(_gr); u != INVALID; ++u)
449 // Find strongly connected components and initialize _comp_nodes
451 void findComponents() {
452 _comp_num = stronglyConnectedComponents(_gr, _comp);
453 _comp_nodes.resize(_comp_num);
454 if (_comp_num == 1) {
455 _comp_nodes[0].clear();
456 for (NodeIt n(_gr); n != INVALID; ++n) {
457 _comp_nodes[0].push_back(n);
458 _out_arcs[n].clear();
459 for (OutArcIt a(_gr, n); a != INVALID; ++a) {
460 _out_arcs[n].push_back(a);
464 for (int i = 0; i < _comp_num; ++i)
465 _comp_nodes[i].clear();
466 for (NodeIt n(_gr); n != INVALID; ++n) {
468 _comp_nodes[k].push_back(n);
469 _out_arcs[n].clear();
470 for (OutArcIt a(_gr, n); a != INVALID; ++a) {
471 if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
477 // Initialize path data for the current component
478 bool initComponent(int comp) {
479 _nodes = &(_comp_nodes[comp]);
480 int n = _nodes->size();
481 if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
484 for (int i = 0; i < n; ++i) {
485 _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
490 // Process all rounds of computing path data for the current component.
491 // _data[v][k] is the length of a shortest directed walk from the root
492 // node to node v containing exactly k arcs.
493 void processRounds() {
494 Node start = (*_nodes)[0];
495 _data[start][0] = PathData(0);
497 _process.push_back(start);
499 int k, n = _nodes->size();
500 for (k = 1; k <= n && int(_process.size()) < n; ++k) {
501 processNextBuildRound(k);
503 for ( ; k <= n; ++k) {
504 processNextFullRound(k);
508 // Process one round and rebuild _process
509 void processNextBuildRound(int k) {
510 std::vector<Node> next;
514 for (int i = 0; i < int(_process.size()); ++i) {
516 for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
519 d = _data[u][k-1].dist + _length[e];
520 if (_tolerance.less(d, _data[v][k].dist)) {
521 if (_data[v][k].dist == INF) next.push_back(v);
522 _data[v][k] = PathData(d, e);
529 // Process one round using _nodes instead of _process
530 void processNextFullRound(int k) {
534 for (int i = 0; i < int(_nodes->size()); ++i) {
536 for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
539 d = _data[u][k-1].dist + _length[e];
540 if (_tolerance.less(d, _data[v][k].dist)) {
541 _data[v][k] = PathData(d, e);
547 // Update the minimum cycle mean
548 void updateMinMean() {
549 int n = _nodes->size();
550 for (int i = 0; i < n; ++i) {
551 Node u = (*_nodes)[i];
552 if (_data[u][n].dist == INF) continue;
553 LargeValue length, max_length = 0;
554 int size, max_size = 1;
555 bool found_curr = false;
556 for (int k = 0; k < n; ++k) {
557 if (_data[u][k].dist == INF) continue;
558 length = _data[u][n].dist - _data[u][k].dist;
560 if (!found_curr || length * max_size > max_length * size) {
566 if ( found_curr && (_cycle_node == INVALID ||
567 max_length * _cycle_size < _cycle_length * max_size) ) {
568 _cycle_length = max_length;
569 _cycle_size = max_size;
581 #endif //LEMON_KARP_H