lemon/kruskal.h
author alpar
Mon, 13 Nov 2006 18:46:19 +0000
changeset 2301 eb378706bd3d
parent 2259 da142c310d02
child 2308 cddae1c4fee6
permissions -rw-r--r--
Test the automatic compilation checker 1/2: make a bug
alpar@906
     1
/* -*- C++ -*-
alpar@906
     2
 *
alpar@1956
     3
 * This file is a part of LEMON, a generic C++ optimization library
alpar@1956
     4
 *
alpar@1956
     5
 * Copyright (C) 2003-2006
alpar@1956
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@1359
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@906
     8
 *
alpar@906
     9
 * Permission to use, modify and distribute this software is granted
alpar@906
    10
 * provided that this copyright notice appears in all copies. For
alpar@906
    11
 * precise terms see the accompanying LICENSE file.
alpar@906
    12
 *
alpar@906
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@906
    14
 * express or implied, and with no claim as to its suitability for any
alpar@906
    15
 * purpose.
alpar@906
    16
 *
alpar@906
    17
 */
alpar@906
    18
alpar@921
    19
#ifndef LEMON_KRUSKAL_H
alpar@921
    20
#define LEMON_KRUSKAL_H
alpar@810
    21
alpar@810
    22
#include <algorithm>
klao@1942
    23
#include <vector>
alpar@921
    24
#include <lemon/unionfind.h>
deba@1993
    25
#include <lemon/bits/utility.h>
deba@1993
    26
#include <lemon/bits/traits.h>
alpar@810
    27
alpar@810
    28
///\ingroup spantree
alpar@810
    29
///\file
alpar@810
    30
///\brief Kruskal's algorithm to compute a minimum cost tree
alpar@810
    31
///
alpar@810
    32
///Kruskal's algorithm to compute a minimum cost tree.
alpar@1557
    33
///
alpar@1557
    34
///\todo The file still needs some clean-up.
alpar@810
    35
alpar@921
    36
namespace lemon {
alpar@810
    37
alpar@810
    38
  /// \addtogroup spantree
alpar@810
    39
  /// @{
alpar@810
    40
alpar@810
    41
  /// Kruskal's algorithm to find a minimum cost tree of a graph.
alpar@810
    42
alpar@810
    43
  /// This function runs Kruskal's algorithm to find a minimum cost tree.
alpar@1557
    44
  /// Due to hard C++ hacking, it accepts various input and output types.
alpar@1557
    45
  ///
alpar@1555
    46
  /// \param g The graph the algorithm runs on.
alpar@2260
    47
  /// It can be either \ref concepts::Graph "directed" or 
alpar@2260
    48
  /// \ref concepts::UGraph "undirected".
alpar@1555
    49
  /// If the graph is directed, the algorithm consider it to be 
alpar@1555
    50
  /// undirected by disregarding the direction of the edges.
alpar@810
    51
  ///
alpar@1557
    52
  /// \param in This object is used to describe the edge costs. It can be one
alpar@1557
    53
  /// of the following choices.
alpar@1557
    54
  /// - An STL compatible 'Forward Container'
alpar@824
    55
  /// with <tt>std::pair<GR::Edge,X></tt> as its <tt>value_type</tt>,
alpar@1557
    56
  /// where \c X is the type of the costs. The pairs indicates the edges along
alpar@1557
    57
  /// with the assigned cost. <em>They must be in a
alpar@1557
    58
  /// cost-ascending order.</em>
alpar@1557
    59
  /// - Any readable Edge map. The values of the map indicate the edge costs.
alpar@810
    60
  ///
alpar@1557
    61
  /// \retval out Here we also have a choise.
alpar@2259
    62
  /// - It can be a writable \c bool edge map. 
alpar@810
    63
  /// After running the algorithm
alpar@810
    64
  /// this will contain the found minimum cost spanning tree: the value of an
alpar@810
    65
  /// edge will be set to \c true if it belongs to the tree, otherwise it will
alpar@810
    66
  /// be set to \c false. The value of each edge will be set exactly once.
alpar@1557
    67
  /// - It can also be an iteraror of an STL Container with
alpar@1557
    68
  /// <tt>GR::Edge</tt> as its <tt>value_type</tt>.
alpar@1557
    69
  /// The algorithm copies the elements of the found tree into this sequence.
alpar@1557
    70
  /// For example, if we know that the spanning tree of the graph \c g has
alpar@1603
    71
  /// say 53 edges, then
alpar@2259
    72
  /// we can put its edges into an STL vector \c tree with a code like this.
alpar@1946
    73
  ///\code
alpar@1557
    74
  /// std::vector<Edge> tree(53);
alpar@1557
    75
  /// kruskal(g,cost,tree.begin());
alpar@1946
    76
  ///\endcode
alpar@1557
    77
  /// Or if we don't know in advance the size of the tree, we can write this.
alpar@1946
    78
  ///\code
alpar@1557
    79
  /// std::vector<Edge> tree;
alpar@1557
    80
  /// kruskal(g,cost,std::back_inserter(tree));
alpar@1946
    81
  ///\endcode
alpar@810
    82
  ///
alpar@810
    83
  /// \return The cost of the found tree.
alpar@1449
    84
  ///
alpar@2259
    85
  /// \warning If kruskal runs on an
alpar@2260
    86
  /// \ref lemon::concepts::UGraph "undirected graph", be sure that the
alpar@1603
    87
  /// map storing the tree is also undirected
klao@1909
    88
  /// (e.g. ListUGraph::UEdgeMap<bool>, otherwise the values of the
alpar@1603
    89
  /// half of the edges will not be set.
alpar@1603
    90
  ///
alpar@1449
    91
  /// \todo Discuss the case of undirected graphs: In this case the algorithm
klao@1909
    92
  /// also require <tt>Edge</tt>s instead of <tt>UEdge</tt>s, as some
alpar@1449
    93
  /// people would expect. So, one should be careful not to add both of the
klao@1909
    94
  /// <tt>Edge</tt>s belonging to a certain <tt>UEdge</tt>.
alpar@1570
    95
  /// (\ref kruskal() and \ref KruskalMapInput are kind enough to do so.)
alpar@810
    96
alpar@1557
    97
#ifdef DOXYGEN
alpar@824
    98
  template <class GR, class IN, class OUT>
alpar@824
    99
  typename IN::value_type::second_type
alpar@1547
   100
  kruskal(GR const& g, IN const& in, 
alpar@1557
   101
	  OUT& out)
alpar@1557
   102
#else
alpar@1557
   103
  template <class GR, class IN, class OUT>
alpar@1557
   104
  typename IN::value_type::second_type
alpar@1557
   105
  kruskal(GR const& g, IN const& in, 
alpar@1557
   106
	  OUT& out,
alpar@1557
   107
// 	  typename IN::value_type::first_type = typename GR::Edge()
alpar@1557
   108
// 	  ,typename OUT::Key = OUT::Key()
alpar@1557
   109
// 	  //,typename OUT::Key = typename GR::Edge()
alpar@1557
   110
	  const typename IN::value_type::first_type * = 
alpar@1557
   111
	  (const typename IN::value_type::first_type *)(0),
alpar@1557
   112
	  const typename OUT::Key * = (const typename OUT::Key *)(0)
alpar@1557
   113
	  )
alpar@1557
   114
#endif
alpar@810
   115
  {
alpar@824
   116
    typedef typename IN::value_type::second_type EdgeCost;
alpar@824
   117
    typedef typename GR::template NodeMap<int> NodeIntMap;
alpar@824
   118
    typedef typename GR::Node Node;
alpar@810
   119
deba@2205
   120
    NodeIntMap comp(g);
deba@2205
   121
    UnionFind<Node,NodeIntMap> uf(comp);
deba@2205
   122
    for (typename GR::NodeIt it(g); it != INVALID; ++it) {
deba@2205
   123
      uf.insert(it);
deba@2205
   124
    }
alpar@810
   125
      
alpar@810
   126
    EdgeCost tot_cost = 0;
alpar@824
   127
    for (typename IN::const_iterator p = in.begin(); 
alpar@810
   128
	 p!=in.end(); ++p ) {
alpar@1547
   129
      if ( uf.join(g.target((*p).first),
alpar@1547
   130
		   g.source((*p).first)) ) {
alpar@810
   131
	out.set((*p).first, true);
alpar@810
   132
	tot_cost += (*p).second;
alpar@810
   133
      }
alpar@810
   134
      else {
alpar@810
   135
	out.set((*p).first, false);
alpar@810
   136
      }
alpar@810
   137
    }
alpar@810
   138
    return tot_cost;
alpar@810
   139
  }
alpar@810
   140
alpar@1557
   141
 
alpar@1557
   142
  /// @}
alpar@1557
   143
alpar@1557
   144
  
alpar@810
   145
  /* A work-around for running Kruskal with const-reference bool maps... */
alpar@810
   146
klao@885
   147
  /// Helper class for calling kruskal with "constant" output map.
klao@885
   148
klao@885
   149
  /// Helper class for calling kruskal with output maps constructed
klao@885
   150
  /// on-the-fly.
alpar@810
   151
  ///
klao@885
   152
  /// A typical examle is the following call:
alpar@1547
   153
  /// <tt>kruskal(g, some_input, makeSequenceOutput(iterator))</tt>.
klao@885
   154
  /// Here, the third argument is a temporary object (which wraps around an
klao@885
   155
  /// iterator with a writable bool map interface), and thus by rules of C++
klao@885
   156
  /// is a \c const object. To enable call like this exist this class and
klao@885
   157
  /// the prototype of the \ref kruskal() function with <tt>const& OUT</tt>
klao@885
   158
  /// third argument.
alpar@824
   159
  template<class Map>
alpar@810
   160
  class NonConstMapWr {
alpar@810
   161
    const Map &m;
alpar@810
   162
  public:
alpar@1557
   163
    typedef typename Map::Key Key;
alpar@987
   164
    typedef typename Map::Value Value;
alpar@810
   165
alpar@810
   166
    NonConstMapWr(const Map &_m) : m(_m) {}
alpar@810
   167
alpar@987
   168
    template<class Key>
alpar@987
   169
    void set(Key const& k, Value const &v) const { m.set(k,v); }
alpar@810
   170
  };
alpar@810
   171
alpar@824
   172
  template <class GR, class IN, class OUT>
alpar@810
   173
  inline
klao@885
   174
  typename IN::value_type::second_type
alpar@1557
   175
  kruskal(GR const& g, IN const& edges, OUT const& out_map,
alpar@1557
   176
// 	  typename IN::value_type::first_type = typename GR::Edge(),
alpar@1557
   177
// 	  typename OUT::Key = GR::Edge()
alpar@1557
   178
	  const typename IN::value_type::first_type * = 
alpar@1557
   179
	  (const typename IN::value_type::first_type *)(0),
alpar@1557
   180
	  const typename OUT::Key * = (const typename OUT::Key *)(0)
alpar@1557
   181
	  )
alpar@810
   182
  {
alpar@824
   183
    NonConstMapWr<OUT> map_wr(out_map);
alpar@1547
   184
    return kruskal(g, edges, map_wr);
alpar@810
   185
  }  
alpar@810
   186
alpar@810
   187
  /* ** ** Input-objects ** ** */
alpar@810
   188
zsuzska@1274
   189
  /// Kruskal's input source.
alpar@1557
   190
 
zsuzska@1274
   191
  /// Kruskal's input source.
alpar@810
   192
  ///
alpar@1570
   193
  /// In most cases you possibly want to use the \ref kruskal() instead.
alpar@810
   194
  ///
alpar@810
   195
  /// \sa makeKruskalMapInput()
alpar@810
   196
  ///
alpar@824
   197
  ///\param GR The type of the graph the algorithm runs on.
alpar@810
   198
  ///\param Map An edge map containing the cost of the edges.
alpar@810
   199
  ///\par
alpar@810
   200
  ///The cost type can be any type satisfying
alpar@810
   201
  ///the STL 'LessThan comparable'
alpar@810
   202
  ///concept if it also has an operator+() implemented. (It is necessary for
alpar@810
   203
  ///computing the total cost of the tree).
alpar@810
   204
  ///
alpar@824
   205
  template<class GR, class Map>
alpar@810
   206
  class KruskalMapInput
alpar@824
   207
    : public std::vector< std::pair<typename GR::Edge,
alpar@987
   208
				    typename Map::Value> > {
alpar@810
   209
    
alpar@810
   210
  public:
alpar@824
   211
    typedef std::vector< std::pair<typename GR::Edge,
alpar@987
   212
				   typename Map::Value> > Parent;
alpar@810
   213
    typedef typename Parent::value_type value_type;
alpar@810
   214
alpar@810
   215
  private:
alpar@810
   216
    class comparePair {
alpar@810
   217
    public:
alpar@810
   218
      bool operator()(const value_type& a,
alpar@810
   219
		      const value_type& b) {
alpar@810
   220
	return a.second < b.second;
alpar@810
   221
      }
alpar@810
   222
    };
alpar@810
   223
alpar@1449
   224
    template<class _GR>
deba@1979
   225
    typename enable_if<UndirectedTagIndicator<_GR>,void>::type
alpar@1547
   226
    fillWithEdges(const _GR& g, const Map& m,dummy<0> = 0) 
alpar@1449
   227
    {
klao@1909
   228
      for(typename GR::UEdgeIt e(g);e!=INVALID;++e) 
deba@1679
   229
	push_back(value_type(g.direct(e, true), m[e]));
alpar@1449
   230
    }
alpar@1449
   231
alpar@1449
   232
    template<class _GR>
deba@1979
   233
    typename disable_if<UndirectedTagIndicator<_GR>,void>::type
alpar@1547
   234
    fillWithEdges(const _GR& g, const Map& m,dummy<1> = 1) 
alpar@1449
   235
    {
alpar@1547
   236
      for(typename GR::EdgeIt e(g);e!=INVALID;++e) 
alpar@1449
   237
	push_back(value_type(e, m[e]));
alpar@1449
   238
    }
alpar@1449
   239
    
alpar@1449
   240
    
alpar@810
   241
  public:
alpar@810
   242
alpar@810
   243
    void sort() {
alpar@810
   244
      std::sort(this->begin(), this->end(), comparePair());
alpar@810
   245
    }
alpar@810
   246
alpar@1547
   247
    KruskalMapInput(GR const& g, Map const& m) {
alpar@1547
   248
      fillWithEdges(g,m); 
alpar@810
   249
      sort();
alpar@810
   250
    }
alpar@810
   251
  };
alpar@810
   252
alpar@810
   253
  /// Creates a KruskalMapInput object for \ref kruskal()
alpar@810
   254
zsuzska@1274
   255
  /// It makes easier to use 
alpar@810
   256
  /// \ref KruskalMapInput by making it unnecessary 
alpar@810
   257
  /// to explicitly give the type of the parameters.
alpar@810
   258
  ///
alpar@810
   259
  /// In most cases you possibly
alpar@1570
   260
  /// want to use \ref kruskal() instead.
alpar@810
   261
  ///
alpar@1547
   262
  ///\param g The type of the graph the algorithm runs on.
alpar@810
   263
  ///\param m An edge map containing the cost of the edges.
alpar@810
   264
  ///\par
alpar@810
   265
  ///The cost type can be any type satisfying the
alpar@810
   266
  ///STL 'LessThan Comparable'
alpar@810
   267
  ///concept if it also has an operator+() implemented. (It is necessary for
alpar@810
   268
  ///computing the total cost of the tree).
alpar@810
   269
  ///
alpar@810
   270
  ///\return An appropriate input source for \ref kruskal().
alpar@810
   271
  ///
alpar@824
   272
  template<class GR, class Map>
alpar@810
   273
  inline
alpar@1547
   274
  KruskalMapInput<GR,Map> makeKruskalMapInput(const GR &g,const Map &m)
alpar@810
   275
  {
alpar@1547
   276
    return KruskalMapInput<GR,Map>(g,m);
alpar@810
   277
  }
alpar@810
   278
  
alpar@810
   279
  
klao@885
   280
klao@885
   281
  /* ** ** Output-objects: simple writable bool maps ** ** */
alpar@810
   282
  
klao@885
   283
klao@885
   284
alpar@810
   285
  /// A writable bool-map that makes a sequence of "true" keys
alpar@810
   286
alpar@810
   287
  /// A writable bool-map that creates a sequence out of keys that receives
alpar@810
   288
  /// the value "true".
klao@885
   289
  ///
klao@885
   290
  /// \sa makeKruskalSequenceOutput()
klao@885
   291
  ///
klao@885
   292
  /// Very often, when looking for a min cost spanning tree, we want as
klao@885
   293
  /// output a container containing the edges of the found tree. For this
klao@885
   294
  /// purpose exist this class that wraps around an STL iterator with a
klao@885
   295
  /// writable bool map interface. When a key gets value "true" this key
klao@885
   296
  /// is added to sequence pointed by the iterator.
klao@885
   297
  ///
klao@885
   298
  /// A typical usage:
alpar@1946
   299
  ///\code
klao@885
   300
  /// std::vector<Graph::Edge> v;
klao@885
   301
  /// kruskal(g, input, makeKruskalSequenceOutput(back_inserter(v)));
alpar@1946
   302
  ///\endcode
klao@885
   303
  /// 
klao@885
   304
  /// For the most common case, when the input is given by a simple edge
klao@885
   305
  /// map and the output is a sequence of the tree edges, a special
klao@885
   306
  /// wrapper function exists: \ref kruskalEdgeMap_IteratorOut().
klao@885
   307
  ///
alpar@987
   308
  /// \warning Not a regular property map, as it doesn't know its Key
klao@885
   309
alpar@824
   310
  template<class Iterator>
klao@885
   311
  class KruskalSequenceOutput {
alpar@810
   312
    mutable Iterator it;
alpar@810
   313
alpar@810
   314
  public:
klao@1942
   315
    typedef typename std::iterator_traits<Iterator>::value_type Key;
alpar@987
   316
    typedef bool Value;
alpar@810
   317
klao@885
   318
    KruskalSequenceOutput(Iterator const &_it) : it(_it) {}
alpar@810
   319
alpar@987
   320
    template<typename Key>
alpar@987
   321
    void set(Key const& k, bool v) const { if(v) {*it=k; ++it;} }
alpar@810
   322
  };
alpar@810
   323
alpar@824
   324
  template<class Iterator>
alpar@810
   325
  inline
klao@885
   326
  KruskalSequenceOutput<Iterator>
klao@885
   327
  makeKruskalSequenceOutput(Iterator it) {
klao@885
   328
    return KruskalSequenceOutput<Iterator>(it);
alpar@810
   329
  }
alpar@810
   330
klao@885
   331
klao@885
   332
alpar@810
   333
  /* ** ** Wrapper funtions ** ** */
alpar@810
   334
alpar@1557
   335
//   \brief Wrapper function to kruskal().
alpar@1557
   336
//   Input is from an edge map, output is a plain bool map.
alpar@1557
   337
//  
alpar@1557
   338
//   Wrapper function to kruskal().
alpar@1557
   339
//   Input is from an edge map, output is a plain bool map.
alpar@1557
   340
//  
alpar@1557
   341
//   \param g The type of the graph the algorithm runs on.
alpar@1557
   342
//   \param in An edge map containing the cost of the edges.
alpar@1557
   343
//   \par
alpar@1557
   344
//   The cost type can be any type satisfying the
alpar@1557
   345
//   STL 'LessThan Comparable'
alpar@1557
   346
//   concept if it also has an operator+() implemented. (It is necessary for
alpar@1557
   347
//   computing the total cost of the tree).
alpar@1557
   348
//  
alpar@1557
   349
//   \retval out This must be a writable \c bool edge map.
alpar@1557
   350
//   After running the algorithm
alpar@1557
   351
//   this will contain the found minimum cost spanning tree: the value of an
alpar@1557
   352
//   edge will be set to \c true if it belongs to the tree, otherwise it will
alpar@1557
   353
//   be set to \c false. The value of each edge will be set exactly once.
alpar@1557
   354
//  
alpar@1557
   355
//   \return The cost of the found tree.
alpar@810
   356
alpar@824
   357
  template <class GR, class IN, class RET>
alpar@810
   358
  inline
alpar@987
   359
  typename IN::Value
alpar@1557
   360
  kruskal(GR const& g,
alpar@1557
   361
	  IN const& in,
alpar@1557
   362
	  RET &out,
alpar@1557
   363
	  //	  typename IN::Key = typename GR::Edge(),
alpar@1557
   364
	  //typename IN::Key = typename IN::Key (),
alpar@1557
   365
	  //	  typename RET::Key = typename GR::Edge()
alpar@1557
   366
	  const typename IN::Key *  = (const typename IN::Key *)(0),
alpar@1557
   367
	  const typename RET::Key * = (const typename RET::Key *)(0)
alpar@1557
   368
	  )
alpar@1557
   369
  {
alpar@1547
   370
    return kruskal(g,
alpar@1547
   371
		   KruskalMapInput<GR,IN>(g,in),
alpar@810
   372
		   out);
alpar@810
   373
  }
alpar@810
   374
alpar@1557
   375
//   \brief Wrapper function to kruskal().
alpar@1557
   376
//   Input is from an edge map, output is an STL Sequence.
alpar@1557
   377
//  
alpar@1557
   378
//   Wrapper function to kruskal().
alpar@1557
   379
//   Input is from an edge map, output is an STL Sequence.
alpar@1557
   380
//  
alpar@1557
   381
//   \param g The type of the graph the algorithm runs on.
alpar@1557
   382
//   \param in An edge map containing the cost of the edges.
alpar@1557
   383
//   \par
alpar@1557
   384
//   The cost type can be any type satisfying the
alpar@1557
   385
//   STL 'LessThan Comparable'
alpar@1557
   386
//   concept if it also has an operator+() implemented. (It is necessary for
alpar@1557
   387
//   computing the total cost of the tree).
alpar@1557
   388
//  
alpar@1557
   389
//   \retval out This must be an iteraror of an STL Container with
alpar@1557
   390
//   <tt>GR::Edge</tt> as its <tt>value_type</tt>.
alpar@1557
   391
//   The algorithm copies the elements of the found tree into this sequence.
alpar@1557
   392
//   For example, if we know that the spanning tree of the graph \c g has
alpar@1603
   393
//   say 53 edges, then
alpar@2259
   394
//   we can put its edges into an STL vector \c tree with a code like this.
alpar@1946
   395
//\code
alpar@1557
   396
//   std::vector<Edge> tree(53);
alpar@1570
   397
//   kruskal(g,cost,tree.begin());
alpar@1946
   398
//\endcode
alpar@1557
   399
//   Or if we don't know in advance the size of the tree, we can write this.
alpar@1946
   400
//\code
alpar@1557
   401
//   std::vector<Edge> tree;
alpar@1570
   402
//   kruskal(g,cost,std::back_inserter(tree));
alpar@1946
   403
//\endcode
alpar@1557
   404
//  
alpar@1557
   405
//   \return The cost of the found tree.
alpar@1557
   406
//  
alpar@1557
   407
//   \bug its name does not follow the coding style.
klao@885
   408
alpar@824
   409
  template <class GR, class IN, class RET>
alpar@810
   410
  inline
alpar@987
   411
  typename IN::Value
alpar@1557
   412
  kruskal(const GR& g,
alpar@1557
   413
	  const IN& in,
alpar@1557
   414
	  RET out,
alpar@1557
   415
	  const typename RET::value_type * = 
alpar@1557
   416
	  (const typename RET::value_type *)(0)
alpar@1557
   417
	  )
alpar@810
   418
  {
klao@885
   419
    KruskalSequenceOutput<RET> _out(out);
alpar@1547
   420
    return kruskal(g, KruskalMapInput<GR,IN>(g, in), _out);
alpar@810
   421
  }
alpar@1557
   422
 
klao@1942
   423
  template <class GR, class IN, class RET>
klao@1942
   424
  inline
klao@1942
   425
  typename IN::Value
klao@1942
   426
  kruskal(const GR& g,
klao@1942
   427
	  const IN& in,
klao@1942
   428
	  RET *out
klao@1942
   429
	  )
klao@1942
   430
  {
klao@1942
   431
    KruskalSequenceOutput<RET*> _out(out);
klao@1942
   432
    return kruskal(g, KruskalMapInput<GR,IN>(g, in), _out);
klao@1942
   433
  }
klao@1942
   434
 
alpar@810
   435
  /// @}
alpar@810
   436
alpar@921
   437
} //namespace lemon
alpar@810
   438
alpar@921
   439
#endif //LEMON_KRUSKAL_H