lemon/min_mean_cycle.h
author alpar
Tue, 24 Apr 2007 09:39:01 +0000
changeset 2436 0c941c524b47
parent 2409 fe0a8fe16271
child 2437 02c7076bf894
permissions -rw-r--r--
Integer parameters also convert to double
alpar@2409
     1
/* -*- C++ -*-
alpar@2409
     2
 *
alpar@2409
     3
 * This file is a part of LEMON, a generic C++ optimization library
alpar@2409
     4
 *
alpar@2409
     5
 * Copyright (C) 2003-2007
alpar@2409
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@2409
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@2409
     8
 *
alpar@2409
     9
 * Permission to use, modify and distribute this software is granted
alpar@2409
    10
 * provided that this copyright notice appears in all copies. For
alpar@2409
    11
 * precise terms see the accompanying LICENSE file.
alpar@2409
    12
 *
alpar@2409
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@2409
    14
 * express or implied, and with no claim as to its suitability for any
alpar@2409
    15
 * purpose.
alpar@2409
    16
 *
alpar@2409
    17
 */
alpar@2409
    18
alpar@2409
    19
#ifndef LEMON_MIN_MEAN_CYCLE_H
alpar@2409
    20
#define LEMON_MIN_MEAN_CYCLE_H
alpar@2409
    21
alpar@2409
    22
/// \ingroup min_cost_flow
alpar@2409
    23
///
alpar@2409
    24
/// \file 
alpar@2409
    25
/// \brief Karp algorithm for finding a minimum mean cycle.
alpar@2409
    26
alpar@2409
    27
#include <lemon/graph_utils.h>
alpar@2409
    28
#include <lemon/topology.h>
alpar@2409
    29
#include <lemon/path.h>
alpar@2409
    30
alpar@2409
    31
namespace lemon {
alpar@2409
    32
alpar@2409
    33
  /// \addtogroup min_cost_flow
alpar@2409
    34
  /// @{
alpar@2409
    35
deba@2413
    36
  /// \brief Implementation of Karp's algorithm for finding a
deba@2413
    37
  /// minimum mean (directed) cycle.
alpar@2409
    38
  ///
deba@2413
    39
  /// The \ref lemon::MinMeanCycle "MinMeanCycle" implements Karp's
deba@2413
    40
  /// algorithm for finding a minimum mean (directed) cycle.
alpar@2409
    41
  ///
alpar@2409
    42
  /// \param Graph The directed graph type the algorithm runs on.
alpar@2409
    43
  /// \param LengthMap The type of the length (cost) map.
alpar@2409
    44
  ///
alpar@2409
    45
  /// \author Peter Kovacs
alpar@2409
    46
alpar@2409
    47
#ifdef DOXYGEN
alpar@2409
    48
  template <typename Graph, typename LengthMap>
alpar@2409
    49
#else
alpar@2409
    50
  template <typename Graph,
alpar@2409
    51
    typename LengthMap = typename Graph::template EdgeMap<int> >
alpar@2409
    52
#endif
alpar@2409
    53
alpar@2409
    54
  class MinMeanCycle
alpar@2409
    55
  {
alpar@2409
    56
    typedef typename Graph::Node Node;
alpar@2409
    57
    typedef typename Graph::NodeIt NodeIt;
alpar@2409
    58
    typedef typename Graph::Edge Edge;
alpar@2409
    59
    typedef typename Graph::EdgeIt EdgeIt;
alpar@2409
    60
    typedef typename Graph::OutEdgeIt OutEdgeIt;
alpar@2409
    61
alpar@2409
    62
    typedef typename LengthMap::Value Length;
deba@2413
    63
alpar@2409
    64
    typedef typename Graph::template NodeMap<int> IntNodeMap;
alpar@2409
    65
    typedef typename Graph::template NodeMap<Edge> PredNodeMap;
alpar@2409
    66
    typedef Path<Graph> Path;
alpar@2409
    67
    typedef std::vector<Node> NodeVector;
alpar@2409
    68
    typedef typename NodeVector::iterator NodeVectorIt;
alpar@2409
    69
alpar@2409
    70
  protected:
deba@2413
    71
alpar@2409
    72
    /// \brief Data sturcture for path data.
deba@2413
    73
    struct PathData
deba@2413
    74
    {
alpar@2409
    75
      bool found;
alpar@2409
    76
      Length dist;
alpar@2409
    77
      Edge pred;
deba@2413
    78
      PathData(bool _found = false, Length _dist = 0) :
alpar@2409
    79
	found(_found), dist(_dist), pred(INVALID) {}
deba@2413
    80
      PathData(bool _found, Length _dist, Edge _pred) :
alpar@2409
    81
	found(_found), dist(_dist), pred(_pred) {}
alpar@2409
    82
    };
deba@2413
    83
alpar@2409
    84
  private:
deba@2413
    85
deba@2413
    86
    typedef typename Graph::template NodeMap<std::vector<PathData> >
deba@2413
    87
      PathDataNodeMap;
deba@2413
    88
alpar@2409
    89
  protected:
alpar@2409
    90
alpar@2409
    91
    /// \brief Node map for storing path data.
alpar@2409
    92
    /// 
alpar@2409
    93
    /// Node map for storing path data of all nodes in the current
alpar@2409
    94
    /// component. dmap[v][k] is the length of a shortest directed walk 
alpar@2409
    95
    /// to node v from the starting node containing exactly k edges.
deba@2413
    96
    PathDataNodeMap dmap;
alpar@2409
    97
    
alpar@2409
    98
    /// \brief The directed graph the algorithm runs on.
alpar@2409
    99
    const Graph& graph;
alpar@2409
   100
    /// \brief The length of the edges.
alpar@2409
   101
    const LengthMap& length;
alpar@2409
   102
    
alpar@2409
   103
    /// \brief The total length of the found cycle.
alpar@2409
   104
    Length cycle_length;
alpar@2409
   105
    /// \brief The number of edges in the found cycle.
alpar@2409
   106
    int cycle_size;
deba@2413
   107
    /// \brief A node for obtaining a minimum mean cycle. 
deba@2413
   108
    Node cycle_node;
deba@2413
   109
alpar@2409
   110
    /// \brief The found cycle.
alpar@2409
   111
    Path *cycle_path;
deba@2413
   112
    /// \brief The algorithm uses local \ref lemon::Path "Path" 
deba@2413
   113
    /// structure to store the found cycle.
alpar@2409
   114
    bool local_path;
alpar@2409
   115
    
alpar@2409
   116
    /// \brief Node map for identifying strongly connected components.
alpar@2409
   117
    IntNodeMap comp;
alpar@2409
   118
    /// \brief The number of strongly connected components.
alpar@2409
   119
    int comp_num;
deba@2413
   120
    /// \brief Counter for identifying the current component.
alpar@2409
   121
    int comp_cnt;
alpar@2409
   122
    /// \brief Nodes of the current component.
alpar@2409
   123
    NodeVector nodes;
alpar@2409
   124
    /// \brief The processed nodes in the last round.
alpar@2409
   125
    NodeVector process;
alpar@2409
   126
    
alpar@2409
   127
  public :
alpar@2409
   128
alpar@2409
   129
    /// \brief The constructor of the class.
alpar@2409
   130
    ///
alpar@2409
   131
    /// The constructor of the class.
alpar@2409
   132
    ///
alpar@2409
   133
    /// \param _graph The directed graph the algorithm runs on.
alpar@2409
   134
    /// \param _length The length (cost) of the edges.
alpar@2409
   135
    MinMeanCycle( const Graph& _graph,
alpar@2409
   136
		  const LengthMap& _length ) :
deba@2413
   137
      graph(_graph), length(_length), dmap(_graph), comp(_graph),
deba@2413
   138
      cycle_length(0), cycle_size(-1), cycle_node(INVALID),
alpar@2409
   139
      cycle_path(NULL), local_path(false)
alpar@2409
   140
    { }
alpar@2409
   141
alpar@2409
   142
    /// \brief The destructor of the class.
alpar@2409
   143
    ~MinMeanCycle() { 
alpar@2409
   144
      if (local_path) delete cycle_path;
alpar@2409
   145
    }
alpar@2409
   146
alpar@2409
   147
  protected:
alpar@2409
   148
alpar@2409
   149
    /// \brief Initializes the internal data structures for the current
alpar@2409
   150
    /// component.
alpar@2409
   151
    void initCurrent() {
alpar@2409
   152
      nodes.clear();
alpar@2409
   153
      // Finding the nodes of the current component
alpar@2409
   154
      for (NodeIt v(graph); v != INVALID; ++v) {
alpar@2409
   155
	if (comp[v] == comp_cnt) nodes.push_back(v);
alpar@2409
   156
      }
alpar@2409
   157
      // Creating vectors for all nodes
alpar@2409
   158
      int n = nodes.size();
alpar@2409
   159
      for (NodeVectorIt vi = nodes.begin(); vi != nodes.end(); ++vi) {
alpar@2409
   160
	dmap[*vi].resize(n + 1);
alpar@2409
   161
      }
alpar@2409
   162
    }
alpar@2409
   163
    
deba@2413
   164
    /// \brief Processes all rounds of computing required path data for 
deba@2413
   165
    /// the current component.
alpar@2409
   166
    void processRounds() {
alpar@2409
   167
      dmap[nodes[0]][0] = PathData(true, 0);
alpar@2409
   168
      process.clear();
deba@2413
   169
      // Processing the first round
deba@2413
   170
      for (OutEdgeIt e(graph, nodes[0]); e != INVALID; ++e) {
deba@2413
   171
	Node v = graph.target(e);
alpar@2409
   172
	if (comp[v] != comp_cnt || v == nodes[0]) continue;
deba@2413
   173
	dmap[v][1] = PathData(true, length[e], e);
alpar@2409
   174
	process.push_back(v);
alpar@2409
   175
      }
deba@2413
   176
      // Processing other rounds 
alpar@2409
   177
      int n = nodes.size(), k;
alpar@2409
   178
      for (k = 2; k <= n && process.size() < n; ++k) {
alpar@2409
   179
	processNextBuildRound(k);
alpar@2409
   180
      }
alpar@2409
   181
      for ( ; k <= n; ++k) {
alpar@2409
   182
	processNextFullRound(k);
alpar@2409
   183
      }
alpar@2409
   184
    }
alpar@2409
   185
    
alpar@2409
   186
    /// \brief Processes one round of computing required path data and
alpar@2409
   187
    /// rebuilds \ref process vector.
alpar@2409
   188
    void processNextBuildRound(int k) {
alpar@2409
   189
      NodeVector next;
alpar@2409
   190
      for (NodeVectorIt ui = process.begin(); ui != process.end(); ++ui) {
deba@2413
   191
	for (OutEdgeIt e(graph, *ui); e != INVALID; ++e) {
deba@2413
   192
	  Node v = graph.target(e);
alpar@2409
   193
	  if (comp[v] != comp_cnt) continue;
deba@2413
   194
	  if (!dmap[v][k].found) {
deba@2413
   195
	    next.push_back(v);
deba@2413
   196
	    dmap[v][k] = PathData(true, dmap[*ui][k-1].dist + length[e], e);
deba@2413
   197
	  }
deba@2413
   198
	  else if (dmap[*ui][k-1].dist + length[e] < dmap[v][k].dist) {
deba@2413
   199
	    dmap[v][k] = PathData(true, dmap[*ui][k-1].dist + length[e], e);
alpar@2409
   200
	  }
alpar@2409
   201
	}
alpar@2409
   202
      }
alpar@2409
   203
      process.swap(next);
alpar@2409
   204
    }
alpar@2409
   205
alpar@2409
   206
    /// \brief Processes one round of computing required path data
alpar@2409
   207
    /// using \ref nodes vector instead of \ref process vector.
alpar@2409
   208
    void processNextFullRound(int k) {
alpar@2409
   209
      for (NodeVectorIt ui = nodes.begin(); ui != nodes.end(); ++ui) {
deba@2413
   210
	for (OutEdgeIt e(graph, *ui); e != INVALID; ++e) {
deba@2413
   211
	  Node v = graph.target(e);
alpar@2409
   212
	  if (comp[v] != comp_cnt) continue;
deba@2413
   213
	  if ( !dmap[v][k].found || 
deba@2413
   214
	       dmap[*ui][k-1].dist + length[e] < dmap[v][k].dist ) {
deba@2413
   215
	    dmap[v][k] = PathData(true, dmap[*ui][k-1].dist + length[e], e);
alpar@2409
   216
	  }
alpar@2409
   217
	}
alpar@2409
   218
      }
alpar@2409
   219
    }
alpar@2409
   220
    
deba@2413
   221
    /// \brief Finds the minimum cycle mean value in the current 
deba@2413
   222
    /// component.
deba@2413
   223
    bool findCurrentMin(Length &min_length, int &min_size, Node &min_node) {
alpar@2409
   224
      bool found_min = false;
alpar@2409
   225
      for (NodeVectorIt vi = nodes.begin(); vi != nodes.end(); ++vi) {
deba@2413
   226
	int n = nodes.size();
deba@2413
   227
	if (!dmap[*vi][n].found) continue;
alpar@2409
   228
	Length len;
alpar@2409
   229
	int size;
alpar@2409
   230
	bool found_one = false;
alpar@2409
   231
	for (int k = 0; k < n; ++k) {
deba@2413
   232
	  if (!dmap[*vi][k].found) continue;
alpar@2409
   233
	  Length _len = dmap[*vi][n].dist - dmap[*vi][k].dist;
alpar@2409
   234
	  int _size = n - k; 
deba@2413
   235
	  if (!found_one || len * _size < _len * size) {
alpar@2409
   236
	    found_one = true;
alpar@2409
   237
	    len = _len;
alpar@2409
   238
	    size = _size;
alpar@2409
   239
	  }
alpar@2409
   240
	}
deba@2413
   241
	if ( found_one && 
deba@2413
   242
	     (!found_min || len * min_size < min_length * size) ) {
alpar@2409
   243
	  found_min = true;
alpar@2409
   244
	  min_length = len;
alpar@2409
   245
	  min_size = size;
alpar@2409
   246
	  min_node = *vi;
alpar@2409
   247
	}
alpar@2409
   248
      }
alpar@2409
   249
      return found_min;
alpar@2409
   250
    }
alpar@2409
   251
    
deba@2413
   252
  public:  
alpar@2409
   253
    
alpar@2409
   254
    /// \brief Runs the algorithm.
alpar@2409
   255
    ///
alpar@2409
   256
    /// Runs the algorithm.
alpar@2409
   257
    ///
alpar@2409
   258
    /// \return \c true if a cycle exists in the graph.
deba@2413
   259
    ///
deba@2413
   260
    /// \note Apart from the return value, m.run() is just a shortcut 
deba@2413
   261
    /// of the following code.
deba@2413
   262
    /// \code
deba@2413
   263
    ///   m.init();
deba@2413
   264
    ///   m.findMinMean();
deba@2413
   265
    ///   m.findCycle();
deba@2413
   266
    /// \endcode
alpar@2409
   267
    bool run() {
alpar@2409
   268
      init();
deba@2413
   269
      findMinMean();
deba@2413
   270
      return findCycle();
deba@2413
   271
    }
deba@2413
   272
    
deba@2413
   273
    /// \brief Initializes the internal data structures.
deba@2413
   274
    void init() {
deba@2413
   275
      comp_num = stronglyConnectedComponents(graph, comp);
deba@2413
   276
      if (!cycle_path) {
deba@2413
   277
	local_path = true;
deba@2413
   278
	cycle_path = new Path;
deba@2413
   279
      }
deba@2413
   280
    }
deba@2413
   281
deba@2413
   282
    /// \brief Finds the minimum cycle mean value in the graph.
deba@2413
   283
    ///
deba@2413
   284
    /// Computes all the required path data and finds the minimum cycle
deba@2413
   285
    /// mean value in the graph.
deba@2413
   286
    ///
deba@2413
   287
    /// \return \c true if a cycle exists in the graph.
deba@2413
   288
    /// 
deba@2413
   289
    /// \pre \ref init() must be called before using this function.
deba@2413
   290
    bool findMinMean() {
deba@2413
   291
      cycle_node = INVALID;
alpar@2409
   292
      for (comp_cnt = 0; comp_cnt < comp_num; ++comp_cnt) {
alpar@2409
   293
	initCurrent();
alpar@2409
   294
	processRounds();
alpar@2409
   295
	
alpar@2409
   296
	Length min_length;
alpar@2409
   297
	int min_size;
alpar@2409
   298
	Node min_node;
deba@2413
   299
	bool found_min = findCurrentMin(min_length, min_size, min_node);
alpar@2409
   300
	
deba@2413
   301
	if ( found_min && (cycle_node == INVALID || 
deba@2413
   302
	     min_length * cycle_size < cycle_length * min_size) ) {
alpar@2409
   303
	  cycle_length = min_length;
alpar@2409
   304
	  cycle_size = min_size;
alpar@2409
   305
	  cycle_node = min_node;
alpar@2409
   306
	}
alpar@2409
   307
      }
deba@2413
   308
      return (cycle_node != INVALID);
alpar@2409
   309
    }
alpar@2409
   310
    
deba@2413
   311
    /// \brief Finds a critical (minimum mean) cycle.
alpar@2409
   312
    ///
deba@2413
   313
    /// Finds a critical (minimum mean) cycle using the path data
deba@2413
   314
    /// stored in \ref dmap.
deba@2413
   315
    ///
deba@2413
   316
    /// \return \c true if a cycle exists in the graph.
deba@2413
   317
    /// 
deba@2413
   318
    /// \pre \ref init() and \ref findMinMean() must be called before 
deba@2413
   319
    /// using this function.
deba@2413
   320
    bool findCycle() {
deba@2413
   321
      if (cycle_node == INVALID) return false;
deba@2413
   322
      cycle_length = 0;
deba@2413
   323
      cycle_size = 0;
deba@2413
   324
      IntNodeMap reached(graph, -1);
deba@2413
   325
      int r = reached[cycle_node] = dmap[cycle_node].size() - 1;
deba@2413
   326
      Node u = graph.source(dmap[cycle_node][r].pred);
deba@2413
   327
      while (reached[u] < 0) {
deba@2413
   328
	reached[u] = --r;
deba@2413
   329
	u = graph.source(dmap[u][r].pred);
deba@2413
   330
      }
deba@2413
   331
      r = reached[u];
deba@2413
   332
      Edge e = dmap[u][r].pred;
deba@2413
   333
      cycle_path->addFront(e);
deba@2413
   334
      cycle_length = cycle_length + length[e];
deba@2413
   335
      ++cycle_size;
deba@2413
   336
      Node v;
deba@2413
   337
      while ((v = graph.source(e)) != u) {
deba@2413
   338
	e = dmap[v][--r].pred;
deba@2413
   339
	cycle_path->addFront(e);
deba@2413
   340
	cycle_length = cycle_length + length[e];
deba@2413
   341
	++cycle_size;
deba@2413
   342
      }
deba@2413
   343
      return true;
deba@2413
   344
    }
deba@2413
   345
deba@2413
   346
    /// \brief Resets the internal data structures.
deba@2413
   347
    ///
deba@2413
   348
    /// Resets the internal data structures so that \ref findMinMean() 
deba@2413
   349
    /// and \ref findCycle() can be called again (e.g. when the 
deba@2413
   350
    /// underlaying graph has been modified).
deba@2413
   351
    void reset() {
deba@2413
   352
      for (NodeIt u(graph); u != INVALID; ++u)
deba@2413
   353
	dmap[u].clear();
deba@2413
   354
      cycle_node = INVALID;
deba@2413
   355
      if (cycle_path) cycle_path->clear();
deba@2413
   356
      comp_num = stronglyConnectedComponents(graph, comp);
deba@2413
   357
    }
deba@2413
   358
    
deba@2413
   359
    /// \brief Returns the total length of the found cycle.
deba@2413
   360
    ///
deba@2413
   361
    /// Returns the total length of the found cycle.
alpar@2409
   362
    ///
alpar@2409
   363
    /// \pre \ref run() must be called before using this function.
alpar@2409
   364
    Length cycleLength() const { 
alpar@2409
   365
      return cycle_length;
alpar@2409
   366
    }
alpar@2409
   367
    
deba@2413
   368
    /// \brief Returns the number of edges in the found cycle.
alpar@2409
   369
    ///
deba@2413
   370
    /// Returns the number of edges in the found cycle.
alpar@2409
   371
    ///
alpar@2409
   372
    /// \pre \ref run() must be called before using this function.
alpar@2409
   373
    int cycleEdgeNum() const { 
alpar@2409
   374
      return cycle_size;
alpar@2409
   375
    }
alpar@2409
   376
    
deba@2413
   377
    /// \brief Returns the mean length of the found cycle.
alpar@2409
   378
    ///
deba@2413
   379
    /// Returns the mean length of the found cycle.
alpar@2409
   380
    ///
alpar@2409
   381
    /// \pre \ref run() must be called before using this function.
alpar@2409
   382
    ///
alpar@2409
   383
    /// \warning LengthMap::Value must be convertible to double.
deba@2413
   384
    ///
deba@2413
   385
    /// \note m.minMean() is just a shortcut of the following code.
deba@2413
   386
    /// \code
deba@2413
   387
    ///   return m.cycleEdgeNum() / double(m.cycleLength());
deba@2413
   388
    /// \endcode
alpar@2409
   389
    double minMean() const { 
deba@2413
   390
      return cycle_length / (double)cycle_size;
alpar@2409
   391
    }
alpar@2409
   392
alpar@2409
   393
    /// \brief Returns a const reference to the \ref lemon::Path "Path"
deba@2413
   394
    /// structure of the found cycle.
alpar@2409
   395
    ///
alpar@2409
   396
    /// Returns a const reference to the \ref lemon::Path "Path"
deba@2413
   397
    /// structure of the found cycle.
alpar@2409
   398
    ///
alpar@2409
   399
    /// \pre \ref run() must be called before using this function.
alpar@2409
   400
    ///
alpar@2409
   401
    /// \sa \ref cyclePath()
alpar@2409
   402
    const Path &cycle() const {
alpar@2409
   403
      return *cycle_path;
alpar@2409
   404
    }
alpar@2409
   405
    
alpar@2409
   406
    /// \brief Sets the \ref lemon::Path "Path" structure storing the 
alpar@2409
   407
    /// found cycle.
alpar@2409
   408
    /// 
alpar@2409
   409
    /// Sets the \ref lemon::Path "Path" structure storing the found 
alpar@2409
   410
    /// cycle. If you don't use this function before calling 
alpar@2409
   411
    /// \ref run(), it will allocate one. The destuctor deallocates 
alpar@2409
   412
    /// this automatically allocated map, of course.
alpar@2409
   413
    ///
alpar@2409
   414
    /// \note The algorithm calls only the \ref lemon::Path::addFront()
alpar@2409
   415
    /// "addFront()" method of the given \ref lemon::Path "Path" 
alpar@2409
   416
    /// structure.
alpar@2409
   417
    /// 
alpar@2409
   418
    /// \return \c (*this)
alpar@2409
   419
    MinMeanCycle &cyclePath(Path& path) {
alpar@2409
   420
      if (local_path) {
alpar@2409
   421
	delete cycle_path;
alpar@2409
   422
	local_path = false;
alpar@2409
   423
      }
alpar@2409
   424
      cycle_path = &path;
alpar@2409
   425
      return *this;
alpar@2409
   426
    }
alpar@2409
   427
alpar@2409
   428
  }; //class MinMeanCycle
alpar@2409
   429
alpar@2409
   430
  ///@}
alpar@2409
   431
alpar@2409
   432
} //namespace lemon
alpar@2409
   433
alpar@2409
   434
#endif //LEMON_MIN_MEAN_CYCLE_H