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