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
19 #ifndef LEMON_HARTMANN_ORLIN_H
20 #define LEMON_HARTMANN_ORLIN_H
22 /// \ingroup shortest_path
25 /// \brief Hartmann-Orlin'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 HartmannOrlin algorithm.
38 /// Default traits class of HartmannOrlin 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::Rea_data "Rea_data" 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 HartmannOrlinDefaultTraits
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 HartmannOrlinDefaultTraits<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 the Hartmann-Orlin algorithm for finding
97 /// a minimum mean cycle.
99 /// This class implements the Hartmann-Orlin algorithm for finding
100 /// a directed cycle of minimum mean length (cost) in a digraph.
101 /// It is an improved version of \ref Karp "Karp's original algorithm",
102 /// it applies an efficient early termination scheme.
104 /// \tparam GR The type of the digraph the algorithm runs on.
105 /// \tparam LEN The type of the length map. The default
106 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
108 template <typename GR, typename LEN, typename TR>
110 template < typename GR,
111 typename LEN = typename GR::template ArcMap<int>,
112 typename TR = HartmannOrlinDefaultTraits<GR, LEN> >
118 /// The type of the digraph
119 typedef typename TR::Digraph Digraph;
120 /// The type of the length map
121 typedef typename TR::LengthMap LengthMap;
122 /// The type of the arc lengths
123 typedef typename TR::Value Value;
125 /// \brief The large value type
127 /// The large value type used for internal computations.
128 /// Using the \ref HartmannOrlinDefaultTraits "default traits class",
129 /// it is \c long \c long if the \c Value type is integer,
130 /// otherwise it is \c double.
131 typedef typename TR::LargeValue LargeValue;
133 /// The tolerance type
134 typedef typename TR::Tolerance Tolerance;
136 /// \brief The path type of the found cycles
138 /// The path type of the found cycles.
139 /// Using the \ref HartmannOrlinDefaultTraits "default traits class",
140 /// it is \ref lemon::Path "Path<Digraph>".
141 typedef typename TR::Path Path;
143 /// The \ref HartmannOrlinDefaultTraits "traits class" of the algorithm
148 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
150 // Data sturcture for path data
155 PathData(LargeValue d, Arc p = INVALID) :
159 typedef typename Digraph::template NodeMap<std::vector<PathData> >
164 // The digraph the algorithm runs on
166 // The length of the arcs
167 const LengthMap &_length;
169 // Data for storing the strongly connected components
171 typename Digraph::template NodeMap<int> _comp;
172 std::vector<std::vector<Node> > _comp_nodes;
173 std::vector<Node>* _nodes;
174 typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
176 // Data for the found cycles
177 bool _curr_found, _best_found;
178 LargeValue _curr_length, _best_length;
179 int _curr_size, _best_size;
180 Node _curr_node, _best_node;
181 int _curr_level, _best_level;
186 // Node map for storing path data
187 PathDataNodeMap _data;
188 // The processed nodes in the last round
189 std::vector<Node> _process;
191 Tolerance _tolerance;
194 const LargeValue INF;
198 /// \name Named Template Parameters
201 template <typename T>
202 struct SetLargeValueTraits : public Traits {
203 typedef T LargeValue;
204 typedef lemon::Tolerance<T> Tolerance;
207 /// \brief \ref named-templ-param "Named parameter" for setting
208 /// \c LargeValue type.
210 /// \ref named-templ-param "Named parameter" for setting \c LargeValue
211 /// type. It is used for internal computations in the algorithm.
212 template <typename T>
214 : public HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > {
215 typedef HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > Create;
218 template <typename T>
219 struct SetPathTraits : public Traits {
223 /// \brief \ref named-templ-param "Named parameter" for setting
226 /// \ref named-templ-param "Named parameter" for setting the \c %Path
227 /// type of the found cycles.
228 /// It must conform to the \ref lemon::concepts::Path "Path" concept
229 /// and it must have an \c addFront() function.
230 template <typename T>
232 : public HartmannOrlin<GR, LEN, SetPathTraits<T> > {
233 typedef HartmannOrlin<GR, LEN, SetPathTraits<T> > Create;
240 /// \brief Constructor.
242 /// The constructor of the class.
244 /// \param digraph The digraph the algorithm runs on.
245 /// \param length The lengths (costs) of the arcs.
246 HartmannOrlin( const Digraph &digraph,
247 const LengthMap &length ) :
248 _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
249 _best_found(false), _best_length(0), _best_size(1),
250 _cycle_path(NULL), _local_path(false), _data(digraph),
251 INF(std::numeric_limits<LargeValue>::has_infinity ?
252 std::numeric_limits<LargeValue>::infinity() :
253 std::numeric_limits<LargeValue>::max())
258 if (_local_path) delete _cycle_path;
261 /// \brief Set the path structure for storing the found cycle.
263 /// This function sets an external path structure for storing the
266 /// If you don't call this function before calling \ref run() or
267 /// \ref findMinMean(), it will allocate a local \ref Path "path"
268 /// structure. The destuctor deallocates this automatically
269 /// allocated object, of course.
271 /// \note The algorithm calls only the \ref lemon::Path::addFront()
272 /// "addFront()" function of the given path structure.
274 /// \return <tt>(*this)</tt>
275 HartmannOrlin& cycle(Path &path) {
284 /// \name Execution control
285 /// The simplest way to execute the algorithm is to call the \ref run()
287 /// If you only need the minimum mean length, you may call
288 /// \ref findMinMean().
292 /// \brief Run the algorithm.
294 /// This function runs the algorithm.
295 /// It can be called more than once (e.g. if the underlying digraph
296 /// and/or the arc lengths have been modified).
298 /// \return \c true if a directed cycle exists in the digraph.
300 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
302 /// return mmc.findMinMean() && mmc.findCycle();
305 return findMinMean() && findCycle();
308 /// \brief Find the minimum cycle mean.
310 /// This function finds the minimum mean length of the directed
311 /// cycles in the digraph.
313 /// \return \c true if a directed cycle exists in the digraph.
315 // Initialization and find strongly connected components
319 // Find the minimum cycle mean in the components
320 for (int comp = 0; comp < _comp_num; ++comp) {
321 if (!initComponent(comp)) continue;
324 // Update the best cycle (global minimum mean cycle)
325 if ( _curr_found && (!_best_found ||
326 _curr_length * _best_size < _best_length * _curr_size) ) {
328 _best_length = _curr_length;
329 _best_size = _curr_size;
330 _best_node = _curr_node;
331 _best_level = _curr_level;
337 /// \brief Find a minimum mean directed cycle.
339 /// This function finds a directed cycle of minimum mean length
340 /// in the digraph using the data computed by findMinMean().
342 /// \return \c true if a directed cycle exists in the digraph.
344 /// \pre \ref findMinMean() must be called before using this function.
346 if (!_best_found) return false;
347 IntNodeMap reached(_gr, -1);
348 int r = _best_level + 1;
350 while (reached[u] < 0) {
352 u = _gr.source(_data[u][r].pred);
355 Arc e = _data[u][r].pred;
356 _cycle_path->addFront(e);
357 _best_length = _length[e];
360 while ((v = _gr.source(e)) != u) {
361 e = _data[v][--r].pred;
362 _cycle_path->addFront(e);
363 _best_length += _length[e];
371 /// \name Query Functions
372 /// The results of the algorithm can be obtained using these
374 /// The algorithm should be executed before using them.
378 /// \brief Return the total length of the found cycle.
380 /// This function returns the total length of the found cycle.
382 /// \pre \ref run() or \ref findMinMean() must be called before
383 /// using this function.
384 LargeValue cycleLength() const {
388 /// \brief Return the number of arcs on the found cycle.
390 /// This function returns the number of arcs on the found cycle.
392 /// \pre \ref run() or \ref findMinMean() must be called before
393 /// using this function.
394 int cycleArcNum() const {
398 /// \brief Return the mean length of the found cycle.
400 /// This function returns the mean length of the found cycle.
402 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
405 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
408 /// \pre \ref run() or \ref findMinMean() must be called before
409 /// using this function.
410 double cycleMean() const {
411 return static_cast<double>(_best_length) / _best_size;
414 /// \brief Return the found cycle.
416 /// This function returns a const reference to the path structure
417 /// storing the found cycle.
419 /// \pre \ref run() or \ref findCycle() must be called before using
421 const Path& cycle() const {
433 _cycle_path = new Path;
435 _cycle_path->clear();
439 _cycle_path->clear();
440 for (NodeIt u(_gr); u != INVALID; ++u)
444 // Find strongly connected components and initialize _comp_nodes
446 void findComponents() {
447 _comp_num = stronglyConnectedComponents(_gr, _comp);
448 _comp_nodes.resize(_comp_num);
449 if (_comp_num == 1) {
450 _comp_nodes[0].clear();
451 for (NodeIt n(_gr); n != INVALID; ++n) {
452 _comp_nodes[0].push_back(n);
453 _out_arcs[n].clear();
454 for (OutArcIt a(_gr, n); a != INVALID; ++a) {
455 _out_arcs[n].push_back(a);
459 for (int i = 0; i < _comp_num; ++i)
460 _comp_nodes[i].clear();
461 for (NodeIt n(_gr); n != INVALID; ++n) {
463 _comp_nodes[k].push_back(n);
464 _out_arcs[n].clear();
465 for (OutArcIt a(_gr, n); a != INVALID; ++a) {
466 if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
472 // Initialize path data for the current component
473 bool initComponent(int comp) {
474 _nodes = &(_comp_nodes[comp]);
475 int n = _nodes->size();
476 if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
479 for (int i = 0; i < n; ++i) {
480 _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
485 // Process all rounds of computing path data for the current component.
486 // _data[v][k] is the length of a shortest directed walk from the root
487 // node to node v containing exactly k arcs.
488 void processRounds() {
489 Node start = (*_nodes)[0];
490 _data[start][0] = PathData(0);
492 _process.push_back(start);
494 int k, n = _nodes->size();
496 bool terminate = false;
497 for (k = 1; k <= n && int(_process.size()) < n && !terminate; ++k) {
498 processNextBuildRound(k);
499 if (k == next_check || k == n) {
500 terminate = checkTermination(k);
501 next_check = next_check * 3 / 2;
504 for ( ; k <= n && !terminate; ++k) {
505 processNextFullRound(k);
506 if (k == next_check || k == n) {
507 terminate = checkTermination(k);
508 next_check = next_check * 3 / 2;
513 // Process one round and rebuild _process
514 void processNextBuildRound(int k) {
515 std::vector<Node> next;
519 for (int i = 0; i < int(_process.size()); ++i) {
521 for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
524 d = _data[u][k-1].dist + _length[e];
525 if (_tolerance.less(d, _data[v][k].dist)) {
526 if (_data[v][k].dist == INF) next.push_back(v);
527 _data[v][k] = PathData(d, e);
534 // Process one round using _nodes instead of _process
535 void processNextFullRound(int k) {
539 for (int i = 0; i < int(_nodes->size()); ++i) {
541 for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
544 d = _data[u][k-1].dist + _length[e];
545 if (_tolerance.less(d, _data[v][k].dist)) {
546 _data[v][k] = PathData(d, e);
552 // Check early termination
553 bool checkTermination(int k) {
554 typedef std::pair<int, int> Pair;
555 typename GR::template NodeMap<Pair> level(_gr, Pair(-1, 0));
556 typename GR::template NodeMap<LargeValue> pi(_gr);
557 int n = _nodes->size();
562 // Search for cycles that are already found
564 for (int i = 0; i < n; ++i) {
566 if (_data[u][k].dist == INF) continue;
567 for (int j = k; j >= 0; --j) {
568 if (level[u].first == i && level[u].second > 0) {
570 length = _data[u][level[u].second].dist - _data[u][j].dist;
571 size = level[u].second - j;
572 if (!_curr_found || length * _curr_size < _curr_length * size) {
573 _curr_length = length;
576 _curr_level = level[u].second;
580 level[u] = Pair(i, j);
581 u = _gr.source(_data[u][j].pred);
585 // If at least one cycle is found, check the optimality condition
587 if (_curr_found && k < n) {
588 // Find node potentials
589 for (int i = 0; i < n; ++i) {
592 for (int j = 0; j <= k; ++j) {
593 if (_data[u][j].dist < INF) {
594 d = _data[u][j].dist * _curr_size - j * _curr_length;
595 if (_tolerance.less(d, pi[u])) pi[u] = d;
600 // Check the optimality condition for all arcs
602 for (ArcIt a(_gr); a != INVALID; ++a) {
603 if (_tolerance.less(_length[a] * _curr_size - _curr_length,
604 pi[_gr.target(a)] - pi[_gr.source(a)]) ) {
614 }; //class HartmannOrlin
620 #endif //LEMON_HARTMANN_ORLIN_H