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