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_MIN_MEAN_CYCLE_H
20 #define LEMON_MIN_MEAN_CYCLE_H
22 /// \ingroup shortest_path
25 /// \brief Howard's algorithm for finding a minimum mean cycle.
28 #include <lemon/core.h>
29 #include <lemon/path.h>
30 #include <lemon/tolerance.h>
31 #include <lemon/connectivity.h>
35 /// \brief Default traits class of MinMeanCycle class.
37 /// Default traits class of MinMeanCycle class.
38 /// \tparam GR The type of the digraph.
39 /// \tparam LEN The type of the length map.
40 /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
42 template <typename GR, typename LEN>
44 template <typename GR, typename LEN,
45 bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 struct MinMeanCycleDefaultTraits
49 /// The type of the digraph
51 /// The type of the length map
52 typedef LEN LengthMap;
53 /// The type of the arc lengths
54 typedef typename LengthMap::Value Value;
56 /// \brief The large value type used for internal computations
58 /// The large value type used for internal computations.
59 /// It is \c long \c long if the \c Value type is integer,
60 /// otherwise it is \c double.
61 /// \c Value must be convertible to \c LargeValue.
62 typedef double LargeValue;
64 /// The tolerance type used for internal computations
65 typedef lemon::Tolerance<LargeValue> Tolerance;
67 /// \brief The path type of the found cycles
69 /// The path type of the found cycles.
70 /// It must conform to the \ref lemon::concepts::Path "Path" concept
71 /// and it must have an \c addBack() function.
72 typedef lemon::Path<Digraph> Path;
75 // Default traits class for integer value types
76 template <typename GR, typename LEN>
77 struct MinMeanCycleDefaultTraits<GR, LEN, true>
80 typedef LEN LengthMap;
81 typedef typename LengthMap::Value Value;
82 #ifdef LEMON_HAVE_LONG_LONG
83 typedef long long LargeValue;
85 typedef long LargeValue;
87 typedef lemon::Tolerance<LargeValue> Tolerance;
88 typedef lemon::Path<Digraph> Path;
92 /// \addtogroup shortest_path
95 /// \brief Implementation of Howard's algorithm for finding a minimum
98 /// \ref MinMeanCycle implements Howard's algorithm for finding a
99 /// directed cycle of minimum mean length (cost) in a digraph.
101 /// \tparam GR The type of the digraph the algorithm runs on.
102 /// \tparam LEN The type of the length map. The default
103 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
105 template <typename GR, typename LEN, typename TR>
107 template < typename GR,
108 typename LEN = typename GR::template ArcMap<int>,
109 typename TR = MinMeanCycleDefaultTraits<GR, LEN> >
115 /// The type of the digraph
116 typedef typename TR::Digraph Digraph;
117 /// The type of the length map
118 typedef typename TR::LengthMap LengthMap;
119 /// The type of the arc lengths
120 typedef typename TR::Value Value;
122 /// \brief The large value type
124 /// The large value type used for internal computations.
125 /// Using the \ref MinMeanCycleDefaultTraits "default traits class",
126 /// it is \c long \c long if the \c Value type is integer,
127 /// otherwise it is \c double.
128 typedef typename TR::LargeValue LargeValue;
130 /// The tolerance type
131 typedef typename TR::Tolerance Tolerance;
133 /// \brief The path type of the found cycles
135 /// The path type of the found cycles.
136 /// Using the \ref MinMeanCycleDefaultTraits "default traits class",
137 /// it is \ref lemon::Path "Path<Digraph>".
138 typedef typename TR::Path Path;
140 /// The \ref MinMeanCycleDefaultTraits "traits class" of the algorithm
145 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
147 // The digraph the algorithm runs on
149 // The length of the arcs
150 const LengthMap &_length;
152 // Data for the found cycles
153 bool _curr_found, _best_found;
154 LargeValue _curr_length, _best_length;
155 int _curr_size, _best_size;
156 Node _curr_node, _best_node;
161 // Internal data used by the algorithm
162 typename Digraph::template NodeMap<Arc> _policy;
163 typename Digraph::template NodeMap<bool> _reached;
164 typename Digraph::template NodeMap<int> _level;
165 typename Digraph::template NodeMap<LargeValue> _dist;
167 // Data for storing the strongly connected components
169 typename Digraph::template NodeMap<int> _comp;
170 std::vector<std::vector<Node> > _comp_nodes;
171 std::vector<Node>* _nodes;
172 typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
174 // Queue used for BFS search
175 std::vector<Node> _queue;
178 Tolerance _tolerance;
182 /// \name Named Template Parameters
185 template <typename T>
186 struct SetLargeValueTraits : public Traits {
187 typedef T LargeValue;
188 typedef lemon::Tolerance<T> Tolerance;
191 /// \brief \ref named-templ-param "Named parameter" for setting
192 /// \c LargeValue type.
194 /// \ref named-templ-param "Named parameter" for setting \c LargeValue
195 /// type. It is used for internal computations in the algorithm.
196 template <typename T>
198 : public MinMeanCycle<GR, LEN, SetLargeValueTraits<T> > {
199 typedef MinMeanCycle<GR, LEN, SetLargeValueTraits<T> > Create;
202 template <typename T>
203 struct SetPathTraits : public Traits {
207 /// \brief \ref named-templ-param "Named parameter" for setting
210 /// \ref named-templ-param "Named parameter" for setting the \c %Path
211 /// type of the found cycles.
212 /// It must conform to the \ref lemon::concepts::Path "Path" concept
213 /// and it must have an \c addBack() function.
214 template <typename T>
216 : public MinMeanCycle<GR, LEN, SetPathTraits<T> > {
217 typedef MinMeanCycle<GR, LEN, SetPathTraits<T> > Create;
224 /// \brief Constructor.
226 /// The constructor of the class.
228 /// \param digraph The digraph the algorithm runs on.
229 /// \param length The lengths (costs) of the arcs.
230 MinMeanCycle( const Digraph &digraph,
231 const LengthMap &length ) :
232 _gr(digraph), _length(length), _cycle_path(NULL), _local_path(false),
233 _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
234 _comp(digraph), _in_arcs(digraph)
239 if (_local_path) delete _cycle_path;
242 /// \brief Set the path structure for storing the found cycle.
244 /// This function sets an external path structure for storing the
247 /// If you don't call this function before calling \ref run() or
248 /// \ref findMinMean(), it will allocate a local \ref Path "path"
249 /// structure. The destuctor deallocates this automatically
250 /// allocated object, of course.
252 /// \note The algorithm calls only the \ref lemon::Path::addBack()
253 /// "addBack()" function of the given path structure.
255 /// \return <tt>(*this)</tt>
258 MinMeanCycle& cyclePath(Path &path) {
267 /// \name Execution control
268 /// The simplest way to execute the algorithm is to call the \ref run()
270 /// If you only need the minimum mean length, you may call
271 /// \ref findMinMean().
275 /// \brief Run the algorithm.
277 /// This function runs the algorithm.
278 /// It can be called more than once (e.g. if the underlying digraph
279 /// and/or the arc lengths have been modified).
281 /// \return \c true if a directed cycle exists in the digraph.
283 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
285 /// return mmc.findMinMean() && mmc.findCycle();
288 return findMinMean() && findCycle();
291 /// \brief Find the minimum cycle mean.
293 /// This function finds the minimum mean length of the directed
294 /// cycles in the digraph.
296 /// \return \c true if a directed cycle exists in the digraph.
298 // Initialize and find strongly connected components
302 // Find the minimum cycle mean in the components
303 for (int comp = 0; comp < _comp_num; ++comp) {
304 // Find the minimum mean cycle in the current component
305 if (!buildPolicyGraph(comp)) continue;
308 if (!computeNodeDistances()) break;
310 // Update the best cycle (global minimum mean cycle)
311 if ( !_best_found || (_curr_found &&
312 _curr_length * _best_size < _best_length * _curr_size) ) {
314 _best_length = _curr_length;
315 _best_size = _curr_size;
316 _best_node = _curr_node;
322 /// \brief Find a minimum mean directed cycle.
324 /// This function finds a directed cycle of minimum mean length
325 /// in the digraph using the data computed by findMinMean().
327 /// \return \c true if a directed cycle exists in the digraph.
329 /// \pre \ref findMinMean() must be called before using this function.
331 if (!_best_found) return false;
332 _cycle_path->addBack(_policy[_best_node]);
333 for ( Node v = _best_node;
334 (v = _gr.target(_policy[v])) != _best_node; ) {
335 _cycle_path->addBack(_policy[v]);
342 /// \name Query Functions
343 /// The results of the algorithm can be obtained using these
345 /// The algorithm should be executed before using them.
349 /// \brief Return the total length of the found cycle.
351 /// This function returns the total length of the found cycle.
353 /// \pre \ref run() or \ref findMinMean() must be called before
354 /// using this function.
355 LargeValue cycleLength() const {
359 /// \brief Return the number of arcs on the found cycle.
361 /// This function returns the number of arcs on the found cycle.
363 /// \pre \ref run() or \ref findMinMean() must be called before
364 /// using this function.
365 int cycleArcNum() const {
369 /// \brief Return the mean length of the found cycle.
371 /// This function returns the mean length of the found cycle.
373 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
376 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
379 /// \pre \ref run() or \ref findMinMean() must be called before
380 /// using this function.
381 double cycleMean() const {
382 return static_cast<double>(_best_length) / _best_size;
385 /// \brief Return the found cycle.
387 /// This function returns a const reference to the path structure
388 /// storing the found cycle.
390 /// \pre \ref run() or \ref findCycle() must be called before using
394 const Path& cycle() const {
406 _cycle_path = new Path;
408 _queue.resize(countNodes(_gr));
412 _cycle_path->clear();
415 // Find strongly connected components and initialize _comp_nodes
417 void findComponents() {
418 _comp_num = stronglyConnectedComponents(_gr, _comp);
419 _comp_nodes.resize(_comp_num);
420 if (_comp_num == 1) {
421 _comp_nodes[0].clear();
422 for (NodeIt n(_gr); n != INVALID; ++n) {
423 _comp_nodes[0].push_back(n);
425 for (InArcIt a(_gr, n); a != INVALID; ++a) {
426 _in_arcs[n].push_back(a);
430 for (int i = 0; i < _comp_num; ++i)
431 _comp_nodes[i].clear();
432 for (NodeIt n(_gr); n != INVALID; ++n) {
434 _comp_nodes[k].push_back(n);
436 for (InArcIt a(_gr, n); a != INVALID; ++a) {
437 if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
443 // Build the policy graph in the given strongly connected component
444 // (the out-degree of every node is 1)
445 bool buildPolicyGraph(int comp) {
446 _nodes = &(_comp_nodes[comp]);
447 if (_nodes->size() < 1 ||
448 (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
451 for (int i = 0; i < int(_nodes->size()); ++i) {
452 _dist[(*_nodes)[i]] = std::numeric_limits<LargeValue>::max();
456 for (int i = 0; i < int(_nodes->size()); ++i) {
458 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
461 if (_length[e] < _dist[u]) {
462 _dist[u] = _length[e];
470 // Find the minimum mean cycle in the policy graph
471 void findPolicyCycle() {
472 for (int i = 0; i < int(_nodes->size()); ++i) {
473 _level[(*_nodes)[i]] = -1;
479 for (int i = 0; i < int(_nodes->size()); ++i) {
481 if (_level[u] >= 0) continue;
482 for (; _level[u] < 0; u = _gr.target(_policy[u])) {
485 if (_level[u] == i) {
487 clength = _length[_policy[u]];
489 for (v = u; (v = _gr.target(_policy[v])) != u; ) {
490 clength += _length[_policy[v]];
494 (clength * _curr_size < _curr_length * csize) ) {
496 _curr_length = clength;
504 // Contract the policy graph and compute node distances
505 bool computeNodeDistances() {
506 // Find the component of the main cycle and compute node distances
508 for (int i = 0; i < int(_nodes->size()); ++i) {
509 _reached[(*_nodes)[i]] = false;
511 _qfront = _qback = 0;
512 _queue[0] = _curr_node;
513 _reached[_curr_node] = true;
514 _dist[_curr_node] = 0;
517 while (_qfront <= _qback) {
518 v = _queue[_qfront++];
519 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
522 if (_policy[u] == e && !_reached[u]) {
524 _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
525 _queue[++_qback] = u;
530 // Connect all other nodes to this component and compute node
531 // distances using reverse BFS
533 while (_qback < int(_nodes->size())-1) {
534 v = _queue[_qfront++];
535 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
541 _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
542 _queue[++_qback] = u;
547 // Improve node distances
548 bool improved = false;
549 for (int i = 0; i < int(_nodes->size()); ++i) {
551 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
554 LargeValue delta = _dist[v] + _length[e] * _curr_size - _curr_length;
555 if (_tolerance.less(delta, _dist[u])) {
565 }; //class MinMeanCycle
571 #endif //LEMON_MIN_MEAN_CYCLE_H