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 shortest_path
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 shortest_path
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.
102 /// \tparam GR The type of the digraph the algorithm runs on.
103 /// \tparam LEN The type of the length map. The default
104 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
106 template <typename GR, typename LEN, typename TR>
108 template < typename GR,
109 typename LEN = typename GR::template ArcMap<int>,
110 typename TR = KarpDefaultTraits<GR, LEN> >
116 /// The type of the digraph
117 typedef typename TR::Digraph Digraph;
118 /// The type of the length map
119 typedef typename TR::LengthMap LengthMap;
120 /// The type of the arc lengths
121 typedef typename TR::Value Value;
123 /// \brief The large value type
125 /// The large value type used for internal computations.
126 /// Using the \ref KarpDefaultTraits "default traits class",
127 /// it is \c long \c long if the \c Value type is integer,
128 /// otherwise it is \c double.
129 typedef typename TR::LargeValue LargeValue;
131 /// The tolerance type
132 typedef typename TR::Tolerance Tolerance;
134 /// \brief The path type of the found cycles
136 /// The path type of the found cycles.
137 /// Using the \ref KarpDefaultTraits "default traits class",
138 /// it is \ref lemon::Path "Path<Digraph>".
139 typedef typename TR::Path Path;
141 /// The \ref KarpDefaultTraits "traits class" of the algorithm
146 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148 // Data sturcture for path data
154 PathData(bool f = false, LargeValue d = 0, Arc p = INVALID) :
155 found(f), dist(d), pred(p) {}
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;
192 /// \name Named Template Parameters
195 template <typename T>
196 struct SetLargeValueTraits : public Traits {
197 typedef T LargeValue;
198 typedef lemon::Tolerance<T> Tolerance;
201 /// \brief \ref named-templ-param "Named parameter" for setting
202 /// \c LargeValue type.
204 /// \ref named-templ-param "Named parameter" for setting \c LargeValue
205 /// type. It is used for internal computations in the algorithm.
206 template <typename T>
208 : public Karp<GR, LEN, SetLargeValueTraits<T> > {
209 typedef Karp<GR, LEN, SetLargeValueTraits<T> > Create;
212 template <typename T>
213 struct SetPathTraits : public Traits {
217 /// \brief \ref named-templ-param "Named parameter" for setting
220 /// \ref named-templ-param "Named parameter" for setting the \c %Path
221 /// type of the found cycles.
222 /// It must conform to the \ref lemon::concepts::Path "Path" concept
223 /// and it must have an \c addFront() function.
224 template <typename T>
226 : public Karp<GR, LEN, SetPathTraits<T> > {
227 typedef Karp<GR, LEN, SetPathTraits<T> > Create;
234 /// \brief Constructor.
236 /// The constructor of the class.
238 /// \param digraph The digraph the algorithm runs on.
239 /// \param length The lengths (costs) of the arcs.
240 Karp( const Digraph &digraph,
241 const LengthMap &length ) :
242 _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
243 _cycle_length(0), _cycle_size(1), _cycle_node(INVALID),
244 _cycle_path(NULL), _local_path(false), _data(digraph)
249 if (_local_path) delete _cycle_path;
252 /// \brief Set the path structure for storing the found cycle.
254 /// This function sets an external path structure for storing the
257 /// If you don't call this function before calling \ref run() or
258 /// \ref findMinMean(), it will allocate a local \ref Path "path"
259 /// structure. The destuctor deallocates this automatically
260 /// allocated object, of course.
262 /// \note The algorithm calls only the \ref lemon::Path::addFront()
263 /// "addFront()" function of the given path structure.
265 /// \return <tt>(*this)</tt>
266 Karp& cycle(Path &path) {
275 /// \name Execution control
276 /// The simplest way to execute the algorithm is to call the \ref run()
278 /// If you only need the minimum mean length, you may call
279 /// \ref findMinMean().
283 /// \brief Run the algorithm.
285 /// This function runs the algorithm.
286 /// It can be called more than once (e.g. if the underlying digraph
287 /// and/or the arc lengths have been modified).
289 /// \return \c true if a directed cycle exists in the digraph.
291 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
293 /// return mmc.findMinMean() && mmc.findCycle();
296 return findMinMean() && findCycle();
299 /// \brief Find the minimum cycle mean.
301 /// This function finds the minimum mean length of the directed
302 /// cycles in the digraph.
304 /// \return \c true if a directed cycle exists in the digraph.
306 // Initialization and find strongly connected components
310 // Find the minimum cycle mean in the components
311 for (int comp = 0; comp < _comp_num; ++comp) {
312 if (!initComponent(comp)) continue;
316 return (_cycle_node != INVALID);
319 /// \brief Find a minimum mean directed cycle.
321 /// This function finds a directed cycle of minimum mean length
322 /// in the digraph using the data computed by findMinMean().
324 /// \return \c true if a directed cycle exists in the digraph.
326 /// \pre \ref findMinMean() must be called before using this function.
328 if (_cycle_node == INVALID) return false;
329 IntNodeMap reached(_gr, -1);
330 int r = _data[_cycle_node].size();
331 Node u = _cycle_node;
332 while (reached[u] < 0) {
334 u = _gr.source(_data[u][r].pred);
337 Arc e = _data[u][r].pred;
338 _cycle_path->addFront(e);
339 _cycle_length = _length[e];
342 while ((v = _gr.source(e)) != u) {
343 e = _data[v][--r].pred;
344 _cycle_path->addFront(e);
345 _cycle_length += _length[e];
353 /// \name Query Functions
354 /// The results of the algorithm can be obtained using these
356 /// The algorithm should be executed before using them.
360 /// \brief Return the total length of the found cycle.
362 /// This function returns the total length of the found cycle.
364 /// \pre \ref run() or \ref findMinMean() must be called before
365 /// using this function.
366 LargeValue cycleLength() const {
367 return _cycle_length;
370 /// \brief Return the number of arcs on the found cycle.
372 /// This function returns the number of arcs on the found cycle.
374 /// \pre \ref run() or \ref findMinMean() must be called before
375 /// using this function.
376 int cycleArcNum() const {
380 /// \brief Return the mean length of the found cycle.
382 /// This function returns the mean length of the found cycle.
384 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
387 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
390 /// \pre \ref run() or \ref findMinMean() must be called before
391 /// using this function.
392 double cycleMean() const {
393 return static_cast<double>(_cycle_length) / _cycle_size;
396 /// \brief Return the found cycle.
398 /// This function returns a const reference to the path structure
399 /// storing the found cycle.
401 /// \pre \ref run() or \ref findCycle() must be called before using
403 const Path& cycle() const {
415 _cycle_path = new Path;
417 _cycle_path->clear();
420 _cycle_node = INVALID;
421 for (NodeIt u(_gr); u != INVALID; ++u)
425 // Find strongly connected components and initialize _comp_nodes
427 void findComponents() {
428 _comp_num = stronglyConnectedComponents(_gr, _comp);
429 _comp_nodes.resize(_comp_num);
430 if (_comp_num == 1) {
431 _comp_nodes[0].clear();
432 for (NodeIt n(_gr); n != INVALID; ++n) {
433 _comp_nodes[0].push_back(n);
434 _out_arcs[n].clear();
435 for (OutArcIt a(_gr, n); a != INVALID; ++a) {
436 _out_arcs[n].push_back(a);
440 for (int i = 0; i < _comp_num; ++i)
441 _comp_nodes[i].clear();
442 for (NodeIt n(_gr); n != INVALID; ++n) {
444 _comp_nodes[k].push_back(n);
445 _out_arcs[n].clear();
446 for (OutArcIt a(_gr, n); a != INVALID; ++a) {
447 if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
453 // Initialize path data for the current component
454 bool initComponent(int comp) {
455 _nodes = &(_comp_nodes[comp]);
456 int n = _nodes->size();
457 if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
460 for (int i = 0; i < n; ++i) {
461 _data[(*_nodes)[i]].resize(n + 1);
466 // Process all rounds of computing path data for the current component.
467 // _data[v][k] is the length of a shortest directed walk from the root
468 // node to node v containing exactly k arcs.
469 void processRounds() {
470 Node start = (*_nodes)[0];
471 _data[start][0] = PathData(true, 0);
473 _process.push_back(start);
475 int k, n = _nodes->size();
476 for (k = 1; k <= n && int(_process.size()) < n; ++k) {
477 processNextBuildRound(k);
479 for ( ; k <= n; ++k) {
480 processNextFullRound(k);
484 // Process one round and rebuild _process
485 void processNextBuildRound(int k) {
486 std::vector<Node> next;
490 for (int i = 0; i < int(_process.size()); ++i) {
492 for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
495 d = _data[u][k-1].dist + _length[e];
496 if (!_data[v][k].found) {
498 _data[v][k] = PathData(true, _data[u][k-1].dist + _length[e], e);
500 else if (_tolerance.less(d, _data[v][k].dist)) {
501 _data[v][k] = PathData(true, d, e);
508 // Process one round using _nodes instead of _process
509 void processNextFullRound(int k) {
513 for (int i = 0; i < int(_nodes->size()); ++i) {
515 for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
518 d = _data[u][k-1].dist + _length[e];
519 if (!_data[v][k].found || _tolerance.less(d, _data[v][k].dist)) {
520 _data[v][k] = PathData(true, d, e);
526 // Update the minimum cycle mean
527 void updateMinMean() {
528 int n = _nodes->size();
529 for (int i = 0; i < n; ++i) {
530 Node u = (*_nodes)[i];
531 if (!_data[u][n].found) continue;
532 LargeValue length, max_length = 0;
533 int size, max_size = 1;
534 bool found_curr = false;
535 for (int k = 0; k < n; ++k) {
536 if (!_data[u][k].found) continue;
537 length = _data[u][n].dist - _data[u][k].dist;
539 if (!found_curr || length * max_size > max_length * size) {
545 if ( found_curr && (_cycle_node == INVALID ||
546 max_length * _cycle_size < _cycle_length * max_size) ) {
547 _cycle_length = max_length;
548 _cycle_size = max_size;
560 #endif //LEMON_KARP_H