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