lemon/karp.h
author Alpar Juttner <alpar@cs.elte.hu>
Thu, 05 Nov 2009 08:39:49 +0100
changeset 770 432c54cec63c
parent 768 0a42883c8221
child 771 8452ca46e29a
permissions -rw-r--r--
Merge #179 (Port the min mean cycle algorithms)
     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 
    34 namespace 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     /// \brief Set the tolerance used by the algorithm.
   282     ///
   283     /// This function sets the tolerance object used by the algorithm.
   284     ///
   285     /// \return <tt>(*this)</tt>
   286     Karp& tolerance(const Tolerance& tolerance) {
   287       _tolerance = tolerance;
   288       return *this;
   289     }
   290 
   291     /// \brief Return a const reference to the tolerance.
   292     ///
   293     /// This function returns a const reference to the tolerance object
   294     /// used by the algorithm.
   295     const Tolerance& tolerance() const {
   296       return _tolerance;
   297     }
   298 
   299     /// \name Execution control
   300     /// The simplest way to execute the algorithm is to call the \ref run()
   301     /// function.\n
   302     /// If you only need the minimum mean length, you may call
   303     /// \ref findMinMean().
   304 
   305     /// @{
   306 
   307     /// \brief Run the algorithm.
   308     ///
   309     /// This function runs the algorithm.
   310     /// It can be called more than once (e.g. if the underlying digraph
   311     /// and/or the arc lengths have been modified).
   312     ///
   313     /// \return \c true if a directed cycle exists in the digraph.
   314     ///
   315     /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
   316     /// \code
   317     ///   return mmc.findMinMean() && mmc.findCycle();
   318     /// \endcode
   319     bool run() {
   320       return findMinMean() && findCycle();
   321     }
   322 
   323     /// \brief Find the minimum cycle mean.
   324     ///
   325     /// This function finds the minimum mean length of the directed
   326     /// cycles in the digraph.
   327     ///
   328     /// \return \c true if a directed cycle exists in the digraph.
   329     bool findMinMean() {
   330       // Initialization and find strongly connected components
   331       init();
   332       findComponents();
   333       
   334       // Find the minimum cycle mean in the components
   335       for (int comp = 0; comp < _comp_num; ++comp) {
   336         if (!initComponent(comp)) continue;
   337         processRounds();
   338         updateMinMean();
   339       }
   340       return (_cycle_node != INVALID);
   341     }
   342 
   343     /// \brief Find a minimum mean directed cycle.
   344     ///
   345     /// This function finds a directed cycle of minimum mean length
   346     /// in the digraph using the data computed by findMinMean().
   347     ///
   348     /// \return \c true if a directed cycle exists in the digraph.
   349     ///
   350     /// \pre \ref findMinMean() must be called before using this function.
   351     bool findCycle() {
   352       if (_cycle_node == INVALID) return false;
   353       IntNodeMap reached(_gr, -1);
   354       int r = _data[_cycle_node].size();
   355       Node u = _cycle_node;
   356       while (reached[u] < 0) {
   357         reached[u] = --r;
   358         u = _gr.source(_data[u][r].pred);
   359       }
   360       r = reached[u];
   361       Arc e = _data[u][r].pred;
   362       _cycle_path->addFront(e);
   363       _cycle_length = _length[e];
   364       _cycle_size = 1;
   365       Node v;
   366       while ((v = _gr.source(e)) != u) {
   367         e = _data[v][--r].pred;
   368         _cycle_path->addFront(e);
   369         _cycle_length += _length[e];
   370         ++_cycle_size;
   371       }
   372       return true;
   373     }
   374 
   375     /// @}
   376 
   377     /// \name Query Functions
   378     /// The results of the algorithm can be obtained using these
   379     /// functions.\n
   380     /// The algorithm should be executed before using them.
   381 
   382     /// @{
   383 
   384     /// \brief Return the total length of the found cycle.
   385     ///
   386     /// This function returns the total length of the found cycle.
   387     ///
   388     /// \pre \ref run() or \ref findMinMean() must be called before
   389     /// using this function.
   390     LargeValue cycleLength() const {
   391       return _cycle_length;
   392     }
   393 
   394     /// \brief Return the number of arcs on the found cycle.
   395     ///
   396     /// This function returns the number of arcs on the found cycle.
   397     ///
   398     /// \pre \ref run() or \ref findMinMean() must be called before
   399     /// using this function.
   400     int cycleArcNum() const {
   401       return _cycle_size;
   402     }
   403 
   404     /// \brief Return the mean length of the found cycle.
   405     ///
   406     /// This function returns the mean length of the found cycle.
   407     ///
   408     /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
   409     /// following code.
   410     /// \code
   411     ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
   412     /// \endcode
   413     ///
   414     /// \pre \ref run() or \ref findMinMean() must be called before
   415     /// using this function.
   416     double cycleMean() const {
   417       return static_cast<double>(_cycle_length) / _cycle_size;
   418     }
   419 
   420     /// \brief Return the found cycle.
   421     ///
   422     /// This function returns a const reference to the path structure
   423     /// storing the found cycle.
   424     ///
   425     /// \pre \ref run() or \ref findCycle() must be called before using
   426     /// this function.
   427     const Path& cycle() const {
   428       return *_cycle_path;
   429     }
   430 
   431     ///@}
   432 
   433   private:
   434 
   435     // Initialization
   436     void init() {
   437       if (!_cycle_path) {
   438         _local_path = true;
   439         _cycle_path = new Path;
   440       }
   441       _cycle_path->clear();
   442       _cycle_length = 0;
   443       _cycle_size = 1;
   444       _cycle_node = INVALID;
   445       for (NodeIt u(_gr); u != INVALID; ++u)
   446         _data[u].clear();
   447     }
   448 
   449     // Find strongly connected components and initialize _comp_nodes
   450     // and _out_arcs
   451     void findComponents() {
   452       _comp_num = stronglyConnectedComponents(_gr, _comp);
   453       _comp_nodes.resize(_comp_num);
   454       if (_comp_num == 1) {
   455         _comp_nodes[0].clear();
   456         for (NodeIt n(_gr); n != INVALID; ++n) {
   457           _comp_nodes[0].push_back(n);
   458           _out_arcs[n].clear();
   459           for (OutArcIt a(_gr, n); a != INVALID; ++a) {
   460             _out_arcs[n].push_back(a);
   461           }
   462         }
   463       } else {
   464         for (int i = 0; i < _comp_num; ++i)
   465           _comp_nodes[i].clear();
   466         for (NodeIt n(_gr); n != INVALID; ++n) {
   467           int k = _comp[n];
   468           _comp_nodes[k].push_back(n);
   469           _out_arcs[n].clear();
   470           for (OutArcIt a(_gr, n); a != INVALID; ++a) {
   471             if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
   472           }
   473         }
   474       }
   475     }
   476 
   477     // Initialize path data for the current component
   478     bool initComponent(int comp) {
   479       _nodes = &(_comp_nodes[comp]);
   480       int n = _nodes->size();
   481       if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
   482         return false;
   483       }      
   484       for (int i = 0; i < n; ++i) {
   485         _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
   486       }
   487       return true;
   488     }
   489 
   490     // Process all rounds of computing path data for the current component.
   491     // _data[v][k] is the length of a shortest directed walk from the root
   492     // node to node v containing exactly k arcs.
   493     void processRounds() {
   494       Node start = (*_nodes)[0];
   495       _data[start][0] = PathData(0);
   496       _process.clear();
   497       _process.push_back(start);
   498 
   499       int k, n = _nodes->size();
   500       for (k = 1; k <= n && int(_process.size()) < n; ++k) {
   501         processNextBuildRound(k);
   502       }
   503       for ( ; k <= n; ++k) {
   504         processNextFullRound(k);
   505       }
   506     }
   507 
   508     // Process one round and rebuild _process
   509     void processNextBuildRound(int k) {
   510       std::vector<Node> next;
   511       Node u, v;
   512       Arc e;
   513       LargeValue d;
   514       for (int i = 0; i < int(_process.size()); ++i) {
   515         u = _process[i];
   516         for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
   517           e = _out_arcs[u][j];
   518           v = _gr.target(e);
   519           d = _data[u][k-1].dist + _length[e];
   520           if (_tolerance.less(d, _data[v][k].dist)) {
   521             if (_data[v][k].dist == INF) next.push_back(v);
   522             _data[v][k] = PathData(d, e);
   523           }
   524         }
   525       }
   526       _process.swap(next);
   527     }
   528 
   529     // Process one round using _nodes instead of _process
   530     void processNextFullRound(int k) {
   531       Node u, v;
   532       Arc e;
   533       LargeValue d;
   534       for (int i = 0; i < int(_nodes->size()); ++i) {
   535         u = (*_nodes)[i];
   536         for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
   537           e = _out_arcs[u][j];
   538           v = _gr.target(e);
   539           d = _data[u][k-1].dist + _length[e];
   540           if (_tolerance.less(d, _data[v][k].dist)) {
   541             _data[v][k] = PathData(d, e);
   542           }
   543         }
   544       }
   545     }
   546 
   547     // Update the minimum cycle mean
   548     void updateMinMean() {
   549       int n = _nodes->size();
   550       for (int i = 0; i < n; ++i) {
   551         Node u = (*_nodes)[i];
   552         if (_data[u][n].dist == INF) continue;
   553         LargeValue length, max_length = 0;
   554         int size, max_size = 1;
   555         bool found_curr = false;
   556         for (int k = 0; k < n; ++k) {
   557           if (_data[u][k].dist == INF) continue;
   558           length = _data[u][n].dist - _data[u][k].dist;
   559           size = n - k;
   560           if (!found_curr || length * max_size > max_length * size) {
   561             found_curr = true;
   562             max_length = length;
   563             max_size = size;
   564           }
   565         }
   566         if ( found_curr && (_cycle_node == INVALID ||
   567              max_length * _cycle_size < _cycle_length * max_size) ) {
   568           _cycle_length = max_length;
   569           _cycle_size = max_size;
   570           _cycle_node = u;
   571         }
   572       }
   573     }
   574 
   575   }; //class Karp
   576 
   577   ///@}
   578 
   579 } //namespace lemon
   580 
   581 #endif //LEMON_KARP_H