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