COIN-OR::LEMON - Graph Library

source: lemon/lemon/karp.h @ 815:0a42883c8221

Last change on this file since 815:0a42883c8221 was 815:0a42883c8221, checked in by Peter Kovacs <kpeter@…>, 15 years ago

Separate group for the min mean cycle classes (#179)

File size: 16.3 KB
Line 
1/* -*- C++ -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library
4 *
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
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.
12 *
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
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_KARP_H
20#define LEMON_KARP_H
21
22/// \ingroup min_mean_cycle
23///
24/// \file
25/// \brief Karp's algorithm for finding a minimum mean cycle.
26
27#include <vector>
28#include <limits>
29#include <lemon/core.h>
30#include <lemon/path.h>
31#include <lemon/tolerance.h>
32#include <lemon/connectivity.h>
33
34namespace lemon {
35
36  /// \brief Default traits class of Karp algorithm.
37  ///
38  /// Default traits class of Karp algorithm.
39  /// \tparam GR The type of the digraph.
40  /// \tparam LEN The type of the length map.
41  /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
42#ifdef DOXYGEN
43  template <typename GR, typename LEN>
44#else
45  template <typename GR, typename LEN,
46    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47#endif
48  struct KarpDefaultTraits
49  {
50    /// The type of the digraph
51    typedef GR Digraph;
52    /// The type of the length map
53    typedef LEN LengthMap;
54    /// The type of the arc lengths
55    typedef typename LengthMap::Value Value;
56
57    /// \brief The large value type used for internal computations
58    ///
59    /// The large value type used for internal computations.
60    /// It is \c long \c long if the \c Value type is integer,
61    /// otherwise it is \c double.
62    /// \c Value must be convertible to \c LargeValue.
63    typedef double LargeValue;
64
65    /// The tolerance type used for internal computations
66    typedef lemon::Tolerance<LargeValue> Tolerance;
67
68    /// \brief The path type of the found cycles
69    ///
70    /// The path type of the found cycles.
71    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72    /// and it must have an \c addBack() function.
73    typedef lemon::Path<Digraph> Path;
74  };
75
76  // Default traits class for integer value types
77  template <typename GR, typename LEN>
78  struct KarpDefaultTraits<GR, LEN, true>
79  {
80    typedef GR Digraph;
81    typedef LEN LengthMap;
82    typedef typename LengthMap::Value Value;
83#ifdef LEMON_HAVE_LONG_LONG
84    typedef long long LargeValue;
85#else
86    typedef long LargeValue;
87#endif
88    typedef lemon::Tolerance<LargeValue> Tolerance;
89    typedef lemon::Path<Digraph> Path;
90  };
91
92
93  /// \addtogroup min_mean_cycle
94  /// @{
95
96  /// \brief Implementation of Karp's algorithm for finding a minimum
97  /// mean cycle.
98  ///
99  /// This class implements Karp's algorithm for finding a directed
100  /// cycle of minimum mean length (cost) in a digraph.
101  /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
102  ///
103  /// \tparam GR The type of the digraph the algorithm runs on.
104  /// \tparam LEN The type of the length map. The default
105  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
106#ifdef DOXYGEN
107  template <typename GR, typename LEN, typename TR>
108#else
109  template < typename GR,
110             typename LEN = typename GR::template ArcMap<int>,
111             typename TR = KarpDefaultTraits<GR, LEN> >
112#endif
113  class Karp
114  {
115  public:
116
117    /// The type of the digraph
118    typedef typename TR::Digraph Digraph;
119    /// The type of the length map
120    typedef typename TR::LengthMap LengthMap;
121    /// The type of the arc lengths
122    typedef typename TR::Value Value;
123
124    /// \brief The large value type
125    ///
126    /// The large value type used for internal computations.
127    /// Using the \ref KarpDefaultTraits "default traits class",
128    /// it is \c long \c long if the \c Value type is integer,
129    /// otherwise it is \c double.
130    typedef typename TR::LargeValue LargeValue;
131
132    /// The tolerance type
133    typedef typename TR::Tolerance Tolerance;
134
135    /// \brief The path type of the found cycles
136    ///
137    /// The path type of the found cycles.
138    /// Using the \ref KarpDefaultTraits "default traits class",
139    /// it is \ref lemon::Path "Path<Digraph>".
140    typedef typename TR::Path Path;
141
142    /// The \ref KarpDefaultTraits "traits class" of the algorithm
143    typedef TR Traits;
144
145  private:
146
147    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148
149    // Data sturcture for path data
150    struct PathData
151    {
152      LargeValue dist;
153      Arc pred;
154      PathData(LargeValue d, Arc p = INVALID) :
155        dist(d), pred(p) {}
156    };
157
158    typedef typename Digraph::template NodeMap<std::vector<PathData> >
159      PathDataNodeMap;
160
161  private:
162
163    // The digraph the algorithm runs on
164    const Digraph &_gr;
165    // The length of the arcs
166    const LengthMap &_length;
167
168    // Data for storing the strongly connected components
169    int _comp_num;
170    typename Digraph::template NodeMap<int> _comp;
171    std::vector<std::vector<Node> > _comp_nodes;
172    std::vector<Node>* _nodes;
173    typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
174
175    // Data for the found cycle
176    LargeValue _cycle_length;
177    int _cycle_size;
178    Node _cycle_node;
179
180    Path *_cycle_path;
181    bool _local_path;
182
183    // Node map for storing path data
184    PathDataNodeMap _data;
185    // The processed nodes in the last round
186    std::vector<Node> _process;
187
188    Tolerance _tolerance;
189   
190    // Infinite constant
191    const LargeValue INF;
192
193  public:
194
195    /// \name Named Template Parameters
196    /// @{
197
198    template <typename T>
199    struct SetLargeValueTraits : public Traits {
200      typedef T LargeValue;
201      typedef lemon::Tolerance<T> Tolerance;
202    };
203
204    /// \brief \ref named-templ-param "Named parameter" for setting
205    /// \c LargeValue type.
206    ///
207    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
208    /// type. It is used for internal computations in the algorithm.
209    template <typename T>
210    struct SetLargeValue
211      : public Karp<GR, LEN, SetLargeValueTraits<T> > {
212      typedef Karp<GR, LEN, SetLargeValueTraits<T> > Create;
213    };
214
215    template <typename T>
216    struct SetPathTraits : public Traits {
217      typedef T Path;
218    };
219
220    /// \brief \ref named-templ-param "Named parameter" for setting
221    /// \c %Path type.
222    ///
223    /// \ref named-templ-param "Named parameter" for setting the \c %Path
224    /// type of the found cycles.
225    /// It must conform to the \ref lemon::concepts::Path "Path" concept
226    /// and it must have an \c addFront() function.
227    template <typename T>
228    struct SetPath
229      : public Karp<GR, LEN, SetPathTraits<T> > {
230      typedef Karp<GR, LEN, SetPathTraits<T> > Create;
231    };
232
233    /// @}
234
235  public:
236
237    /// \brief Constructor.
238    ///
239    /// The constructor of the class.
240    ///
241    /// \param digraph The digraph the algorithm runs on.
242    /// \param length The lengths (costs) of the arcs.
243    Karp( const Digraph &digraph,
244          const LengthMap &length ) :
245      _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
246      _cycle_length(0), _cycle_size(1), _cycle_node(INVALID),
247      _cycle_path(NULL), _local_path(false), _data(digraph),
248      INF(std::numeric_limits<LargeValue>::has_infinity ?
249          std::numeric_limits<LargeValue>::infinity() :
250          std::numeric_limits<LargeValue>::max())
251    {}
252
253    /// Destructor.
254    ~Karp() {
255      if (_local_path) delete _cycle_path;
256    }
257
258    /// \brief Set the path structure for storing the found cycle.
259    ///
260    /// This function sets an external path structure for storing the
261    /// found cycle.
262    ///
263    /// If you don't call this function before calling \ref run() or
264    /// \ref findMinMean(), it will allocate a local \ref Path "path"
265    /// structure. The destuctor deallocates this automatically
266    /// allocated object, of course.
267    ///
268    /// \note The algorithm calls only the \ref lemon::Path::addFront()
269    /// "addFront()" function of the given path structure.
270    ///
271    /// \return <tt>(*this)</tt>
272    Karp& cycle(Path &path) {
273      if (_local_path) {
274        delete _cycle_path;
275        _local_path = false;
276      }
277      _cycle_path = &path;
278      return *this;
279    }
280
281    /// \name Execution control
282    /// The simplest way to execute the algorithm is to call the \ref run()
283    /// function.\n
284    /// If you only need the minimum mean length, you may call
285    /// \ref findMinMean().
286
287    /// @{
288
289    /// \brief Run the algorithm.
290    ///
291    /// This function runs the algorithm.
292    /// It can be called more than once (e.g. if the underlying digraph
293    /// and/or the arc lengths have been modified).
294    ///
295    /// \return \c true if a directed cycle exists in the digraph.
296    ///
297    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
298    /// \code
299    ///   return mmc.findMinMean() && mmc.findCycle();
300    /// \endcode
301    bool run() {
302      return findMinMean() && findCycle();
303    }
304
305    /// \brief Find the minimum cycle mean.
306    ///
307    /// This function finds the minimum mean length of the directed
308    /// cycles in the digraph.
309    ///
310    /// \return \c true if a directed cycle exists in the digraph.
311    bool findMinMean() {
312      // Initialization and find strongly connected components
313      init();
314      findComponents();
315     
316      // Find the minimum cycle mean in the components
317      for (int comp = 0; comp < _comp_num; ++comp) {
318        if (!initComponent(comp)) continue;
319        processRounds();
320        updateMinMean();
321      }
322      return (_cycle_node != INVALID);
323    }
324
325    /// \brief Find a minimum mean directed cycle.
326    ///
327    /// This function finds a directed cycle of minimum mean length
328    /// in the digraph using the data computed by findMinMean().
329    ///
330    /// \return \c true if a directed cycle exists in the digraph.
331    ///
332    /// \pre \ref findMinMean() must be called before using this function.
333    bool findCycle() {
334      if (_cycle_node == INVALID) return false;
335      IntNodeMap reached(_gr, -1);
336      int r = _data[_cycle_node].size();
337      Node u = _cycle_node;
338      while (reached[u] < 0) {
339        reached[u] = --r;
340        u = _gr.source(_data[u][r].pred);
341      }
342      r = reached[u];
343      Arc e = _data[u][r].pred;
344      _cycle_path->addFront(e);
345      _cycle_length = _length[e];
346      _cycle_size = 1;
347      Node v;
348      while ((v = _gr.source(e)) != u) {
349        e = _data[v][--r].pred;
350        _cycle_path->addFront(e);
351        _cycle_length += _length[e];
352        ++_cycle_size;
353      }
354      return true;
355    }
356
357    /// @}
358
359    /// \name Query Functions
360    /// The results of the algorithm can be obtained using these
361    /// functions.\n
362    /// The algorithm should be executed before using them.
363
364    /// @{
365
366    /// \brief Return the total length of the found cycle.
367    ///
368    /// This function returns the total length of the found cycle.
369    ///
370    /// \pre \ref run() or \ref findMinMean() must be called before
371    /// using this function.
372    LargeValue cycleLength() const {
373      return _cycle_length;
374    }
375
376    /// \brief Return the number of arcs on the found cycle.
377    ///
378    /// This function returns the number of arcs on the found cycle.
379    ///
380    /// \pre \ref run() or \ref findMinMean() must be called before
381    /// using this function.
382    int cycleArcNum() const {
383      return _cycle_size;
384    }
385
386    /// \brief Return the mean length of the found cycle.
387    ///
388    /// This function returns the mean length of the found cycle.
389    ///
390    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
391    /// following code.
392    /// \code
393    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
394    /// \endcode
395    ///
396    /// \pre \ref run() or \ref findMinMean() must be called before
397    /// using this function.
398    double cycleMean() const {
399      return static_cast<double>(_cycle_length) / _cycle_size;
400    }
401
402    /// \brief Return the found cycle.
403    ///
404    /// This function returns a const reference to the path structure
405    /// storing the found cycle.
406    ///
407    /// \pre \ref run() or \ref findCycle() must be called before using
408    /// this function.
409    const Path& cycle() const {
410      return *_cycle_path;
411    }
412
413    ///@}
414
415  private:
416
417    // Initialization
418    void init() {
419      if (!_cycle_path) {
420        _local_path = true;
421        _cycle_path = new Path;
422      }
423      _cycle_path->clear();
424      _cycle_length = 0;
425      _cycle_size = 1;
426      _cycle_node = INVALID;
427      for (NodeIt u(_gr); u != INVALID; ++u)
428        _data[u].clear();
429    }
430
431    // Find strongly connected components and initialize _comp_nodes
432    // and _out_arcs
433    void findComponents() {
434      _comp_num = stronglyConnectedComponents(_gr, _comp);
435      _comp_nodes.resize(_comp_num);
436      if (_comp_num == 1) {
437        _comp_nodes[0].clear();
438        for (NodeIt n(_gr); n != INVALID; ++n) {
439          _comp_nodes[0].push_back(n);
440          _out_arcs[n].clear();
441          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
442            _out_arcs[n].push_back(a);
443          }
444        }
445      } else {
446        for (int i = 0; i < _comp_num; ++i)
447          _comp_nodes[i].clear();
448        for (NodeIt n(_gr); n != INVALID; ++n) {
449          int k = _comp[n];
450          _comp_nodes[k].push_back(n);
451          _out_arcs[n].clear();
452          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
453            if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
454          }
455        }
456      }
457    }
458
459    // Initialize path data for the current component
460    bool initComponent(int comp) {
461      _nodes = &(_comp_nodes[comp]);
462      int n = _nodes->size();
463      if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
464        return false;
465      }     
466      for (int i = 0; i < n; ++i) {
467        _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
468      }
469      return true;
470    }
471
472    // Process all rounds of computing path data for the current component.
473    // _data[v][k] is the length of a shortest directed walk from the root
474    // node to node v containing exactly k arcs.
475    void processRounds() {
476      Node start = (*_nodes)[0];
477      _data[start][0] = PathData(0);
478      _process.clear();
479      _process.push_back(start);
480
481      int k, n = _nodes->size();
482      for (k = 1; k <= n && int(_process.size()) < n; ++k) {
483        processNextBuildRound(k);
484      }
485      for ( ; k <= n; ++k) {
486        processNextFullRound(k);
487      }
488    }
489
490    // Process one round and rebuild _process
491    void processNextBuildRound(int k) {
492      std::vector<Node> next;
493      Node u, v;
494      Arc e;
495      LargeValue d;
496      for (int i = 0; i < int(_process.size()); ++i) {
497        u = _process[i];
498        for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
499          e = _out_arcs[u][j];
500          v = _gr.target(e);
501          d = _data[u][k-1].dist + _length[e];
502          if (_tolerance.less(d, _data[v][k].dist)) {
503            if (_data[v][k].dist == INF) next.push_back(v);
504            _data[v][k] = PathData(d, e);
505          }
506        }
507      }
508      _process.swap(next);
509    }
510
511    // Process one round using _nodes instead of _process
512    void processNextFullRound(int k) {
513      Node u, v;
514      Arc e;
515      LargeValue d;
516      for (int i = 0; i < int(_nodes->size()); ++i) {
517        u = (*_nodes)[i];
518        for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
519          e = _out_arcs[u][j];
520          v = _gr.target(e);
521          d = _data[u][k-1].dist + _length[e];
522          if (_tolerance.less(d, _data[v][k].dist)) {
523            _data[v][k] = PathData(d, e);
524          }
525        }
526      }
527    }
528
529    // Update the minimum cycle mean
530    void updateMinMean() {
531      int n = _nodes->size();
532      for (int i = 0; i < n; ++i) {
533        Node u = (*_nodes)[i];
534        if (_data[u][n].dist == INF) continue;
535        LargeValue length, max_length = 0;
536        int size, max_size = 1;
537        bool found_curr = false;
538        for (int k = 0; k < n; ++k) {
539          if (_data[u][k].dist == INF) continue;
540          length = _data[u][n].dist - _data[u][k].dist;
541          size = n - k;
542          if (!found_curr || length * max_size > max_length * size) {
543            found_curr = true;
544            max_length = length;
545            max_size = size;
546          }
547        }
548        if ( found_curr && (_cycle_node == INVALID ||
549             max_length * _cycle_size < _cycle_length * max_size) ) {
550          _cycle_length = max_length;
551          _cycle_size = max_size;
552          _cycle_node = u;
553        }
554      }
555    }
556
557  }; //class Karp
558
559  ///@}
560
561} //namespace lemon
562
563#endif //LEMON_KARP_H
Note: See TracBrowser for help on using the repository browser.