prim-example.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //=======================================================================
  2. // Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See
  5. // accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //=======================================================================
  8. #include <boost/config.hpp>
  9. #include <iostream>
  10. #include <boost/graph/adjacency_list.hpp>
  11. #include <boost/graph/prim_minimum_spanning_tree.hpp>
  12. int
  13. main()
  14. {
  15. using namespace boost;
  16. typedef adjacency_list < vecS, vecS, undirectedS,
  17. property<vertex_distance_t, int>, property < edge_weight_t, int > > Graph;
  18. typedef std::pair < int, int >E;
  19. const int num_nodes = 5;
  20. E edges[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),
  21. E(3, 4), E(4, 0)
  22. };
  23. int weights[] = { 1, 1, 2, 7, 3, 1, 1 };
  24. #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
  25. Graph g(num_nodes);
  26. property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);
  27. for (std::size_t j = 0; j < sizeof(edges) / sizeof(E); ++j) {
  28. graph_traits<Graph>::edge_descriptor e; bool inserted;
  29. boost::tie(e, inserted) = add_edge(edges[j].first, edges[j].second, g);
  30. weightmap[e] = weights[j];
  31. }
  32. #else
  33. Graph g(edges, edges + sizeof(edges) / sizeof(E), weights, num_nodes);
  34. #endif
  35. std::vector < graph_traits < Graph >::vertex_descriptor >
  36. p(num_vertices(g));
  37. #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
  38. property_map<Graph, vertex_distance_t>::type distance = get(vertex_distance, g);
  39. property_map<Graph, vertex_index_t>::type indexmap = get(vertex_index, g);
  40. prim_minimum_spanning_tree
  41. (g, *vertices(g).first, &p[0], distance, weightmap, indexmap,
  42. default_dijkstra_visitor());
  43. #else
  44. prim_minimum_spanning_tree(g, &p[0]);
  45. #endif
  46. for (std::size_t i = 0; i != p.size(); ++i)
  47. if (p[i] != i)
  48. std::cout << "parent[" << i << "] = " << p[i] << std::endl;
  49. else
  50. std::cout << "parent[" << i << "] = no parent" << std::endl;
  51. return EXIT_SUCCESS;
  52. }