bellman-ford-internet.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 <iostream>
  9. #include <boost/graph/edge_list.hpp>
  10. #include <boost/graph/bellman_ford_shortest_paths.hpp>
  11. int
  12. main()
  13. {
  14. using namespace boost;
  15. // ID numbers for the routers (vertices).
  16. enum
  17. { A, B, C, D, E, F, G, H, n_vertices };
  18. const int n_edges = 11;
  19. typedef std::pair < int, int >Edge;
  20. // The list of connections between routers stored in an array.
  21. Edge edges[] = {
  22. Edge(A, B), Edge(A, C),
  23. Edge(B, D), Edge(B, E), Edge(C, E), Edge(C, F), Edge(D, H),
  24. Edge(D, E), Edge(E, H), Edge(F, G), Edge(G, H)
  25. };
  26. // Specify the graph type and declare a graph object
  27. typedef edge_list < Edge*, Edge, std::ptrdiff_t, std::random_access_iterator_tag> Graph;
  28. Graph g(edges, edges + n_edges);
  29. // The transmission delay values for each edge.
  30. float delay[] =
  31. {5.0, 1.0, 1.3, 3.0, 10.0, 2.0, 6.3, 0.4, 1.3, 1.2, 0.5};
  32. // Declare some storage for some "external" vertex properties.
  33. char name[] = "ABCDEFGH";
  34. int parent[n_vertices];
  35. for (int i = 0; i < n_vertices; ++i)
  36. parent[i] = i;
  37. float distance[n_vertices];
  38. std::fill(distance, distance + n_vertices, (std::numeric_limits < float >::max)());
  39. // Specify A as the source vertex
  40. distance[A] = 0;
  41. bool r = bellman_ford_shortest_paths(g, int (n_vertices),
  42. weight_map(make_iterator_property_map
  43. (&delay[0],
  44. get(edge_index, g),
  45. delay[0])).
  46. distance_map(&distance[0]).
  47. predecessor_map(&parent[0]));
  48. if (r)
  49. for (int i = 0; i < n_vertices; ++i)
  50. std::cout << name[i] << ": " << distance[i]
  51. << " " << name[parent[i]] << std::endl;
  52. else
  53. std::cout << "negative cycle" << std::endl;
  54. return EXIT_SUCCESS;
  55. }