* This file is a part of LEMON, a generic C++ optimization library
* Copyright (C) 2003-2008
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
#ifndef LEMON_MIN_MEAN_CYCLE_H
#define LEMON_MIN_MEAN_CYCLE_H
/// \ingroup shortest_path
/// \brief Howard's algorithm for finding a minimum mean cycle.
#include <lemon/tolerance.h>
#include <lemon/connectivity.h>
/// \addtogroup shortest_path
/// \brief Implementation of Howard's algorithm for finding a minimum
/// \ref MinMeanCycle implements Howard's algorithm for finding a
/// directed cycle of minimum mean length (cost) in a digraph.
/// \tparam GR The type of the digraph the algorithm runs on.
/// \tparam LEN The type of the length map. The default
/// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
/// \warning \c LEN::Value must be convertible to \c double.
template <typename GR, typename LEN>
typename LEN = typename GR::template ArcMap<int> >
/// The type of the digraph the algorithm runs on
/// The type of the length map
/// The type of the arc lengths
typedef typename LengthMap::Value Value;
/// The type of the paths
typedef lemon::Path<Digraph> Path;
TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
// The digraph the algorithm runs on
// The length of the arcs
const LengthMap &_length;
// The total length of the found cycle
// The number of arcs on the found cycle
typename Digraph::template NodeMap<bool> _reached;
typename Digraph::template NodeMap<double> _dist;
typename Digraph::template NodeMap<Arc> _policy;
typename Digraph::template NodeMap<int> _comp;
std::vector<Node> _nodes;
/// The constructor of the class.
/// \param digraph The digraph the algorithm runs on.
/// \param length The lengths (costs) of the arcs.
MinMeanCycle( const Digraph &digraph,
const LengthMap &length ) :
_gr(digraph), _length(length), _cycle_length(0), _cycle_size(-1),
_cycle_path(NULL), _local_path(false), _reached(digraph),
_dist(digraph), _policy(digraph), _comp(digraph)
if (_local_path) delete _cycle_path;
/// \brief Set the path structure for storing the found cycle.
/// This function sets an external path structure for storing the
/// If you don't call this function before calling \ref run() or
/// \ref init(), it will allocate a local \ref Path "path"
/// structure. The destuctor deallocates this automatically
/// allocated object, of course.
/// \note The algorithm calls only the \ref lemon::Path::addBack()
/// "addBack()" function of the given path structure.
/// \return <tt>(*this)</tt>
MinMeanCycle& cyclePath(Path &path) {
/// \name Execution control
/// The simplest way to execute the algorithm is to call the \ref run()
/// If you only need the minimum mean length, you may call \ref init()
/// and \ref findMinMean().
/// If you would like to run the algorithm again (e.g. the underlying
/// digraph and/or the arc lengths has been modified), you may not
/// create a new instance of the class, rather call \ref reset(),
/// \ref findMinMean() and \ref findCycle() instead.
/// \brief Run the algorithm.
/// This function runs the algorithm.
/// \return \c true if a directed cycle exists in the digraph.
/// \note Apart from the return value, <tt>mmc.run()</tt> is just a
/// shortcut of the following code.
return findMinMean() && findCycle();
/// \brief Initialize the internal data structures.
/// This function initializes the internal data structures.
_comp_num = stronglyConnectedComponents(_gr, _comp);
/// \brief Reset the internal data structures.
/// This function resets the internal data structures so that
/// findMinMean() and findCycle() can be called again (e.g. when the
/// underlying digraph and/or the arc lengths has been modified).
if (_cycle_path) _cycle_path->clear();
_comp_num = stronglyConnectedComponents(_gr, _comp);
/// \brief Find the minimum cycle mean.
/// This function computes all the required data and finds the
/// minimum mean length of the directed cycles in the digraph.
/// \return \c true if a directed cycle exists in the digraph.
/// \pre \ref init() must be called before using this function.
// Find the minimum cycle mean in the components
for (int comp = 0; comp < _comp_num; ++comp) {
if (!initCurrentComponent(comp)) continue;
if (!findPolicyCycles()) break;
contractPolicyGraph(comp);
if (!computeNodeDistances()) break;
/// \brief Find a minimum mean directed cycle.
/// This function finds a directed cycle of minimum mean length
/// in the digraph using the data computed by findMinMean().
/// \return \c true if a directed cycle exists in the digraph.
/// \pre \ref init() and \ref findMinMean() must be called before
if (!_cycle_found) return false;
_cycle_path->addBack(_policy[_cycle_node]);
for ( Node v = _cycle_node;
(v = _gr.target(_policy[v])) != _cycle_node; ) {
_cycle_path->addBack(_policy[v]);
/// \name Query Functions
/// The result of the algorithm can be obtained using these
/// The algorithm should be executed before using them.
/// \brief Return the total length of the found cycle.
/// This function returns the total length of the found cycle.
/// \pre \ref run() or \ref findCycle() must be called before
Value cycleLength() const {
/// \brief Return the number of arcs on the found cycle.
/// This function returns the number of arcs on the found cycle.
/// \pre \ref run() or \ref findCycle() must be called before
int cycleArcNum() const {
/// \brief Return the mean length of the found cycle.
/// This function returns the mean length of the found cycle.
/// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
/// return double(mmc.cycleLength()) / mmc.cycleArcNum();
/// \pre \ref run() or \ref findMinMean() must be called before
double cycleMean() const {
return double(_cycle_length) / _cycle_size;
/// \brief Return the found cycle.
/// This function returns a const reference to the path structure
/// storing the found cycle.
/// \pre \ref run() or \ref findCycle() must be called before using
const Path& cycle() const {
// Initialize the internal data structures for the current strongly
// connected component and create the policy graph.
// The policy graph can be represented by the _policy map because
// the out-degree of every node is 1.
bool initCurrentComponent(int comp) {
// Find the nodes of the current component
for (NodeIt n(_gr); n != INVALID; ++n) {
if (_comp[n] == comp) _nodes.push_back(n);
if (_nodes.size() <= 1) return false;
// Find the arcs of the current component
for (ArcIt e(_gr); e != INVALID; ++e) {
if ( _comp[_gr.source(e)] == comp &&
_comp[_gr.target(e)] == comp )
// Initialize _reached, _dist, _policy maps
for (int i = 0; i < int(_nodes.size()); ++i) {
_reached[_nodes[i]] = false;
_policy[_nodes[i]] = INVALID;
for (int j = 0; j < int(_arcs.size()); ++j) {
if (!_reached[u] || _length[e] < _dist[u]) {
// Find all cycles in the policy graph.
// Set _cycle_found to true if a cycle is found and set
// _cycle_length, _cycle_size, _cycle_node to represent the minimum
// mean cycle in the policy graph.
bool findPolicyCycles() {
typename Digraph::template NodeMap<int> level(_gr, -1);
bool curr_cycle_found = false;
for (int i = 0; i < int(_nodes.size()); ++i) {
if (level[_nodes[i]] < 0) {
while (level[u = _gr.target(_policy[u])] < 0)
if (level[u] == path_cnt) {
clength = _length[_policy[u]];
for (v = u; (v = _gr.target(_policy[v])) != u; ) {
clength += _length[_policy[v]];
clength * _cycle_size < _cycle_length * csize ) {
// Contract the policy graph to be connected by cutting all cycles
// except for the main cycle (i.e. the minimum mean cycle).
void contractPolicyGraph(int comp) {
// Find the component of the main cycle using reverse BFS search
typename Digraph::template NodeMap<int> found(_gr, false);
queue.push_back(_cycle_node);
found[_cycle_node] = true;
v = queue.front(); queue.pop_front();
for (InArcIt e(_gr, v); e != INVALID; ++e) {
if (_policy[u] == e && !found[u]) {
// Connect all other nodes to this component using reverse BFS search
for (int i = 0; i < int(_nodes.size()); ++i)
if (found[_nodes[i]]) queue.push_back(_nodes[i]);
int found_cnt = queue.size();
while (found_cnt < int(_nodes.size())) {
v = queue.front(); queue.pop_front();
for (InArcIt e(_gr, v); e != INVALID; ++e) {
if (_comp[u] == comp && !found[u]) {
// Compute node distances in the policy graph and update the
// policy graph if the node distances can be improved.
bool computeNodeDistances() {
// Compute node distances using reverse BFS search
double cycle_mean = double(_cycle_length) / _cycle_size;
typename Digraph::template NodeMap<int> found(_gr, false);
queue.push_back(_cycle_node);
found[_cycle_node] = true;
v = queue.front(); queue.pop_front();
for (InArcIt e(_gr, v); e != INVALID; ++e) {
if (_policy[u] == e && !found[u]) {
_dist[u] = _dist[v] + _length[e] - cycle_mean;
// Improving node distances
for (int j = 0; j < int(_arcs.size()); ++j) {
u = _gr.source(e); v = _gr.target(e);
double delta = _dist[v] + _length[e] - cycle_mean;
if (_tol.less(delta, _dist[u])) {
#endif //LEMON_MIN_MEAN_CYCLE_H