COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/kruskal.h @ 2377:83775fab25dc

Last change on this file since 2377:83775fab25dc was 2354:3609c77b77be, checked in by Alpar Juttner, 17 years ago

Doc improvements

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