Avoid ambiguity.
2 * lemon/kruskal.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
17 #ifndef LEMON_KRUSKAL_H
18 #define LEMON_KRUSKAL_H
21 #include <lemon/unionfind.h>
22 #include<lemon/utility.h>
25 @defgroup spantree Minimum Cost Spanning Tree Algorithms
27 \brief This group containes the algorithms for finding a minimum cost spanning
30 This group containes the algorithms for finding a minimum cost spanning
36 ///\brief Kruskal's algorithm to compute a minimum cost tree
38 ///Kruskal's algorithm to compute a minimum cost tree.
42 /// \addtogroup spantree
45 /// Kruskal's algorithm to find a minimum cost tree of a graph.
47 /// This function runs Kruskal's algorithm to find a minimum cost tree.
48 /// \param g The graph the algorithm runs on.
49 /// It can be either \ref concept::StaticGraph "directed" or
50 /// \ref concept::UndirStaticGraph "undirected".
51 /// If the graph is directed, the algorithm consider it to be
52 /// undirected by disregarding the direction of the edges.
54 /// \param in This object is used to describe the edge costs. It must
55 /// be an STL compatible 'Forward Container'
56 /// with <tt>std::pair<GR::Edge,X></tt> as its <tt>value_type</tt>,
57 /// where X is the type of the costs. It must contain every edge in
58 /// cost-ascending order.
60 /// For the sake of simplicity, there is a helper class KruskalMapInput,
62 /// simple edge map to an input of this form. Alternatively, you can use
63 /// the function \ref kruskalEdgeMap to compute the minimum cost tree if
64 /// the edge costs are given by an edge map.
66 /// \retval out This must be a writable \c bool edge map.
67 /// After running the algorithm
68 /// this will contain the found minimum cost spanning tree: the value of an
69 /// edge will be set to \c true if it belongs to the tree, otherwise it will
70 /// be set to \c false. The value of each edge will be set exactly once.
72 /// \return The cost of the found tree.
74 /// \todo Discuss the case of undirected graphs: In this case the algorithm
75 /// also require <tt>Edge</tt>s instead of <tt>UndirEdge</tt>s, as some
76 /// people would expect. So, one should be careful not to add both of the
77 /// <tt>Edge</tt>s belonging to a certain <tt>UndirEdge</tt>.
78 /// (\ref kruskalEdgeMap() and \ref KruskalMapInput are kind enough to do so.)
80 template <class GR, class IN, class OUT>
81 typename IN::value_type::second_type
82 kruskal(GR const& g, IN const& in,
85 typedef typename IN::value_type::second_type EdgeCost;
86 typedef typename GR::template NodeMap<int> NodeIntMap;
87 typedef typename GR::Node Node;
89 NodeIntMap comp(g, -1);
90 UnionFind<Node,NodeIntMap> uf(comp);
92 EdgeCost tot_cost = 0;
93 for (typename IN::const_iterator p = in.begin();
95 if ( uf.join(g.target((*p).first),
96 g.source((*p).first)) ) {
97 out.set((*p).first, true);
98 tot_cost += (*p).second;
101 out.set((*p).first, false);
107 /* A work-around for running Kruskal with const-reference bool maps... */
109 /// Helper class for calling kruskal with "constant" output map.
111 /// Helper class for calling kruskal with output maps constructed
114 /// A typical examle is the following call:
115 /// <tt>kruskal(g, some_input, makeSequenceOutput(iterator))</tt>.
116 /// Here, the third argument is a temporary object (which wraps around an
117 /// iterator with a writable bool map interface), and thus by rules of C++
118 /// is a \c const object. To enable call like this exist this class and
119 /// the prototype of the \ref kruskal() function with <tt>const& OUT</tt>
122 class NonConstMapWr {
125 typedef typename Map::Value Value;
127 NonConstMapWr(const Map &_m) : m(_m) {}
130 void set(Key const& k, Value const &v) const { m.set(k,v); }
133 template <class GR, class IN, class OUT>
135 typename IN::value_type::second_type
136 kruskal(GR const& g, IN const& edges, OUT const& out_map)
138 NonConstMapWr<OUT> map_wr(out_map);
139 return kruskal(g, edges, map_wr);
142 /* ** ** Input-objects ** ** */
144 /// Kruskal's input source.
146 /// Kruskal's input source.
148 /// In most cases you possibly want to use the \ref kruskalEdgeMap() instead.
150 /// \sa makeKruskalMapInput()
152 ///\param GR The type of the graph the algorithm runs on.
153 ///\param Map An edge map containing the cost of the edges.
155 ///The cost type can be any type satisfying
156 ///the STL 'LessThan comparable'
157 ///concept if it also has an operator+() implemented. (It is necessary for
158 ///computing the total cost of the tree).
160 template<class GR, class Map>
161 class KruskalMapInput
162 : public std::vector< std::pair<typename GR::Edge,
163 typename Map::Value> > {
166 typedef std::vector< std::pair<typename GR::Edge,
167 typename Map::Value> > Parent;
168 typedef typename Parent::value_type value_type;
173 bool operator()(const value_type& a,
174 const value_type& b) {
175 return a.second < b.second;
180 typename enable_if<typename _GR::UndirTag,void>::type
181 fillWithEdges(const _GR& g, const Map& m,dummy<0> = 0)
183 for(typename GR::UndirEdgeIt e(g);e!=INVALID;++e)
184 push_back(value_type(typename GR::Edge(e,true), m[e]));
188 typename disable_if<typename _GR::UndirTag,void>::type
189 fillWithEdges(const _GR& g, const Map& m,dummy<1> = 1)
191 for(typename GR::EdgeIt e(g);e!=INVALID;++e)
192 push_back(value_type(e, m[e]));
199 std::sort(this->begin(), this->end(), comparePair());
202 KruskalMapInput(GR const& g, Map const& m) {
208 /// Creates a KruskalMapInput object for \ref kruskal()
210 /// It makes easier to use
211 /// \ref KruskalMapInput by making it unnecessary
212 /// to explicitly give the type of the parameters.
214 /// In most cases you possibly
215 /// want to use the function kruskalEdgeMap() instead.
217 ///\param g The type of the graph the algorithm runs on.
218 ///\param m An edge map containing the cost of the edges.
220 ///The cost type can be any type satisfying the
221 ///STL 'LessThan Comparable'
222 ///concept if it also has an operator+() implemented. (It is necessary for
223 ///computing the total cost of the tree).
225 ///\return An appropriate input source for \ref kruskal().
227 template<class GR, class Map>
229 KruskalMapInput<GR,Map> makeKruskalMapInput(const GR &g,const Map &m)
231 return KruskalMapInput<GR,Map>(g,m);
236 /* ** ** Output-objects: simple writable bool maps ** ** */
240 /// A writable bool-map that makes a sequence of "true" keys
242 /// A writable bool-map that creates a sequence out of keys that receives
243 /// the value "true".
245 /// \sa makeKruskalSequenceOutput()
247 /// Very often, when looking for a min cost spanning tree, we want as
248 /// output a container containing the edges of the found tree. For this
249 /// purpose exist this class that wraps around an STL iterator with a
250 /// writable bool map interface. When a key gets value "true" this key
251 /// is added to sequence pointed by the iterator.
255 /// std::vector<Graph::Edge> v;
256 /// kruskal(g, input, makeKruskalSequenceOutput(back_inserter(v)));
259 /// For the most common case, when the input is given by a simple edge
260 /// map and the output is a sequence of the tree edges, a special
261 /// wrapper function exists: \ref kruskalEdgeMap_IteratorOut().
263 /// \warning Not a regular property map, as it doesn't know its Key
265 template<class Iterator>
266 class KruskalSequenceOutput {
272 KruskalSequenceOutput(Iterator const &_it) : it(_it) {}
274 template<typename Key>
275 void set(Key const& k, bool v) const { if(v) {*it=k; ++it;} }
278 template<class Iterator>
280 KruskalSequenceOutput<Iterator>
281 makeKruskalSequenceOutput(Iterator it) {
282 return KruskalSequenceOutput<Iterator>(it);
287 /* ** ** Wrapper funtions ** ** */
291 /// \brief Wrapper function to kruskal().
292 /// Input is from an edge map, output is a plain bool map.
294 /// Wrapper function to kruskal().
295 /// Input is from an edge map, output is a plain bool map.
297 ///\param g The type of the graph the algorithm runs on.
298 ///\param in An edge map containing the cost of the edges.
300 ///The cost type can be any type satisfying the
301 ///STL 'LessThan Comparable'
302 ///concept if it also has an operator+() implemented. (It is necessary for
303 ///computing the total cost of the tree).
305 /// \retval out This must be a writable \c bool edge map.
306 /// After running the algorithm
307 /// this will contain the found minimum cost spanning tree: the value of an
308 /// edge will be set to \c true if it belongs to the tree, otherwise it will
309 /// be set to \c false. The value of each edge will be set exactly once.
311 /// \return The cost of the found tree.
313 template <class GR, class IN, class RET>
316 kruskalEdgeMap(GR const& g,
320 KruskalMapInput<GR,IN>(g,in),
324 /// \brief Wrapper function to kruskal().
325 /// Input is from an edge map, output is an STL Sequence.
327 /// Wrapper function to kruskal().
328 /// Input is from an edge map, output is an STL Sequence.
330 ///\param g The type of the graph the algorithm runs on.
331 ///\param in An edge map containing the cost of the edges.
333 ///The cost type can be any type satisfying the
334 ///STL 'LessThan Comparable'
335 ///concept if it also has an operator+() implemented. (It is necessary for
336 ///computing the total cost of the tree).
338 /// \retval out This must be an iteraror of an STL Container with
339 /// <tt>GR::Edge</tt> as its <tt>value_type</tt>.
340 /// The algorithm copies the elements of the found tree into this sequence.
341 /// For example, if we know that the spanning tree of the graph \c g has
342 /// say 53 edges then
343 /// we can put its edges into a STL vector \c tree with a code like this.
345 /// std::vector<Edge> tree(53);
346 /// kruskalEdgeMap_IteratorOut(g,cost,tree.begin());
348 /// Or if we don't know in advance the size of the tree, we can write this.
350 /// std::vector<Edge> tree;
351 /// kruskalEdgeMap_IteratorOut(g,cost,std::back_inserter(tree));
354 /// \return The cost of the found tree.
356 /// \bug its name does not follow the coding style.
358 template <class GR, class IN, class RET>
361 kruskalEdgeMap_IteratorOut(const GR& g,
365 KruskalSequenceOutput<RET> _out(out);
366 return kruskal(g, KruskalMapInput<GR,IN>(g, in), _out);
373 #endif //LEMON_KRUSKAL_H