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