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