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_HOWARD_H
20 #define LEMON_HOWARD_H
22 /// \ingroup min_mean_cycle
25 /// \brief Howard'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 Howard class.
38 /// Default traits class of Howard class.
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 HowardDefaultTraits
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 HowardDefaultTraits<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 Howard's algorithm for finding a minimum
99 /// This class implements Howard's policy iteration algorithm for finding
100 /// a directed cycle of minimum mean length (cost) in a digraph
101 /// \ref amo93networkflows, \ref dasdan98minmeancycle.
102 /// This class provides the most efficient algorithm for the
103 /// minimum mean cycle problem, though the best known theoretical
104 /// bound on its running time is exponential.
106 /// \tparam GR The type of the digraph the algorithm runs on.
107 /// \tparam LEN The type of the length map. The default
108 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
109 /// \tparam TR The traits class that defines various types used by the
110 /// algorithm. By default, it is \ref HowardDefaultTraits
111 /// "HowardDefaultTraits<GR, LEN>".
112 /// In most cases, this parameter should not be set directly,
113 /// consider to use the named template parameters instead.
115 template <typename GR, typename LEN, typename TR>
117 template < typename GR,
118 typename LEN = typename GR::template ArcMap<int>,
119 typename TR = HowardDefaultTraits<GR, LEN> >
125 /// The type of the digraph
126 typedef typename TR::Digraph Digraph;
127 /// The type of the length map
128 typedef typename TR::LengthMap LengthMap;
129 /// The type of the arc lengths
130 typedef typename TR::Value Value;
132 /// \brief The large value type
134 /// The large value type used for internal computations.
135 /// By default, it is \c long \c long if the \c Value type is integer,
136 /// otherwise it is \c double.
137 typedef typename TR::LargeValue LargeValue;
139 /// The tolerance type
140 typedef typename TR::Tolerance Tolerance;
142 /// \brief The path type of the found cycles
144 /// The path type of the found cycles.
145 /// Using the \ref HowardDefaultTraits "default traits class",
146 /// it is \ref lemon::Path "Path<Digraph>".
147 typedef typename TR::Path Path;
149 /// The \ref HowardDefaultTraits "traits class" of the algorithm
154 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
156 // The digraph the algorithm runs on
158 // The length of the arcs
159 const LengthMap &_length;
161 // Data for the found cycles
162 bool _curr_found, _best_found;
163 LargeValue _curr_length, _best_length;
164 int _curr_size, _best_size;
165 Node _curr_node, _best_node;
170 // Internal data used by the algorithm
171 typename Digraph::template NodeMap<Arc> _policy;
172 typename Digraph::template NodeMap<bool> _reached;
173 typename Digraph::template NodeMap<int> _level;
174 typename Digraph::template NodeMap<LargeValue> _dist;
176 // Data for storing the strongly connected components
178 typename Digraph::template NodeMap<int> _comp;
179 std::vector<std::vector<Node> > _comp_nodes;
180 std::vector<Node>* _nodes;
181 typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
183 // Queue used for BFS search
184 std::vector<Node> _queue;
187 Tolerance _tolerance;
190 const LargeValue INF;
194 /// \name Named Template Parameters
197 template <typename T>
198 struct SetLargeValueTraits : public Traits {
199 typedef T LargeValue;
200 typedef lemon::Tolerance<T> Tolerance;
203 /// \brief \ref named-templ-param "Named parameter" for setting
204 /// \c LargeValue type.
206 /// \ref named-templ-param "Named parameter" for setting \c LargeValue
207 /// type. It is used for internal computations in the algorithm.
208 template <typename T>
210 : public Howard<GR, LEN, SetLargeValueTraits<T> > {
211 typedef Howard<GR, LEN, SetLargeValueTraits<T> > Create;
214 template <typename T>
215 struct SetPathTraits : public Traits {
219 /// \brief \ref named-templ-param "Named parameter" for setting
222 /// \ref named-templ-param "Named parameter" for setting the \c %Path
223 /// type of the found cycles.
224 /// It must conform to the \ref lemon::concepts::Path "Path" concept
225 /// and it must have an \c addBack() function.
226 template <typename T>
228 : public Howard<GR, LEN, SetPathTraits<T> > {
229 typedef Howard<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 Howard( const Digraph &digraph,
247 const LengthMap &length ) :
248 _gr(digraph), _length(length), _best_found(false),
249 _best_length(0), _best_size(1), _cycle_path(NULL), _local_path(false),
250 _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
251 _comp(digraph), _in_arcs(digraph),
252 INF(std::numeric_limits<LargeValue>::has_infinity ?
253 std::numeric_limits<LargeValue>::infinity() :
254 std::numeric_limits<LargeValue>::max())
259 if (_local_path) delete _cycle_path;
262 /// \brief Set the path structure for storing the found cycle.
264 /// This function sets an external path structure for storing the
267 /// If you don't call this function before calling \ref run() or
268 /// \ref findMinMean(), it will allocate a local \ref Path "path"
269 /// structure. The destuctor deallocates this automatically
270 /// allocated object, of course.
272 /// \note The algorithm calls only the \ref lemon::Path::addBack()
273 /// "addBack()" function of the given path structure.
275 /// \return <tt>(*this)</tt>
276 Howard& cycle(Path &path) {
285 /// \brief Set the tolerance used by the algorithm.
287 /// This function sets the tolerance object used by the algorithm.
289 /// \return <tt>(*this)</tt>
290 Howard& tolerance(const Tolerance& tolerance) {
291 _tolerance = tolerance;
295 /// \brief Return a const reference to the tolerance.
297 /// This function returns a const reference to the tolerance object
298 /// used by the algorithm.
299 const Tolerance& tolerance() const {
303 /// \name Execution control
304 /// The simplest way to execute the algorithm is to call the \ref run()
306 /// If you only need the minimum mean length, you may call
307 /// \ref findMinMean().
311 /// \brief Run the algorithm.
313 /// This function runs the algorithm.
314 /// It can be called more than once (e.g. if the underlying digraph
315 /// and/or the arc lengths have been modified).
317 /// \return \c true if a directed cycle exists in the digraph.
319 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
321 /// return mmc.findMinMean() && mmc.findCycle();
324 return findMinMean() && findCycle();
327 /// \brief Find the minimum cycle mean.
329 /// This function finds the minimum mean length of the directed
330 /// cycles in the digraph.
332 /// \return \c true if a directed cycle exists in the digraph.
334 // Initialize and find strongly connected components
338 // Find the minimum cycle mean in the components
339 for (int comp = 0; comp < _comp_num; ++comp) {
340 // Find the minimum mean cycle in the current component
341 if (!buildPolicyGraph(comp)) continue;
344 if (!computeNodeDistances()) break;
346 // Update the best cycle (global minimum mean cycle)
347 if ( _curr_found && (!_best_found ||
348 _curr_length * _best_size < _best_length * _curr_size) ) {
350 _best_length = _curr_length;
351 _best_size = _curr_size;
352 _best_node = _curr_node;
358 /// \brief Find a minimum mean directed cycle.
360 /// This function finds a directed cycle of minimum mean length
361 /// in the digraph using the data computed by findMinMean().
363 /// \return \c true if a directed cycle exists in the digraph.
365 /// \pre \ref findMinMean() must be called before using this function.
367 if (!_best_found) return false;
368 _cycle_path->addBack(_policy[_best_node]);
369 for ( Node v = _best_node;
370 (v = _gr.target(_policy[v])) != _best_node; ) {
371 _cycle_path->addBack(_policy[v]);
378 /// \name Query Functions
379 /// The results of the algorithm can be obtained using these
381 /// The algorithm should be executed before using them.
385 /// \brief Return the total length of the found cycle.
387 /// This function returns the total length of the found cycle.
389 /// \pre \ref run() or \ref findMinMean() must be called before
390 /// using this function.
391 Value cycleLength() const {
392 return static_cast<Value>(_best_length);
395 /// \brief Return the number of arcs on the found cycle.
397 /// This function returns the number of arcs on the found cycle.
399 /// \pre \ref run() or \ref findMinMean() must be called before
400 /// using this function.
401 int cycleArcNum() const {
405 /// \brief Return the mean length of the found cycle.
407 /// This function returns the mean length of the found cycle.
409 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
412 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
415 /// \pre \ref run() or \ref findMinMean() must be called before
416 /// using this function.
417 double cycleMean() const {
418 return static_cast<double>(_best_length) / _best_size;
421 /// \brief Return the found cycle.
423 /// This function returns a const reference to the path structure
424 /// storing the found cycle.
426 /// \pre \ref run() or \ref findCycle() must be called before using
428 const Path& cycle() const {
440 _cycle_path = new Path;
442 _queue.resize(countNodes(_gr));
446 _cycle_path->clear();
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);
459 for (InArcIt a(_gr, n); a != INVALID; ++a) {
460 _in_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);
470 for (InArcIt a(_gr, n); a != INVALID; ++a) {
471 if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
477 // Build the policy graph in the given strongly connected component
478 // (the out-degree of every node is 1)
479 bool buildPolicyGraph(int comp) {
480 _nodes = &(_comp_nodes[comp]);
481 if (_nodes->size() < 1 ||
482 (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
485 for (int i = 0; i < int(_nodes->size()); ++i) {
486 _dist[(*_nodes)[i]] = INF;
490 for (int i = 0; i < int(_nodes->size()); ++i) {
492 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
495 if (_length[e] < _dist[u]) {
496 _dist[u] = _length[e];
504 // Find the minimum mean cycle in the policy graph
505 void findPolicyCycle() {
506 for (int i = 0; i < int(_nodes->size()); ++i) {
507 _level[(*_nodes)[i]] = -1;
513 for (int i = 0; i < int(_nodes->size()); ++i) {
515 if (_level[u] >= 0) continue;
516 for (; _level[u] < 0; u = _gr.target(_policy[u])) {
519 if (_level[u] == i) {
521 clength = _length[_policy[u]];
523 for (v = u; (v = _gr.target(_policy[v])) != u; ) {
524 clength += _length[_policy[v]];
528 (clength * _curr_size < _curr_length * csize) ) {
530 _curr_length = clength;
538 // Contract the policy graph and compute node distances
539 bool computeNodeDistances() {
540 // Find the component of the main cycle and compute node distances
542 for (int i = 0; i < int(_nodes->size()); ++i) {
543 _reached[(*_nodes)[i]] = false;
545 _qfront = _qback = 0;
546 _queue[0] = _curr_node;
547 _reached[_curr_node] = true;
548 _dist[_curr_node] = 0;
551 while (_qfront <= _qback) {
552 v = _queue[_qfront++];
553 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
556 if (_policy[u] == e && !_reached[u]) {
558 _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
559 _queue[++_qback] = u;
564 // Connect all other nodes to this component and compute node
565 // distances using reverse BFS
567 while (_qback < int(_nodes->size())-1) {
568 v = _queue[_qfront++];
569 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
575 _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
576 _queue[++_qback] = u;
581 // Improve node distances
582 bool improved = false;
583 for (int i = 0; i < int(_nodes->size()); ++i) {
585 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
588 LargeValue delta = _dist[v] + _length[e] * _curr_size - _curr_length;
589 if (_tolerance.less(delta, _dist[u])) {
605 #endif //LEMON_HOWARD_H