topo_sort.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //=======================================================================
  2. // Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
  3. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
  4. //
  5. // Distributed under the Boost Software License, Version 1.0. (See
  6. // accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //=======================================================================
  9. #include <boost/config.hpp>
  10. #include <iostream>
  11. #include <list>
  12. #include <algorithm>
  13. #include <boost/graph/adjacency_list.hpp>
  14. #include <boost/graph/topological_sort.hpp>
  15. #include <iterator>
  16. #include <utility>
  17. typedef std::pair<std::size_t,std::size_t> Pair;
  18. /*
  19. Topological sort example
  20. The topological sort algorithm creates a linear ordering
  21. of the vertices such that if edge (u,v) appears in the graph,
  22. then u comes before v in the ordering.
  23. Sample output:
  24. A topological ordering: 2 5 0 1 4 3
  25. */
  26. int
  27. main(int , char* [])
  28. {
  29. //begin
  30. using namespace boost;
  31. /* Topological sort will need to color the graph. Here we use an
  32. internal decorator, so we "property" the color to the graph.
  33. */
  34. typedef adjacency_list<vecS, vecS, directedS,
  35. property<vertex_color_t, default_color_type> > Graph;
  36. typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
  37. Pair edges[6] = { Pair(0,1), Pair(2,4),
  38. Pair(2,5),
  39. Pair(0,3), Pair(1,4),
  40. Pair(4,3) };
  41. #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
  42. // VC++ can't handle the iterator constructor
  43. Graph G(6);
  44. for (std::size_t j = 0; j < 6; ++j)
  45. add_edge(edges[j].first, edges[j].second, G);
  46. #else
  47. Graph G(edges, edges + 6, 6);
  48. #endif
  49. boost::property_map<Graph, vertex_index_t>::type id = get(vertex_index, G);
  50. typedef std::vector< Vertex > container;
  51. container c;
  52. topological_sort(G, std::back_inserter(c));
  53. std::cout << "A topological ordering: ";
  54. for (container::reverse_iterator ii = c.rbegin();
  55. ii != c.rend(); ++ii)
  56. std::cout << id[*ii] << " ";
  57. std::cout << std::endl;
  58. return 0;
  59. }