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 // The total length of the found cycle
79 // The number of arcs on the found cycle
88 typename Digraph::template NodeMap<bool> _reached;
89 typename Digraph::template NodeMap<double> _dist;
90 typename Digraph::template NodeMap<Arc> _policy;
92 typename Digraph::template NodeMap<int> _comp;
95 std::vector<Node> _nodes;
96 std::vector<Arc> _arcs;
97 Tolerance<double> _tol;
101 /// \brief Constructor.
103 /// The constructor of the class.
105 /// \param digraph The digraph the algorithm runs on.
106 /// \param length The lengths (costs) of the arcs.
107 MinMeanCycle( const Digraph &digraph,
108 const LengthMap &length ) :
109 _gr(digraph), _length(length), _cycle_length(0), _cycle_size(-1),
110 _cycle_path(NULL), _local_path(false), _reached(digraph),
111 _dist(digraph), _policy(digraph), _comp(digraph)
116 if (_local_path) delete _cycle_path;
119 /// \brief Set the path structure for storing the found cycle.
121 /// This function sets an external path structure for storing the
124 /// If you don't call this function before calling \ref run() or
125 /// \ref findMinMean(), it will allocate a local \ref Path "path"
126 /// structure. The destuctor deallocates this automatically
127 /// allocated object, of course.
129 /// \note The algorithm calls only the \ref lemon::Path::addBack()
130 /// "addBack()" function of the given path structure.
132 /// \return <tt>(*this)</tt>
135 MinMeanCycle& cyclePath(Path &path) {
144 /// \name Execution control
145 /// The simplest way to execute the algorithm is to call the \ref run()
147 /// If you only need the minimum mean length, you may call
148 /// \ref findMinMean().
152 /// \brief Run the algorithm.
154 /// This function runs the algorithm.
155 /// It can be called more than once (e.g. if the underlying digraph
156 /// and/or the arc lengths have been modified).
158 /// \return \c true if a directed cycle exists in the digraph.
160 /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
162 /// return mmc.findMinMean() && mmc.findCycle();
165 return findMinMean() && findCycle();
168 /// \brief Find the minimum cycle mean.
170 /// This function finds the minimum mean length of the directed
171 /// cycles in the digraph.
173 /// \return \c true if a directed cycle exists in the digraph.
179 _cycle_path = new Path;
181 _cycle_path->clear();
182 _cycle_found = false;
184 // Find the minimum cycle mean in the components
185 _comp_num = stronglyConnectedComponents(_gr, _comp);
186 for (int comp = 0; comp < _comp_num; ++comp) {
187 if (!initCurrentComponent(comp)) continue;
189 if (!findPolicyCycles()) break;
190 contractPolicyGraph(comp);
191 if (!computeNodeDistances()) break;
197 /// \brief Find a minimum mean directed cycle.
199 /// This function finds a directed cycle of minimum mean length
200 /// in the digraph using the data computed by findMinMean().
202 /// \return \c true if a directed cycle exists in the digraph.
204 /// \pre \ref findMinMean() must be called before using this function.
206 if (!_cycle_found) return false;
207 _cycle_path->addBack(_policy[_cycle_node]);
208 for ( Node v = _cycle_node;
209 (v = _gr.target(_policy[v])) != _cycle_node; ) {
210 _cycle_path->addBack(_policy[v]);
217 /// \name Query Functions
218 /// The results of the algorithm can be obtained using these
220 /// The algorithm should be executed before using them.
224 /// \brief Return the total length of the found cycle.
226 /// This function returns the total length of the found cycle.
228 /// \pre \ref run() or \ref findCycle() must be called before
229 /// using this function.
230 Value cycleLength() const {
231 return _cycle_length;
234 /// \brief Return the number of arcs on the found cycle.
236 /// This function returns the number of arcs on the found cycle.
238 /// \pre \ref run() or \ref findCycle() must be called before
239 /// using this function.
240 int cycleArcNum() const {
244 /// \brief Return the mean length of the found cycle.
246 /// This function returns the mean length of the found cycle.
248 /// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
251 /// return double(mmc.cycleLength()) / mmc.cycleArcNum();
254 /// \pre \ref run() or \ref findMinMean() must be called before
255 /// using this function.
256 double cycleMean() const {
257 return double(_cycle_length) / _cycle_size;
260 /// \brief Return the found cycle.
262 /// This function returns a const reference to the path structure
263 /// storing the found cycle.
265 /// \pre \ref run() or \ref findCycle() must be called before using
269 const Path& cycle() const {
277 // Initialize the internal data structures for the current strongly
278 // connected component and create the policy graph.
279 // The policy graph can be represented by the _policy map because
280 // the out-degree of every node is 1.
281 bool initCurrentComponent(int comp) {
282 // Find the nodes of the current component
284 for (NodeIt n(_gr); n != INVALID; ++n) {
285 if (_comp[n] == comp) _nodes.push_back(n);
287 if (_nodes.size() <= 1) return false;
288 // Find the arcs of the current component
290 for (ArcIt e(_gr); e != INVALID; ++e) {
291 if ( _comp[_gr.source(e)] == comp &&
292 _comp[_gr.target(e)] == comp )
295 // Initialize _reached, _dist, _policy maps
296 for (int i = 0; i < int(_nodes.size()); ++i) {
297 _reached[_nodes[i]] = false;
298 _policy[_nodes[i]] = INVALID;
301 for (int j = 0; j < int(_arcs.size()); ++j) {
304 if (!_reached[u] || _length[e] < _dist[u]) {
305 _dist[u] = _length[e];
313 // Find all cycles in the policy graph.
314 // Set _cycle_found to true if a cycle is found and set
315 // _cycle_length, _cycle_size, _cycle_node to represent the minimum
316 // mean cycle in the policy graph.
317 bool findPolicyCycles() {
318 typename Digraph::template NodeMap<int> level(_gr, -1);
319 bool curr_cycle_found = false;
324 // Searching for cycles
325 for (int i = 0; i < int(_nodes.size()); ++i) {
326 if (level[_nodes[i]] < 0) {
329 while (level[u = _gr.target(_policy[u])] < 0)
331 if (level[u] == path_cnt) {
333 curr_cycle_found = true;
334 clength = _length[_policy[u]];
336 for (v = u; (v = _gr.target(_policy[v])) != u; ) {
337 clength += _length[_policy[v]];
340 if ( !_cycle_found ||
341 clength * _cycle_size < _cycle_length * csize ) {
343 _cycle_length = clength;
351 return curr_cycle_found;
354 // Contract the policy graph to be connected by cutting all cycles
355 // except for the main cycle (i.e. the minimum mean cycle).
356 void contractPolicyGraph(int comp) {
357 // Find the component of the main cycle using reverse BFS search
358 typename Digraph::template NodeMap<int> found(_gr, false);
359 std::deque<Node> queue;
360 queue.push_back(_cycle_node);
361 found[_cycle_node] = true;
363 while (!queue.empty()) {
364 v = queue.front(); queue.pop_front();
365 for (InArcIt e(_gr, v); e != INVALID; ++e) {
367 if (_policy[u] == e && !found[u]) {
373 // Connect all other nodes to this component using reverse BFS search
375 for (int i = 0; i < int(_nodes.size()); ++i)
376 if (found[_nodes[i]]) queue.push_back(_nodes[i]);
377 int found_cnt = queue.size();
378 while (found_cnt < int(_nodes.size())) {
379 v = queue.front(); queue.pop_front();
380 for (InArcIt e(_gr, v); e != INVALID; ++e) {
382 if (_comp[u] == comp && !found[u]) {
392 // Compute node distances in the policy graph and update the
393 // policy graph if the node distances can be improved.
394 bool computeNodeDistances() {
395 // Compute node distances using reverse BFS search
396 double cycle_mean = double(_cycle_length) / _cycle_size;
397 typename Digraph::template NodeMap<int> found(_gr, false);
398 std::deque<Node> queue;
399 queue.push_back(_cycle_node);
400 found[_cycle_node] = true;
401 _dist[_cycle_node] = 0;
403 while (!queue.empty()) {
404 v = queue.front(); queue.pop_front();
405 for (InArcIt e(_gr, v); e != INVALID; ++e) {
407 if (_policy[u] == e && !found[u]) {
409 _dist[u] = _dist[v] + _length[e] - cycle_mean;
414 // Improving node distances
415 bool improved = false;
416 for (int j = 0; j < int(_arcs.size()); ++j) {
418 u = _gr.source(e); v = _gr.target(e);
419 double delta = _dist[v] + _length[e] - cycle_mean;
420 if (_tol.less(delta, _dist[u])) {
429 }; //class MinMeanCycle
435 #endif //LEMON_MIN_MEAN_CYCLE_H