Guest User

Untitled

a guest
Jul 20th, 2016
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. graph_t compute_Prims_MST_fast(const graph_t & graph)
  2. {
  3.     auto vertices = graph.vertices();
  4.     std::list<int> vertices_in_MST = { *vertices.begin() };
  5.     graph_t MST;
  6.  
  7.     auto cheapest_edge_vertex = [&](int vertex) {
  8.         return *std::min_element(vertices_in_MST.begin(), vertices_in_MST.end(),
  9.                                 [&](int lhs, int rhs) {
  10.                                     return graph.weight(lhs, vertex) < graph.weight(rhs, vertex);
  11.                                 });
  12.     };
  13.  
  14.     auto compare_vertices = [&](int lhs, int rhs) {
  15.         return graph.weight(lhs, cheapest_edge_vertex(lhs)) > graph.weight(rhs, cheapest_edge_vertex(rhs));
  16.     };
  17.  
  18.     std::priority_queue<int, std::vector<int>, std::function<bool (int, int)>> pq(
  19.             std::next(vertices.begin()), vertices.end(), compare_vertices
  20.     );
  21.  
  22.     while (!pq.empty()) {
  23.         auto v = pq.top();
  24.         auto u = cheapest_edge_vertex(v);
  25.         auto weight = graph.weight(u, v);
  26.  
  27.         if (weight != std::numeric_limits<double>::infinity()) {
  28.             MST.add_edge(u, v, weight);
  29.             vertices_in_MST.push_back(v);
  30.         }
  31.  
  32.         pq.pop();
  33.     }
  34.  
  35.     return MST;
  36. };
Advertisement
Add Comment
Please, Sign In to add comment