Graphs: | undirected |
---|---|
Properties: | rank, parent, weight |
Complexity: | O(E log E) |
(1) template <class VertexAndEdgeListGraph, class OutputIterator, class Rank, class Parent > void kruskal_minimum_spanning_tree(VertexAndEdgeListGraph& G, OutputIterator c, Rank rank, Parent p); (2) template <class VertexAndEdgeListGraph, class OutputIterator, class Rank, class Parent, class Weight > void kruskal_minimum_spanning_tree(VertexAndEdgeListGraph& G, OutputIterator out, Rank rank, Parent p, Weight w);
This is Kruskal's algorithm [18,8,27,15] for solving the minimum spanning tree problem. This is a greedy algorithm to calculate the minimum spanning tree for an undirected graph with weighted edges. The output is a set of edges written to the OutputIterator.
boost/graph/kruskal_min_spanning_tree.hpp
The minimum-spanning-tree problem is defined as follows: for a graph G = (V,E) find an acyclic subset T of E that connects all of the vertices in the graph and whose total weight is minimized, where the total weight is given by
The time complexity is O(E log E)
The source code for this example is in examples/kruskal.cpp.
typedef weight_property<int> weightp; typedef adjacency_list< vecS, vecS, undirectedS, off_vertex_default_property<>, weightp > Graph; typedef Graph::edge_descriptor Edge; typedef Graph::vertex_descriptor Vertex; typedef std::pair<int,int> E; const int num_nodes = 5; E edges[] = { E(0,2), E(1,1), E(1,3), E(1,4), E(2,1), E(2,3), E(3,4), E(4,0), E(4,1) }; int weights[] = { 1, 2, 1, 2, 7, 3, 1, 1, 1}; Graph G(num_nodes, edges, edges + sizeof(edges)/sizeof(E), weights); weight_property_map<Graph> weight = get_weight_map(G); typedef std::vector<Edge> container; std::vector<Edge> c; c.reserve(num_vertices(G)); std::vector<Vertex> p(num_vertices(G)); std::vector<int> rank(num_vertices(G)); kruskal_minimum_spanning_tree(G, std::back_inserter(c), rank.begin(), p.begin()); cout << "Print the edge in MST:" << endl; for (std::vector<Edge>::iterator ei = c.begin(); ei != c.end(); ++ei) { cout << index(source(*ei, G)) << " <--> " << index(target(*ei, G)) << " with weight of " << weight[*ei] << endl; }The output is:
Print the edge in MST: 0 <--> 2 with weight of 1 1 <--> 3 with weight of 1 4 <--> 0 with weight of 1 4 <--> 3 with weight of 1
Copyright © 2000 | Jeremy Siek, Univ.of Notre Dame (jsiek@lsc.nd.edu) |