lemon/min_mean_cycle.h
author Peter Kovacs <kpeter@inf.elte.hu>
Mon, 03 Aug 2009 14:35:38 +0200
changeset 759 d66ff32624e2
parent 758 b31e130db13d
child 760 83ce7ce39f21
permissions -rw-r--r--
Simplify the interface of MinMeanCycle (#179)
Remove init() and reset(), and move their content into findMinMean().
kpeter@758
     1
/* -*- C++ -*-
kpeter@758
     2
 *
kpeter@758
     3
 * This file is a part of LEMON, a generic C++ optimization library
kpeter@758
     4
 *
kpeter@758
     5
 * Copyright (C) 2003-2008
kpeter@758
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@758
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@758
     8
 *
kpeter@758
     9
 * Permission to use, modify and distribute this software is granted
kpeter@758
    10
 * provided that this copyright notice appears in all copies. For
kpeter@758
    11
 * precise terms see the accompanying LICENSE file.
kpeter@758
    12
 *
kpeter@758
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@758
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@758
    15
 * purpose.
kpeter@758
    16
 *
kpeter@758
    17
 */
kpeter@758
    18
kpeter@758
    19
#ifndef LEMON_MIN_MEAN_CYCLE_H
kpeter@758
    20
#define LEMON_MIN_MEAN_CYCLE_H
kpeter@758
    21
kpeter@758
    22
/// \ingroup shortest_path
kpeter@758
    23
///
kpeter@758
    24
/// \file
kpeter@758
    25
/// \brief Howard's algorithm for finding a minimum mean cycle.
kpeter@758
    26
kpeter@758
    27
#include <vector>
kpeter@758
    28
#include <lemon/core.h>
kpeter@758
    29
#include <lemon/path.h>
kpeter@758
    30
#include <lemon/tolerance.h>
kpeter@758
    31
#include <lemon/connectivity.h>
kpeter@758
    32
kpeter@758
    33
namespace lemon {
kpeter@758
    34
kpeter@758
    35
  /// \addtogroup shortest_path
kpeter@758
    36
  /// @{
kpeter@758
    37
kpeter@758
    38
  /// \brief Implementation of Howard's algorithm for finding a minimum
kpeter@758
    39
  /// mean cycle.
kpeter@758
    40
  ///
kpeter@758
    41
  /// \ref MinMeanCycle implements Howard's algorithm for finding a
kpeter@758
    42
  /// directed cycle of minimum mean length (cost) in a digraph.
kpeter@758
    43
  ///
kpeter@758
    44
  /// \tparam GR The type of the digraph the algorithm runs on.
kpeter@758
    45
  /// \tparam LEN The type of the length map. The default
kpeter@758
    46
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
kpeter@758
    47
  ///
kpeter@758
    48
  /// \warning \c LEN::Value must be convertible to \c double.
kpeter@758
    49
#ifdef DOXYGEN
kpeter@758
    50
  template <typename GR, typename LEN>
kpeter@758
    51
#else
kpeter@758
    52
  template < typename GR,
kpeter@758
    53
             typename LEN = typename GR::template ArcMap<int> >
kpeter@758
    54
#endif
kpeter@758
    55
  class MinMeanCycle
kpeter@758
    56
  {
kpeter@758
    57
  public:
kpeter@758
    58
  
kpeter@758
    59
    /// The type of the digraph the algorithm runs on
kpeter@758
    60
    typedef GR Digraph;
kpeter@758
    61
    /// The type of the length map
kpeter@758
    62
    typedef LEN LengthMap;
kpeter@758
    63
    /// The type of the arc lengths
kpeter@758
    64
    typedef typename LengthMap::Value Value;
kpeter@758
    65
    /// The type of the paths
kpeter@758
    66
    typedef lemon::Path<Digraph> Path;
kpeter@758
    67
kpeter@758
    68
  private:
kpeter@758
    69
kpeter@758
    70
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
kpeter@758
    71
  
kpeter@758
    72
    // The digraph the algorithm runs on
kpeter@758
    73
    const Digraph &_gr;
kpeter@758
    74
    // The length of the arcs
kpeter@758
    75
    const LengthMap &_length;
kpeter@758
    76
kpeter@758
    77
    // The total length of the found cycle
kpeter@758
    78
    Value _cycle_length;
kpeter@758
    79
    // The number of arcs on the found cycle
kpeter@758
    80
    int _cycle_size;
kpeter@758
    81
    // The found cycle
kpeter@758
    82
    Path *_cycle_path;
kpeter@758
    83
kpeter@758
    84
    bool _local_path;
kpeter@758
    85
    bool _cycle_found;
kpeter@758
    86
    Node _cycle_node;
kpeter@758
    87
kpeter@758
    88
    typename Digraph::template NodeMap<bool> _reached;
kpeter@758
    89
    typename Digraph::template NodeMap<double> _dist;
kpeter@758
    90
    typename Digraph::template NodeMap<Arc> _policy;
kpeter@758
    91
kpeter@758
    92
    typename Digraph::template NodeMap<int> _comp;
kpeter@758
    93
    int _comp_num;
kpeter@758
    94
kpeter@758
    95
    std::vector<Node> _nodes;
kpeter@758
    96
    std::vector<Arc> _arcs;
kpeter@758
    97
    Tolerance<double> _tol;
kpeter@758
    98
kpeter@758
    99
  public:
kpeter@758
   100
kpeter@758
   101
    /// \brief Constructor.
kpeter@758
   102
    ///
kpeter@758
   103
    /// The constructor of the class.
kpeter@758
   104
    ///
kpeter@758
   105
    /// \param digraph The digraph the algorithm runs on.
kpeter@758
   106
    /// \param length The lengths (costs) of the arcs.
kpeter@758
   107
    MinMeanCycle( const Digraph &digraph,
kpeter@758
   108
                  const LengthMap &length ) :
kpeter@758
   109
      _gr(digraph), _length(length), _cycle_length(0), _cycle_size(-1),
kpeter@758
   110
      _cycle_path(NULL), _local_path(false), _reached(digraph),
kpeter@758
   111
      _dist(digraph), _policy(digraph), _comp(digraph)
kpeter@758
   112
    {}
kpeter@758
   113
kpeter@758
   114
    /// Destructor.
kpeter@758
   115
    ~MinMeanCycle() {
kpeter@758
   116
      if (_local_path) delete _cycle_path;
kpeter@758
   117
    }
kpeter@758
   118
kpeter@758
   119
    /// \brief Set the path structure for storing the found cycle.
kpeter@758
   120
    ///
kpeter@758
   121
    /// This function sets an external path structure for storing the
kpeter@758
   122
    /// found cycle.
kpeter@758
   123
    ///
kpeter@758
   124
    /// If you don't call this function before calling \ref run() or
kpeter@759
   125
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
kpeter@758
   126
    /// structure. The destuctor deallocates this automatically
kpeter@758
   127
    /// allocated object, of course.
kpeter@758
   128
    ///
kpeter@758
   129
    /// \note The algorithm calls only the \ref lemon::Path::addBack()
kpeter@758
   130
    /// "addBack()" function of the given path structure.
kpeter@758
   131
    ///
kpeter@758
   132
    /// \return <tt>(*this)</tt>
kpeter@758
   133
    ///
kpeter@758
   134
    /// \sa cycle()
kpeter@758
   135
    MinMeanCycle& cyclePath(Path &path) {
kpeter@758
   136
      if (_local_path) {
kpeter@758
   137
        delete _cycle_path;
kpeter@758
   138
        _local_path = false;
kpeter@758
   139
      }
kpeter@758
   140
      _cycle_path = &path;
kpeter@758
   141
      return *this;
kpeter@758
   142
    }
kpeter@758
   143
kpeter@758
   144
    /// \name Execution control
kpeter@758
   145
    /// The simplest way to execute the algorithm is to call the \ref run()
kpeter@758
   146
    /// function.\n
kpeter@759
   147
    /// If you only need the minimum mean length, you may call
kpeter@759
   148
    /// \ref findMinMean().
kpeter@758
   149
kpeter@758
   150
    /// @{
kpeter@758
   151
kpeter@758
   152
    /// \brief Run the algorithm.
kpeter@758
   153
    ///
kpeter@758
   154
    /// This function runs the algorithm.
kpeter@759
   155
    /// It can be called more than once (e.g. if the underlying digraph
kpeter@759
   156
    /// and/or the arc lengths have been modified).
kpeter@758
   157
    ///
kpeter@758
   158
    /// \return \c true if a directed cycle exists in the digraph.
kpeter@758
   159
    ///
kpeter@759
   160
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
kpeter@758
   161
    /// \code
kpeter@759
   162
    ///   return mmc.findMinMean() && mmc.findCycle();
kpeter@758
   163
    /// \endcode
kpeter@758
   164
    bool run() {
kpeter@758
   165
      return findMinMean() && findCycle();
kpeter@758
   166
    }
kpeter@758
   167
kpeter@759
   168
    /// \brief Find the minimum cycle mean.
kpeter@758
   169
    ///
kpeter@759
   170
    /// This function finds the minimum mean length of the directed
kpeter@759
   171
    /// cycles in the digraph.
kpeter@758
   172
    ///
kpeter@759
   173
    /// \return \c true if a directed cycle exists in the digraph.
kpeter@759
   174
    bool findMinMean() {
kpeter@759
   175
      // Initialize
kpeter@758
   176
      _tol.epsilon(1e-6);
kpeter@758
   177
      if (!_cycle_path) {
kpeter@758
   178
        _local_path = true;
kpeter@758
   179
        _cycle_path = new Path;
kpeter@758
   180
      }
kpeter@759
   181
      _cycle_path->clear();
kpeter@758
   182
      _cycle_found = false;
kpeter@759
   183
kpeter@759
   184
      // Find the minimum cycle mean in the components
kpeter@758
   185
      _comp_num = stronglyConnectedComponents(_gr, _comp);
kpeter@758
   186
      for (int comp = 0; comp < _comp_num; ++comp) {
kpeter@758
   187
        if (!initCurrentComponent(comp)) continue;
kpeter@758
   188
        while (true) {
kpeter@758
   189
          if (!findPolicyCycles()) break;
kpeter@758
   190
          contractPolicyGraph(comp);
kpeter@758
   191
          if (!computeNodeDistances()) break;
kpeter@758
   192
        }
kpeter@758
   193
      }
kpeter@758
   194
      return _cycle_found;
kpeter@758
   195
    }
kpeter@758
   196
kpeter@758
   197
    /// \brief Find a minimum mean directed cycle.
kpeter@758
   198
    ///
kpeter@758
   199
    /// This function finds a directed cycle of minimum mean length
kpeter@758
   200
    /// in the digraph using the data computed by findMinMean().
kpeter@758
   201
    ///
kpeter@758
   202
    /// \return \c true if a directed cycle exists in the digraph.
kpeter@758
   203
    ///
kpeter@759
   204
    /// \pre \ref findMinMean() must be called before using this function.
kpeter@758
   205
    bool findCycle() {
kpeter@758
   206
      if (!_cycle_found) return false;
kpeter@758
   207
      _cycle_path->addBack(_policy[_cycle_node]);
kpeter@758
   208
      for ( Node v = _cycle_node;
kpeter@758
   209
            (v = _gr.target(_policy[v])) != _cycle_node; ) {
kpeter@758
   210
        _cycle_path->addBack(_policy[v]);
kpeter@758
   211
      }
kpeter@758
   212
      return true;
kpeter@758
   213
    }
kpeter@758
   214
kpeter@758
   215
    /// @}
kpeter@758
   216
kpeter@758
   217
    /// \name Query Functions
kpeter@759
   218
    /// The results of the algorithm can be obtained using these
kpeter@758
   219
    /// functions.\n
kpeter@758
   220
    /// The algorithm should be executed before using them.
kpeter@758
   221
kpeter@758
   222
    /// @{
kpeter@758
   223
kpeter@758
   224
    /// \brief Return the total length of the found cycle.
kpeter@758
   225
    ///
kpeter@758
   226
    /// This function returns the total length of the found cycle.
kpeter@758
   227
    ///
kpeter@758
   228
    /// \pre \ref run() or \ref findCycle() must be called before
kpeter@758
   229
    /// using this function.
kpeter@758
   230
    Value cycleLength() const {
kpeter@758
   231
      return _cycle_length;
kpeter@758
   232
    }
kpeter@758
   233
kpeter@758
   234
    /// \brief Return the number of arcs on the found cycle.
kpeter@758
   235
    ///
kpeter@758
   236
    /// This function returns the number of arcs on the found cycle.
kpeter@758
   237
    ///
kpeter@758
   238
    /// \pre \ref run() or \ref findCycle() must be called before
kpeter@758
   239
    /// using this function.
kpeter@758
   240
    int cycleArcNum() const {
kpeter@758
   241
      return _cycle_size;
kpeter@758
   242
    }
kpeter@758
   243
kpeter@758
   244
    /// \brief Return the mean length of the found cycle.
kpeter@758
   245
    ///
kpeter@758
   246
    /// This function returns the mean length of the found cycle.
kpeter@758
   247
    ///
kpeter@758
   248
    /// \note <tt>mmc.cycleMean()</tt> is just a shortcut of the
kpeter@758
   249
    /// following code.
kpeter@758
   250
    /// \code
kpeter@758
   251
    ///   return double(mmc.cycleLength()) / mmc.cycleArcNum();
kpeter@758
   252
    /// \endcode
kpeter@758
   253
    ///
kpeter@758
   254
    /// \pre \ref run() or \ref findMinMean() must be called before
kpeter@758
   255
    /// using this function.
kpeter@758
   256
    double cycleMean() const {
kpeter@758
   257
      return double(_cycle_length) / _cycle_size;
kpeter@758
   258
    }
kpeter@758
   259
kpeter@758
   260
    /// \brief Return the found cycle.
kpeter@758
   261
    ///
kpeter@758
   262
    /// This function returns a const reference to the path structure
kpeter@758
   263
    /// storing the found cycle.
kpeter@758
   264
    ///
kpeter@758
   265
    /// \pre \ref run() or \ref findCycle() must be called before using
kpeter@758
   266
    /// this function.
kpeter@758
   267
    ///
kpeter@758
   268
    /// \sa cyclePath()
kpeter@758
   269
    const Path& cycle() const {
kpeter@758
   270
      return *_cycle_path;
kpeter@758
   271
    }
kpeter@758
   272
kpeter@758
   273
    ///@}
kpeter@758
   274
kpeter@758
   275
  private:
kpeter@758
   276
kpeter@758
   277
    // Initialize the internal data structures for the current strongly
kpeter@758
   278
    // connected component and create the policy graph.
kpeter@758
   279
    // The policy graph can be represented by the _policy map because
kpeter@758
   280
    // the out-degree of every node is 1.
kpeter@758
   281
    bool initCurrentComponent(int comp) {
kpeter@758
   282
      // Find the nodes of the current component
kpeter@758
   283
      _nodes.clear();
kpeter@758
   284
      for (NodeIt n(_gr); n != INVALID; ++n) {
kpeter@758
   285
        if (_comp[n] == comp) _nodes.push_back(n);
kpeter@758
   286
      }
kpeter@758
   287
      if (_nodes.size() <= 1) return false;
kpeter@758
   288
      // Find the arcs of the current component
kpeter@758
   289
      _arcs.clear();
kpeter@758
   290
      for (ArcIt e(_gr); e != INVALID; ++e) {
kpeter@758
   291
        if ( _comp[_gr.source(e)] == comp &&
kpeter@758
   292
             _comp[_gr.target(e)] == comp )
kpeter@758
   293
          _arcs.push_back(e);
kpeter@758
   294
      }
kpeter@758
   295
      // Initialize _reached, _dist, _policy maps
kpeter@758
   296
      for (int i = 0; i < int(_nodes.size()); ++i) {
kpeter@758
   297
        _reached[_nodes[i]] = false;
kpeter@758
   298
        _policy[_nodes[i]] = INVALID;
kpeter@758
   299
      }
kpeter@758
   300
      Node u; Arc e;
kpeter@758
   301
      for (int j = 0; j < int(_arcs.size()); ++j) {
kpeter@758
   302
        e = _arcs[j];
kpeter@758
   303
        u = _gr.source(e);
kpeter@758
   304
        if (!_reached[u] || _length[e] < _dist[u]) {
kpeter@758
   305
          _dist[u] = _length[e];
kpeter@758
   306
          _policy[u] = e;
kpeter@758
   307
          _reached[u] = true;
kpeter@758
   308
        }
kpeter@758
   309
      }
kpeter@758
   310
      return true;
kpeter@758
   311
    }
kpeter@758
   312
kpeter@758
   313
    // Find all cycles in the policy graph.
kpeter@758
   314
    // Set _cycle_found to true if a cycle is found and set
kpeter@758
   315
    // _cycle_length, _cycle_size, _cycle_node to represent the minimum
kpeter@758
   316
    // mean cycle in the policy graph.
kpeter@758
   317
    bool findPolicyCycles() {
kpeter@758
   318
      typename Digraph::template NodeMap<int> level(_gr, -1);
kpeter@758
   319
      bool curr_cycle_found = false;
kpeter@758
   320
      Value clength;
kpeter@758
   321
      int csize;
kpeter@758
   322
      int path_cnt = 0;
kpeter@758
   323
      Node u, v;
kpeter@758
   324
      // Searching for cycles
kpeter@758
   325
      for (int i = 0; i < int(_nodes.size()); ++i) {
kpeter@758
   326
        if (level[_nodes[i]] < 0) {
kpeter@758
   327
          u = _nodes[i];
kpeter@758
   328
          level[u] = path_cnt;
kpeter@758
   329
          while (level[u = _gr.target(_policy[u])] < 0)
kpeter@758
   330
            level[u] = path_cnt;
kpeter@758
   331
          if (level[u] == path_cnt) {
kpeter@758
   332
            // A cycle is found
kpeter@758
   333
            curr_cycle_found = true;
kpeter@758
   334
            clength = _length[_policy[u]];
kpeter@758
   335
            csize = 1;
kpeter@758
   336
            for (v = u; (v = _gr.target(_policy[v])) != u; ) {
kpeter@758
   337
              clength += _length[_policy[v]];
kpeter@758
   338
              ++csize;
kpeter@758
   339
            }
kpeter@758
   340
            if ( !_cycle_found ||
kpeter@758
   341
                 clength * _cycle_size < _cycle_length * csize ) {
kpeter@758
   342
              _cycle_found = true;
kpeter@758
   343
              _cycle_length = clength;
kpeter@758
   344
              _cycle_size = csize;
kpeter@758
   345
              _cycle_node = u;
kpeter@758
   346
            }
kpeter@758
   347
          }
kpeter@758
   348
          ++path_cnt;
kpeter@758
   349
        }
kpeter@758
   350
      }
kpeter@758
   351
      return curr_cycle_found;
kpeter@758
   352
    }
kpeter@758
   353
kpeter@758
   354
    // Contract the policy graph to be connected by cutting all cycles
kpeter@758
   355
    // except for the main cycle (i.e. the minimum mean cycle).
kpeter@758
   356
    void contractPolicyGraph(int comp) {
kpeter@758
   357
      // Find the component of the main cycle using reverse BFS search
kpeter@758
   358
      typename Digraph::template NodeMap<int> found(_gr, false);
kpeter@758
   359
      std::deque<Node> queue;
kpeter@758
   360
      queue.push_back(_cycle_node);
kpeter@758
   361
      found[_cycle_node] = true;
kpeter@758
   362
      Node u, v;
kpeter@758
   363
      while (!queue.empty()) {
kpeter@758
   364
        v = queue.front(); queue.pop_front();
kpeter@758
   365
        for (InArcIt e(_gr, v); e != INVALID; ++e) {
kpeter@758
   366
          u = _gr.source(e);
kpeter@758
   367
          if (_policy[u] == e && !found[u]) {
kpeter@758
   368
            found[u] = true;
kpeter@758
   369
            queue.push_back(u);
kpeter@758
   370
          }
kpeter@758
   371
        }
kpeter@758
   372
      }
kpeter@758
   373
      // Connect all other nodes to this component using reverse BFS search
kpeter@758
   374
      queue.clear();
kpeter@758
   375
      for (int i = 0; i < int(_nodes.size()); ++i)
kpeter@758
   376
        if (found[_nodes[i]]) queue.push_back(_nodes[i]);
kpeter@758
   377
      int found_cnt = queue.size();
kpeter@758
   378
      while (found_cnt < int(_nodes.size())) {
kpeter@758
   379
        v = queue.front(); queue.pop_front();
kpeter@758
   380
        for (InArcIt e(_gr, v); e != INVALID; ++e) {
kpeter@758
   381
          u = _gr.source(e);
kpeter@758
   382
          if (_comp[u] == comp && !found[u]) {
kpeter@758
   383
            found[u] = true;
kpeter@758
   384
            ++found_cnt;
kpeter@758
   385
            _policy[u] = e;
kpeter@758
   386
            queue.push_back(u);
kpeter@758
   387
          }
kpeter@758
   388
        }
kpeter@758
   389
      }
kpeter@758
   390
    }
kpeter@758
   391
kpeter@758
   392
    // Compute node distances in the policy graph and update the
kpeter@758
   393
    // policy graph if the node distances can be improved.
kpeter@758
   394
    bool computeNodeDistances() {
kpeter@758
   395
      // Compute node distances using reverse BFS search
kpeter@758
   396
      double cycle_mean = double(_cycle_length) / _cycle_size;
kpeter@758
   397
      typename Digraph::template NodeMap<int> found(_gr, false);
kpeter@758
   398
      std::deque<Node> queue;
kpeter@758
   399
      queue.push_back(_cycle_node);
kpeter@758
   400
      found[_cycle_node] = true;
kpeter@758
   401
      _dist[_cycle_node] = 0;
kpeter@758
   402
      Node u, v;
kpeter@758
   403
      while (!queue.empty()) {
kpeter@758
   404
        v = queue.front(); queue.pop_front();
kpeter@758
   405
        for (InArcIt e(_gr, v); e != INVALID; ++e) {
kpeter@758
   406
          u = _gr.source(e);
kpeter@758
   407
          if (_policy[u] == e && !found[u]) {
kpeter@758
   408
            found[u] = true;
kpeter@758
   409
            _dist[u] = _dist[v] + _length[e] - cycle_mean;
kpeter@758
   410
            queue.push_back(u);
kpeter@758
   411
          }
kpeter@758
   412
        }
kpeter@758
   413
      }
kpeter@758
   414
      // Improving node distances
kpeter@758
   415
      bool improved = false;
kpeter@758
   416
      for (int j = 0; j < int(_arcs.size()); ++j) {
kpeter@758
   417
        Arc e = _arcs[j];
kpeter@758
   418
        u = _gr.source(e); v = _gr.target(e);
kpeter@758
   419
        double delta = _dist[v] + _length[e] - cycle_mean;
kpeter@758
   420
        if (_tol.less(delta, _dist[u])) {
kpeter@758
   421
          improved = true;
kpeter@758
   422
          _dist[u] = delta;
kpeter@758
   423
          _policy[u] = e;
kpeter@758
   424
        }
kpeter@758
   425
      }
kpeter@758
   426
      return improved;
kpeter@758
   427
    }
kpeter@758
   428
kpeter@758
   429
  }; //class MinMeanCycle
kpeter@758
   430
kpeter@758
   431
  ///@}
kpeter@758
   432
kpeter@758
   433
} //namespace lemon
kpeter@758
   434
kpeter@758
   435
#endif //LEMON_MIN_MEAN_CYCLE_H