3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
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.
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
19 #ifndef LEMON_KRUSKAL_H
20 #define LEMON_KRUSKAL_H
24 #include <lemon/unionfind.h>
25 #include <lemon/graph_utils.h>
26 #include <lemon/maps.h>
28 #include <lemon/radix_sort.h>
30 #include <lemon/bits/utility.h>
31 #include <lemon/bits/traits.h>
35 ///\brief Kruskal's algorithm to compute a minimum cost tree
37 ///Kruskal's algorithm to compute a minimum cost tree.
42 namespace _kruskal_bits {
44 template <typename Map, typename Comp>
47 typedef typename Map::Key Key;
52 MappedComp(const Map& _map)
53 : map(_map), comp() {}
55 bool operator()(const Key& left, const Key& right) {
56 return comp(map[left], map[right]);
63 /// \brief Default traits class of Kruskal class.
65 /// Default traits class of Kruskal class.
66 /// \param _UGraph Undirected graph type.
67 /// \param _CostMap Type of cost map.
68 template <typename _UGraph, typename _CostMap>
69 struct KruskalDefaultTraits{
71 /// \brief The graph type the algorithm runs on.
72 typedef _UGraph UGraph;
74 /// \brief The type of the map that stores the edge costs.
76 /// The type of the map that stores the edge costs.
77 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
78 typedef _CostMap CostMap;
80 /// \brief The type of the cost of the edges.
81 typedef typename _CostMap::Value Value;
83 /// \brief The type of the map that stores whether an edge is in the
84 /// spanning tree or not.
86 /// The type of the map that stores whether an edge is in the
87 /// spanning tree or not.
88 typedef typename _UGraph::template UEdgeMap<bool> TreeMap;
90 /// \brief Instantiates a TreeMap.
92 /// This function instantiates a \ref TreeMap.
94 /// The first parameter is the graph, to which
95 /// we would like to define the \ref TreeMap
96 static TreeMap *createTreeMap(const _UGraph& graph){
97 return new TreeMap(graph);
100 template <typename Iterator>
101 static void sort(Iterator begin, Iterator end, const CostMap& cost) {
102 _kruskal_bits::MappedComp<CostMap, std::less<Value> > comp(cost);
103 std::sort(begin, end, comp);
110 /// \brief Kruskal's algorithm to find a minimum cost tree of a graph.
112 /// This class implements Kruskal's algorithm to find a minimum cost
113 /// spanning tree. The
115 /// \param _UGraph Undirected graph type.
116 /// \param _CostMap Type of cost map.
117 template <typename _UGraph, typename _CostMap,
118 typename _Traits = KruskalDefaultTraits<_UGraph, _CostMap> >
122 typedef _Traits Traits;
124 typedef typename _Traits::UGraph UGraph;
125 typedef typename _Traits::CostMap CostMap;
127 typedef typename _Traits::TreeMap TreeMap;
129 typedef typename _Traits::Value Value;
131 template <typename Comp>
132 struct DefSortCompareTraits : public Traits {
133 template <typename Iterator>
134 static void sort(Iterator begin, Iterator end, const CostMap& cost) {
135 _kruskal_bits::MappedComp<CostMap, Comp> comp(cost, Comp());
136 std::sort(begin, end, comp);
140 /// \brief \ref named-templ-param "Named parameter" for setting the
141 /// comparator object of the standard sort
143 /// \ref named-templ-param "Named parameter" for setting the
144 /// comparator object of the standard sort
145 template <typename Comp>
146 struct DefSortCompare
147 : public Kruskal<UGraph, CostMap, DefSortCompareTraits<Comp> > {
148 typedef Kruskal<UGraph, CostMap, DefSortCompareTraits<Comp> > Create;
151 struct DefRadixSortTraits : public Traits {
152 template <typename Iterator>
153 static void sort(Iterator begin, Iterator end, const CostMap& cost) {
154 radixSort(begin, end, cost);
158 /// \brief \ref named-templ-param "Named parameter" for setting the
159 /// sort function to radix sort
161 /// \brief \ref named-templ-param "Named parameter" for setting the
162 /// sort function to radix sort. The value type of the cost map should
163 /// be integral, of course.
165 : public Kruskal<UGraph, CostMap, DefRadixSortTraits> {
166 typedef Kruskal<UGraph, CostMap, DefRadixSortTraits> Create;
170 struct DefTreeMapTraits : public Traits {
172 static TreeMap *createTreeMap(const UGraph &) {
173 throw UninitializedParameter();
177 /// \brief \ref named-templ-param "Named parameter" for setting
180 /// \ref named-templ-param "Named parameter" for setting TreeMap
184 : public Kruskal< UGraph, CostMap, DefTreeMapTraits<TM> > {
185 typedef Kruskal< UGraph, CostMap, DefTreeMapTraits<TM> > Create;
191 typedef typename UGraph::Node Node;
192 typedef typename UGraph::NodeIt NodeIt;
194 typedef typename UGraph::UEdge UEdge;
195 typedef typename UGraph::UEdgeIt UEdgeIt;
200 std::vector<UEdge> edges;
202 typedef typename UGraph::template NodeMap<int> UfIndex;
203 typedef UnionFind<UfIndex> Uf;
209 void initStructures() {
211 _tree = Traits::createTreeMap(graph);
215 ufi = new typename UGraph::template NodeMap<int>(graph);
216 uf = new UnionFind<typename UGraph::template NodeMap<int> >(*ufi);
220 void initUnionFind() {
222 for (NodeIt it(graph); it != INVALID; ++it) {
232 /// \brief Constructor
234 /// Constructor of the algorithm.
235 Kruskal(const UGraph& _graph, const CostMap& _cost)
236 : graph(_graph), cost(_cost),
237 ufi(0), uf(0), local_tree(false), _tree(0) {}
239 /// \brief Destructor
252 /// \brief Sets the map storing the tree edges.
254 /// Sets the map storing the tree edges.
255 /// If you don't use this function before calling \ref run(),
256 /// it will allocate one. The destuctor deallocates this
257 /// automatically allocated map, of course.
258 /// \return \c *this </tt>
259 Kruskal& treeMap(TreeMap &m){
268 /// \brief Initialize the algorithm
270 /// This member function initializes the unionfind data structure
271 /// and sorts the edges into ascending order
275 for (UEdgeIt e(graph); e != INVALID; ++e) {
277 _tree->set(e, false);
279 Traits::sort(edges.begin(), edges.end(), cost);
284 /// \brief Initialize the algorithm
286 /// This member function initializes the unionfind data structure
287 /// and sets the edge order to the given sequence. The given
288 /// sequence should be a valid STL range of undirected edges.
289 template <typename Iterator>
290 void initPresorted(Iterator begin, Iterator end) {
294 std::copy(begin, end, std::back_inserter(edges));
298 /// \brief Initialize the algorithm
300 /// This member function initializes the unionfind data structure
301 /// and sets the tree to empty. It does not change the order of
302 /// the edges, it uses the order of the previous running.
306 for (UEdgeIt e(graph); e != INVALID; ++e) {
307 _tree->set(e, false);
313 /// \brief Executes the algorithm.
315 /// Executes the algorithm.
317 /// \pre init() must be called before using this function.
319 /// This method runs the %Kruskal algorithm.
321 while (index < int(edges.size())) {
322 if (uf->join(graph.target(edges[index]), graph.source(edges[index]))) {
323 _tree->set(edges[index], true);
329 /// \brief Runs the prim algorithm until it find a new tree edge
331 /// Runs the prim algorithm until it find a new tree edge. If it
332 /// does not next tree edge in the sequence it gives back \c INVALID.
333 UEdge findNextTreeEdge() {
334 while (index < int(edges.size())) {
335 if (uf->join(graph.target(edges[index]), graph.source(edges[index]))) {
336 _tree->set(edges[index], true);
337 return edges[index++];
344 /// \brief Processes the next edge in the sequence
346 /// Processes the next edge in the sequence.
348 /// \return The prcocessed edge.
350 /// \warning The sequence must not be empty!
351 UEdge processNextEdge() {
352 UEdge edge = edges[index++];
357 /// \brief Processes an arbitrary edge
359 /// Processes the next edge in the sequence.
361 /// \return True when the edge is a tree edge.
362 bool processEdge(const UEdge& edge) {
363 if (uf->join(graph.target(edge), graph.source(edge))) {
364 _tree->set(edge, true);
371 /// \brief Returns \c false if there are edge to be processed in
374 /// Returns \c false if there are nodes to be processed in the
377 return index == int(edges.size());
380 /// \brief Returns the next edge to be processed
382 /// Returns the next edge to be processed
384 UEdge nextEdge() const {
388 /// \brief Runs %Kruskal algorithm.
390 /// This method runs the %Kruskal algorithm in order to compute the
391 /// minimum spanning tree (or minimum spanning forest). The
392 /// method also works on graphs that has more than one components.
393 /// In this case it computes the minimum spanning forest.
399 /// \brief Returns a reference to the tree edges map
401 /// Returns a reference to the TreeEdgeMap of the edges of the
402 /// minimum spanning tree. The value of the map is \c true only if
403 /// the edge is in the minimum spanning tree.
405 const TreeMap &treeMap() const { return *_tree;}
407 /// \brief Returns the total cost of the tree
409 /// Returns the total cost of the tree
410 Value treeValue() const {
412 for (UEdgeIt it(graph); it != INVALID; ++it) {
420 /// \brief Returns true when the given edge is tree edge
422 /// Returns true when the given edge is tree edge
423 bool tree(UEdge e) const {
431 namespace _kruskal_bits {
433 template <typename Graph, typename In, typename Out>
434 typename In::value_type::second_type
435 kruskal(const Graph& graph, const In& in, Out& out) {
436 typedef typename In::value_type::second_type Value;
437 typedef typename Graph::template NodeMap<int> IndexMap;
438 typedef typename Graph::Node Node;
440 IndexMap index(graph);
441 UnionFind<IndexMap> uf(index);
442 for (typename Graph::NodeIt it(graph); it != INVALID; ++it) {
446 Value tree_value = 0;
447 for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
448 if (uf.join(graph.target(it->first),graph.source(it->first))) {
449 out.set(it->first, true);
450 tree_value += it->second;
453 out.set(it->first, false);
460 template <typename Sequence>
462 typedef typename Sequence::value_type Value;
463 bool operator()(const Value& left, const Value& right) {
464 return left.second < right.second;
468 template <typename In, typename Enable = void>
469 struct SequenceInputIndicator {
470 static const bool value = false;
473 template <typename In>
474 struct SequenceInputIndicator<In,
475 typename exists<typename In::value_type::first_type>::type> {
476 static const bool value = true;
479 template <typename In, typename Enable = void>
480 struct MapInputIndicator {
481 static const bool value = false;
484 template <typename In>
485 struct MapInputIndicator<In,
486 typename exists<typename In::Value>::type> {
487 static const bool value = true;
490 template <typename In, typename Enable = void>
491 struct SequenceOutputIndicator {
492 static const bool value = false;
495 template <typename Out>
496 struct SequenceOutputIndicator<Out,
497 typename exists<typename Out::value_type>::type> {
498 static const bool value = true;
501 template <typename Out, typename Enable = void>
502 struct MapOutputIndicator {
503 static const bool value = false;
506 template <typename Out>
507 struct MapOutputIndicator<Out,
508 typename exists<typename Out::Value>::type> {
509 static const bool value = true;
512 template <typename In, typename InEnable = void>
513 struct KruskalValueSelector {};
515 template <typename In>
516 struct KruskalValueSelector<In,
517 typename enable_if<SequenceInputIndicator<In>, void>::type>
519 typedef typename In::value_type::second_type Value;
522 template <typename In>
523 struct KruskalValueSelector<In,
524 typename enable_if<MapInputIndicator<In>, void>::type>
526 typedef typename In::Value Value;
529 template <typename Graph, typename In, typename Out,
530 typename InEnable = void>
531 struct KruskalInputSelector {};
533 template <typename Graph, typename In, typename Out,
534 typename InEnable = void>
535 struct KruskalOutputSelector {};
537 template <typename Graph, typename In, typename Out>
538 struct KruskalInputSelector<Graph, In, Out,
539 typename enable_if<SequenceInputIndicator<In>, void>::type >
541 typedef typename In::value_type::second_type Value;
543 static Value kruskal(const Graph& graph, const In& in, Out& out) {
544 return KruskalOutputSelector<Graph, In, Out>::
545 kruskal(graph, in, out);
550 template <typename Graph, typename In, typename Out>
551 struct KruskalInputSelector<Graph, In, Out,
552 typename enable_if<MapInputIndicator<In>, void>::type >
554 typedef typename In::Value Value;
555 static Value kruskal(const Graph& graph, const In& in, Out& out) {
556 typedef typename In::Key MapEdge;
557 typedef typename In::Value Value;
558 typedef typename ItemSetTraits<Graph, MapEdge>::ItemIt MapEdgeIt;
559 typedef std::vector<std::pair<MapEdge, Value> > Sequence;
562 for (MapEdgeIt it(graph); it != INVALID; ++it) {
563 seq.push_back(std::make_pair(it, in[it]));
566 std::sort(seq.begin(), seq.end(), PairComp<Sequence>());
567 return KruskalOutputSelector<Graph, Sequence, Out>::
568 kruskal(graph, seq, out);
572 template <typename Graph, typename In, typename Out>
573 struct KruskalOutputSelector<Graph, In, Out,
574 typename enable_if<SequenceOutputIndicator<Out>, void>::type >
576 typedef typename In::value_type::second_type Value;
578 static Value kruskal(const Graph& graph, const In& in, Out& out) {
579 typedef StoreBoolMap<Out> Map;
581 return _kruskal_bits::kruskal(graph, in, map);
586 template <typename Graph, typename In, typename Out>
587 struct KruskalOutputSelector<Graph, In, Out,
588 typename enable_if<MapOutputIndicator<Out>, void>::type >
590 typedef typename In::value_type::second_type Value;
592 static Value kruskal(const Graph& graph, const In& in, Out& out) {
593 return _kruskal_bits::kruskal(graph, in, out);
599 /// \ingroup spantree
601 /// \brief Kruskal's algorithm to find a minimum cost tree of a graph.
603 /// This function runs Kruskal's algorithm to find a minimum cost tree.
604 /// Due to hard C++ hacking, it accepts various input and output types.
606 /// \param g The graph the algorithm runs on.
607 /// It can be either \ref concepts::Graph "directed" or
608 /// \ref concepts::UGraph "undirected".
609 /// If the graph is directed, the algorithm consider it to be
610 /// undirected by disregarding the direction of the edges.
612 /// \param in This object is used to describe the edge costs. It can be one
613 /// of the following choices.
614 /// - An STL compatible 'Forward Container' with
615 /// <tt>std::pair<GR::UEdge,X></tt> or
616 /// <tt>std::pair<GR::Edge,X></tt> as its <tt>value_type</tt>, where
617 /// \c X is the type of the costs. The pairs indicates the edges
618 /// along with the assigned cost. <em>They must be in a
619 /// cost-ascending order.</em>
620 /// - Any readable Edge map. The values of the map indicate the edge costs.
622 /// \retval out Here we also have a choise.
623 /// - It can be a writable \c bool edge map. After running the
624 /// algorithm this will contain the found minimum cost spanning
625 /// tree: the value of an edge will be set to \c true if it belongs
626 /// to the tree, otherwise it will be set to \c false. The value of
627 /// each edge will be set exactly once.
628 /// - It can also be an iteraror of an STL Container with
629 /// <tt>GR::UEdge</tt> or <tt>GR::Edge</tt> as its
630 /// <tt>value_type</tt>. The algorithm copies the elements of the
631 /// found tree into this sequence. For example, if we know that the
632 /// spanning tree of the graph \c g has say 53 edges, then we can
633 /// put its edges into an STL vector \c tree with a code like this.
635 /// std::vector<Edge> tree(53);
636 /// kruskal(g,cost,tree.begin());
638 /// Or if we don't know in advance the size of the tree, we can
640 ///\code std::vector<Edge> tree;
641 /// kruskal(g,cost,std::back_inserter(tree));
644 /// \return The total cost of the found tree.
646 /// \warning If kruskal runs on an be consistent of using the same
647 /// Edge type for input and output.
651 template <class Graph, class In, class Out>
652 Value kruskal(GR const& g, const In& in, Out& out)
654 template <class Graph, class In, class Out>
655 inline typename _kruskal_bits::KruskalValueSelector<In>::Value
656 kruskal(const Graph& graph, const In& in, Out& out)
659 return _kruskal_bits::KruskalInputSelector<Graph, In, Out>::
660 kruskal(graph, in, out);
666 template <class Graph, class In, class Out>
667 inline typename _kruskal_bits::KruskalValueSelector<In>::Value
668 kruskal(const Graph& graph, const In& in, const Out& out)
670 return _kruskal_bits::KruskalInputSelector<Graph, In, const Out>::
671 kruskal(graph, in, out);
676 #endif //LEMON_KRUSKAL_H