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 /// \addtogroup shortest_path
38 /// \brief Implementation of Howard's algorithm for finding a minimum
41 /// \ref MinMeanCycle implements Howard's algorithm for finding a
42 /// directed cycle of minimum mean length (cost) in a digraph.
44 /// \tparam GR The type of the digraph the algorithm runs on.
45 /// \tparam LEN The type of the length map. The default
46 /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
48 /// \warning \c LEN::Value must be convertible to \c double.
50 template <typename GR, typename LEN>
52 template < typename GR,
53 typename LEN = typename GR::template ArcMap<int> >
59 /// The type of the digraph the algorithm runs on
61 /// The type of the length map
62 typedef LEN LengthMap;
63 /// The type of the arc lengths
64 typedef typename LengthMap::Value Value;
65 /// The type of the paths
66 typedef lemon::Path<Digraph> Path;
70 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
72 // The digraph the algorithm runs on
74 // The length of the arcs
75 const LengthMap &_length;
77 // Data for the found cycles
78 bool _curr_found, _best_found;
79 Value _curr_length, _best_length;
80 int _curr_size, _best_size;
81 Node _curr_node, _best_node;
86 // Internal data used by the algorithm
87 typename Digraph::template NodeMap<Arc> _policy;
88 typename Digraph::template NodeMap<bool> _reached;
89 typename Digraph::template NodeMap<int> _level;
90 typename Digraph::template NodeMap<double> _dist;
92 // Data for storing the strongly connected components
94 typename Digraph::template NodeMap<int> _comp;
95 std::vector<std::vector<Node> > _comp_nodes;
96 std::vector<Node>* _nodes;
97 typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
99 // Queue used for BFS search
100 std::vector<Node> _queue;
103 Tolerance<double> _tol;
107 /// \brief Constructor.
109 /// The constructor of the class.
111 /// \param digraph The digraph the algorithm runs on.
112 /// \param length The lengths (costs) of the arcs.
113 MinMeanCycle( const Digraph &digraph,
114 const LengthMap &length ) :
115 _gr(digraph), _length(length), _cycle_path(NULL), _local_path(false),
116 _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
117 _comp(digraph), _in_arcs(digraph)
122 if (_local_path) delete _cycle_path;
125 /// \brief Set the path structure for storing the found cycle.
127 /// This function sets an external path structure for storing the
130 /// If you don't call this function before calling \ref run() or
131 /// \ref findMinMean(), it will allocate a local \ref Path "path"
132 /// structure. The destuctor deallocates this automatically
133 /// allocated object, of course.
135 /// \note The algorithm calls only the \ref lemon::Path::addBack()
136 /// "addBack()" function of the given path structure.
138 /// \return <tt>(*this)</tt>
141 MinMeanCycle& cyclePath(Path &path) {
150 /// \name Execution control
151 /// The simplest way to execute the algorithm is to call the \ref run()
153 /// If you only need the minimum mean length, you may call
154 /// \ref findMinMean().
158 /// \brief Run the algorithm.
160 /// This function runs the algorithm.
161 /// It can be called more than once (e.g. if the underlying digraph
162 /// and/or the arc lengths have been modified).
164 /// \return \c true if a directed cycle exists in the digraph.
166 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
168 /// return mmc.findMinMean() && mmc.findCycle();
171 return findMinMean() && findCycle();
174 /// \brief Find the minimum cycle mean.
176 /// This function finds the minimum mean length of the directed
177 /// cycles in the digraph.
179 /// \return \c true if a directed cycle exists in the digraph.
181 // Initialize and find strongly connected components
185 // Find the minimum cycle mean in the components
186 for (int comp = 0; comp < _comp_num; ++comp) {
187 // Find the minimum mean cycle in the current component
188 if (!buildPolicyGraph(comp)) continue;
191 if (!computeNodeDistances()) break;
193 // Update the best cycle (global minimum mean cycle)
194 if ( !_best_found || (_curr_found &&
195 _curr_length * _best_size < _best_length * _curr_size) ) {
197 _best_length = _curr_length;
198 _best_size = _curr_size;
199 _best_node = _curr_node;
205 /// \brief Find a minimum mean directed cycle.
207 /// This function finds a directed cycle of minimum mean length
208 /// in the digraph using the data computed by findMinMean().
210 /// \return \c true if a directed cycle exists in the digraph.
212 /// \pre \ref findMinMean() must be called before using this function.
214 if (!_best_found) return false;
215 _cycle_path->addBack(_policy[_best_node]);
216 for ( Node v = _best_node;
217 (v = _gr.target(_policy[v])) != _best_node; ) {
218 _cycle_path->addBack(_policy[v]);
225 /// \name Query Functions
226 /// The results of the algorithm can be obtained using these
228 /// The algorithm should be executed before using them.
232 /// \brief Return the total length of the found cycle.
234 /// This function returns the total length of the found cycle.
236 /// \pre \ref run() or \ref findMinMean() must be called before
237 /// using this function.
238 Value cycleLength() const {
242 /// \brief Return the number of arcs on the found cycle.
244 /// This function returns the number of arcs on the found cycle.
246 /// \pre \ref run() or \ref findMinMean() must be called before
247 /// using this function.
248 int cycleArcNum() const {
252 /// \brief Return the mean length of the found cycle.
254 /// This function returns the mean length of the found cycle.
256 /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
259 /// return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
262 /// \pre \ref run() or \ref findMinMean() must be called before
263 /// using this function.
264 double cycleMean() const {
265 return static_cast<double>(_best_length) / _best_size;
268 /// \brief Return the found cycle.
270 /// This function returns a const reference to the path structure
271 /// storing the found cycle.
273 /// \pre \ref run() or \ref findCycle() must be called before using
277 const Path& cycle() const {
290 _cycle_path = new Path;
292 _queue.resize(countNodes(_gr));
296 _cycle_path->clear();
299 // Find strongly connected components and initialize _comp_nodes
301 void findComponents() {
302 _comp_num = stronglyConnectedComponents(_gr, _comp);
303 _comp_nodes.resize(_comp_num);
304 if (_comp_num == 1) {
305 _comp_nodes[0].clear();
306 for (NodeIt n(_gr); n != INVALID; ++n) {
307 _comp_nodes[0].push_back(n);
309 for (InArcIt a(_gr, n); a != INVALID; ++a) {
310 _in_arcs[n].push_back(a);
314 for (int i = 0; i < _comp_num; ++i)
315 _comp_nodes[i].clear();
316 for (NodeIt n(_gr); n != INVALID; ++n) {
318 _comp_nodes[k].push_back(n);
320 for (InArcIt a(_gr, n); a != INVALID; ++a) {
321 if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
327 // Build the policy graph in the given strongly connected component
328 // (the out-degree of every node is 1)
329 bool buildPolicyGraph(int comp) {
330 _nodes = &(_comp_nodes[comp]);
331 if (_nodes->size() < 1 ||
332 (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
335 for (int i = 0; i < int(_nodes->size()); ++i) {
336 _dist[(*_nodes)[i]] = std::numeric_limits<double>::max();
340 for (int i = 0; i < int(_nodes->size()); ++i) {
342 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
345 if (_length[e] < _dist[u]) {
346 _dist[u] = _length[e];
354 // Find the minimum mean cycle in the policy graph
355 void findPolicyCycle() {
356 for (int i = 0; i < int(_nodes->size()); ++i) {
357 _level[(*_nodes)[i]] = -1;
363 for (int i = 0; i < int(_nodes->size()); ++i) {
365 if (_level[u] >= 0) continue;
366 for (; _level[u] < 0; u = _gr.target(_policy[u])) {
369 if (_level[u] == i) {
371 clength = _length[_policy[u]];
373 for (v = u; (v = _gr.target(_policy[v])) != u; ) {
374 clength += _length[_policy[v]];
378 (clength * _curr_size < _curr_length * csize) ) {
380 _curr_length = clength;
388 // Contract the policy graph and compute node distances
389 bool computeNodeDistances() {
390 // Find the component of the main cycle and compute node distances
392 for (int i = 0; i < int(_nodes->size()); ++i) {
393 _reached[(*_nodes)[i]] = false;
395 double curr_mean = double(_curr_length) / _curr_size;
396 _qfront = _qback = 0;
397 _queue[0] = _curr_node;
398 _reached[_curr_node] = true;
399 _dist[_curr_node] = 0;
402 while (_qfront <= _qback) {
403 v = _queue[_qfront++];
404 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
407 if (_policy[u] == e && !_reached[u]) {
409 _dist[u] = _dist[v] + _length[e] - curr_mean;
410 _queue[++_qback] = u;
415 // Connect all other nodes to this component and compute node
416 // distances using reverse BFS
418 while (_qback < int(_nodes->size())-1) {
419 v = _queue[_qfront++];
420 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
426 _dist[u] = _dist[v] + _length[e] - curr_mean;
427 _queue[++_qback] = u;
432 // Improve node distances
433 bool improved = false;
434 for (int i = 0; i < int(_nodes->size()); ++i) {
436 for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
439 double delta = _dist[v] + _length[e] - curr_mean;
440 if (_tol.less(delta, _dist[u])) {
450 }; //class MinMeanCycle
456 #endif //LEMON_MIN_MEAN_CYCLE_H