tiernan_print_cycles.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // (C) Copyright Andrew Sutton 2007
  2. //
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0 (See accompanying file
  5. // LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  6. //[tiernan_print_cycles
  7. #include <iostream>
  8. #include <boost/graph/directed_graph.hpp>
  9. #include <boost/graph/tiernan_all_cycles.hpp>
  10. #include "helper.hpp"
  11. using namespace std;
  12. using namespace boost;
  13. // The cycle_printer is a visitor that will print the path that comprises
  14. // the cycle. Note that the back() vertex of the path is not the same as
  15. // the front(). It is implicit in the listing of vertices that the back()
  16. // vertex is connected to the front().
  17. template <typename OutputStream>
  18. struct cycle_printer
  19. {
  20. cycle_printer(OutputStream& stream)
  21. : os(stream)
  22. { }
  23. template <typename Path, typename Graph>
  24. void cycle(const Path& p, const Graph& g)
  25. {
  26. // Get the property map containing the vertex indices
  27. // so we can print them.
  28. typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap;
  29. IndexMap indices = get(vertex_index, g);
  30. // Iterate over path printing each vertex that forms the cycle.
  31. typename Path::const_iterator i, end = p.end();
  32. for(i = p.begin(); i != end; ++i) {
  33. os << get(indices, *i) << " ";
  34. }
  35. os << endl;
  36. }
  37. OutputStream& os;
  38. };
  39. // Declare the graph type and its vertex and edge types.
  40. typedef directed_graph<> Graph;
  41. typedef graph_traits<Graph>::vertex_descriptor Vertex;
  42. typedef graph_traits<Graph>::edge_descriptor Edge;
  43. int
  44. main(int argc, char *argv[])
  45. {
  46. // Create the graph and read it from standard input.
  47. Graph g;
  48. read_graph(g, cin);
  49. // Instantiate the visitor for printing cycles
  50. cycle_printer<ostream> vis(cout);
  51. // Use the Tiernan algorithm to visit all cycles, printing them
  52. // as they are found.
  53. tiernan_all_cycles(g, vis);
  54. return 0;
  55. }
  56. //]