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 shortest_path
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 shortest_path
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.
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 = HowardDefaultTraits<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 HowardDefaultTraits "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 HowardDefaultTraits "default traits class",
138 /// it is \ref lemon::Path "Path<Digraph>".
139 typedef typename TR::Path Path;
141 /// The \ref HowardDefaultTraits "traits class" of the algorithm
146 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148 // The digraph the algorithm runs on
150 // The length of the arcs
151 const LengthMap &_length;
153 // Data for the found cycles
154 bool _curr_found, _best_found;
155 LargeValue _curr_length, _best_length;
156 int _curr_size, _best_size;
157 Node _curr_node, _best_node;
162 // Internal data used by the algorithm
163 typename Digraph::template NodeMap<Arc> _policy;
164 typename Digraph::template NodeMap<bool> _reached;
165 typename Digraph::template NodeMap<int> _level;
166 typename Digraph::template NodeMap<LargeValue> _dist;
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> > _in_arcs;
175 // Queue used for BFS search
176 std::vector<Node> _queue;
179 Tolerance _tolerance;
182 const LargeValue INF;
186 /// \name Named Template Parameters
189 template <typename T>
190 struct SetLargeValueTraits : public Traits {
191 typedef T LargeValue;
192 typedef lemon::Tolerance<T> Tolerance;
195 /// \brief \ref named-templ-param "Named parameter" for setting
196 /// \c LargeValue type.
198 /// \ref named-templ-param "Named parameter" for setting \c LargeValue
199 /// type. It is used for internal computations in the algorithm.
200 template <typename T>
202 : public Howard<GR, LEN, SetLargeValueTraits<T> > {
203 typedef Howard<GR, LEN, SetLargeValueTraits<T> > Create;
206 template <typename T>
207 struct SetPathTraits : public Traits {
211 /// \brief \ref named-templ-param "Named parameter" for setting
214 /// \ref named-templ-param "Named parameter" for setting the \c %Path
215 /// type of the found cycles.
216 /// It must conform to the \ref lemon::concepts::Path "Path" concept
217 /// and it must have an \c addBack() function.
218 template <typename T>
220 : public Howard<GR, LEN, SetPathTraits<T> > {
221 typedef Howard<GR, LEN, SetPathTraits<T> > Create;
228 /// \brief Constructor.
230 /// The constructor of the class.
232 /// \param digraph The digraph the algorithm runs on.
233 /// \param length The lengths (costs) of the arcs.
234 Howard( const Digraph &digraph,
235 const LengthMap &length ) :
236 _gr(digraph), _length(length), _best_found(false),
237 _best_length(0), _best_size(1), _cycle_path(NULL), _local_path(false),
238 _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
239 _comp(digraph), _in_arcs(digraph),
240 INF(std::numeric_limits<LargeValue>::has_infinity ?
241 std::numeric_limits<LargeValue>::infinity() :
242 std::numeric_limits<LargeValue>::max())
247 if (_local_path) delete _cycle_path;
250 /// \brief Set the path structure for storing the found cycle.
252 /// This function sets an external path structure for storing the
255 /// If you don't call this function before calling \ref run() or
256 /// \ref findMinMean(), it will allocate a local \ref Path "path"
257 /// structure. The destuctor deallocates this automatically
258 /// allocated object, of course.
260 /// \note The algorithm calls only the \ref lemon::Path::addBack()
261 /// "addBack()" function of the given path structure.
263 /// \return <tt>(*this)</tt>
264 Howard& cycle(Path &path) {
273 /// \name Execution control
274 /// The simplest way to execute the algorithm is to call the \ref run()
276 /// If you only need the minimum mean length, you may call
277 /// \ref findMinMean().
281 /// \brief Run the algorithm.
283 /// This function runs the algorithm.
284 /// It can be called more than once (e.g. if the underlying digraph
285 /// and/or the arc lengths have been modified).
287 /// \return \c true if a directed cycle exists in the digraph.
289 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
291 /// return mmc.findMinMean() && mmc.findCycle();
294 return findMinMean() && findCycle();
297 /// \brief Find the minimum cycle mean.
299 /// This function finds the minimum mean length of the directed
300 /// cycles in the digraph.
302 /// \return \c true if a directed cycle exists in the digraph.
304 // Initialize and find strongly connected components
308 // Find the minimum cycle mean in the components
309 for (int comp = 0; comp < _comp_num; ++comp) {
310 // Find the minimum mean cycle in the current component
311 if (!buildPolicyGraph(comp)) continue;
314 if (!computeNodeDistances()) break;
316 // Update the best cycle (global minimum mean cycle)
317 if ( _curr_found && (!_best_found ||
318 _curr_length * _best_size < _best_length * _curr_size) ) {
320 _best_length = _curr_length;
321 _best_size = _curr_size;
322 _best_node = _curr_node;
328 /// \brief Find a minimum mean directed cycle.
330 /// This function finds a directed cycle of minimum mean length
331 /// in the digraph using the data computed by findMinMean().
333 /// \return \c true if a directed cycle exists in the digraph.
335 /// \pre \ref findMinMean() must be called before using this function.
337 if (!_best_found) return false;
338 _cycle_path->addBack(_policy[_best_node]);
339 for ( Node v = _best_node;
340 (v = _gr.target(_policy[v])) != _best_node; ) {
341 _cycle_path->addBack(_policy[v]);
348 /// \name Query Functions
349 /// The results of the algorithm can be obtained using these
351 /// The algorithm should be executed before using them.
355 /// \brief Return the total length of the found cycle.
357 /// This function returns the total length of the found cycle.
359 /// \pre \ref run() or \ref findMinMean() must be called before
360 /// using this function.
361 LargeValue cycleLength() const {
365 /// \brief Return the number of arcs on the found cycle.
367 /// This function returns the number of arcs on the found cycle.
369 /// \pre \ref run() or \ref findMinMean() must be called before
370 /// using this function.
371 int cycleArcNum() const {
375 /// \brief Return the mean length of the found cycle.
377 /// This function returns the mean length of the found cycle.
379 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
382 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
385 /// \pre \ref run() or \ref findMinMean() must be called before
386 /// using this function.
387 double cycleMean() const {
388 return static_cast<double>(_best_length) / _best_size;
391 /// \brief Return the found cycle.
393 /// This function returns a const reference to the path structure
394 /// storing the found cycle.
396 /// \pre \ref run() or \ref findCycle() must be called before using
398 const Path& cycle() const {
410 _cycle_path = new Path;
412 _queue.resize(countNodes(_gr));
416 _cycle_path->clear();
419 // Find strongly connected components and initialize _comp_nodes
421 void findComponents() {
422 _comp_num = stronglyConnectedComponents(_gr, _comp);
423 _comp_nodes.resize(_comp_num);
424 if (_comp_num == 1) {
425 _comp_nodes[0].clear();
426 for (NodeIt n(_gr); n != INVALID; ++n) {
427 _comp_nodes[0].push_back(n);
429 for (InArcIt a(_gr, n); a != INVALID; ++a) {
430 _in_arcs[n].push_back(a);
434 for (int i = 0; i < _comp_num; ++i)
435 _comp_nodes[i].clear();
436 for (NodeIt n(_gr); n != INVALID; ++n) {
438 _comp_nodes[k].push_back(n);
440 for (InArcIt a(_gr, n); a != INVALID; ++a) {
441 if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
447 // Build the policy graph in the given strongly connected component
448 // (the out-degree of every node is 1)
449 bool buildPolicyGraph(int comp) {
450 _nodes = &(_comp_nodes[comp]);
451 if (_nodes->size() < 1 ||
452 (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
455 for (int i = 0; i < int(_nodes->size()); ++i) {
456 _dist[(*_nodes)[i]] = INF;
460 for (int i = 0; i < int(_nodes->size()); ++i) {
462 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
465 if (_length[e] < _dist[u]) {
466 _dist[u] = _length[e];
474 // Find the minimum mean cycle in the policy graph
475 void findPolicyCycle() {
476 for (int i = 0; i < int(_nodes->size()); ++i) {
477 _level[(*_nodes)[i]] = -1;
483 for (int i = 0; i < int(_nodes->size()); ++i) {
485 if (_level[u] >= 0) continue;
486 for (; _level[u] < 0; u = _gr.target(_policy[u])) {
489 if (_level[u] == i) {
491 clength = _length[_policy[u]];
493 for (v = u; (v = _gr.target(_policy[v])) != u; ) {
494 clength += _length[_policy[v]];
498 (clength * _curr_size < _curr_length * csize) ) {
500 _curr_length = clength;
508 // Contract the policy graph and compute node distances
509 bool computeNodeDistances() {
510 // Find the component of the main cycle and compute node distances
512 for (int i = 0; i < int(_nodes->size()); ++i) {
513 _reached[(*_nodes)[i]] = false;
515 _qfront = _qback = 0;
516 _queue[0] = _curr_node;
517 _reached[_curr_node] = true;
518 _dist[_curr_node] = 0;
521 while (_qfront <= _qback) {
522 v = _queue[_qfront++];
523 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
526 if (_policy[u] == e && !_reached[u]) {
528 _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
529 _queue[++_qback] = u;
534 // Connect all other nodes to this component and compute node
535 // distances using reverse BFS
537 while (_qback < int(_nodes->size())-1) {
538 v = _queue[_qfront++];
539 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
545 _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
546 _queue[++_qback] = u;
551 // Improve node distances
552 bool improved = false;
553 for (int i = 0; i < int(_nodes->size()); ++i) {
555 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
558 LargeValue delta = _dist[v] + _length[e] * _curr_size - _curr_length;
559 if (_tolerance.less(delta, _dist[u])) {
575 #endif //LEMON_HOWARD_H