| Graphs: | undirected |
|---|---|
| Properties: | distance, weight, color, vertex id |
| Complexity: | O(E log V) |
(1)
template <class VertexListGraph, class Vertex>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s);
(2)
template <class VertexListGraph, class Vertex, class Distance>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s, Distance d);
(3)
template <class VertexListGraph, class Vertex,
class Distance, class Visitor>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s,
Distance d, Visitor visit);
(4)
template <class VertexListGraph, class Vertex, class Visitor,
class Distance, class Weight, class Color, class ID>
void prim_minimum_spanning_tree(VertexListGraph& G, Vertex s,
Distance d, Weight w, Color c, ID id,
Visitor visit);
This is Prim's algorithm [25,8,27,15] for solving the minimum spanning tree problem for an undirected graph with weighted edges. See Section Minimum Spanning Tree Algorithms for a definition of the minimum spanning tree problem. The implementation is simply a call to uniform_cost_search() with the appropriate choice of comparison and combine functors.
boost/graph/prim_minimum_spanning_tree.hpp
The time complexity is O(E log V).
The source code for this example is in examples/prim.cpp.
int main(int , char* [])
{
using namespace boost;
typedef adjacency_list<vecS, vecS, undirectedS,
property<vertex_color_t, default_color_type,
property<vertex_distance_t,int> >, property<edge_weight_t,int> >
Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef std::pair<int,int> E;
const int num_nodes = 9;
char name[] = "abcdefghi";
enum { a, b, c, d, e, f, g, h, i };
E edges[] = { E(a,b), E(a,h),
E(b,h), E(b,c),
E(c,d), E(c,f), E(c,i),
E(d,e), E(d,f),
E(e,f),
E(f,g),
E(g,i), E(g,h),
E(h,i) };
int weights[] = { 4, 8,
11, 8,
7, 4, 2,
9, 14,
10,
2,
6, 1,
7 };
Graph G(num_nodes, edges, edges + sizeof(edges)/sizeof(E), weights);
std::vector<Vertex> p(num_vertices(G));
Vertex src = *(vertices(G).first);
p[src] = src;
prim_minimum_spanning_tree
(G, src, get(vertex_distance, G),
make_ucs_visitor(record_predecessors(&p[0], on_edge_relaxed())));
for ( std::vector<Vertex>::iterator vi = p.begin();
vi != p.end(); ++vi)
std::cout << "parent[" << name[vi - p.begin()]
<< "] = " << name[*vi] << std::endl;
return 0;
}
The output is:
parent[a] = a parent[b] = a parent[c] = f parent[d] = c parent[e] = d parent[f] = g parent[g] = h parent[h] = a parent[i] = c
| Copyright © 2000 | Jeremy Siek, Univ.of Notre Dame (jsiek@lsc.nd.edu) |