Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <climits>
  5. using namespace std;
  6.  
  7. struct Edge {
  8. int from, to, weight;
  9. };
  10.  
  11. struct Node {
  12. int vertex, weight;
  13. };
  14.  
  15. class Graph
  16. {
  17. public:
  18. vector<vector<Edge>> adjList;
  19.  
  20. Graph(vector<Edge> const &edges, int N)
  21. {
  22. adjList.resize(N);
  23. for (Edge const &edge : edges)
  24. {
  25. adjList[edge.from].push_back(edge);
  26. //adjList[edge.to].push_back(edge);
  27. }
  28. }
  29. };
  30.  
  31. void print_route(vector<int> const &prev, int i)
  32. {
  33. if (i < 0)
  34. return;
  35.  
  36. print_route(prev, prev[i]);
  37. cout << i << " ";
  38. }
  39.  
  40. struct comp
  41. {
  42. bool operator()(const Node &lhs, const Node &rhs) const
  43. {
  44. return lhs.weight > rhs.weight;
  45. }
  46. };
  47. void shortestPath(Graph const& graph, int source, int N)
  48. {
  49. priority_queue<Node, vector<Node>, comp> min_heap;
  50. min_heap.push({ source, 0 });
  51.  
  52. vector<int> dist(N, INT_MAX);
  53.  
  54. dist[source] = 0;
  55.  
  56. vector<bool> done(N, false);
  57. done[0] = true;
  58.  
  59. //vector<int> prev(N, -1);
  60. while (!min_heap.empty())
  61. {
  62. Node node = min_heap.top();
  63. min_heap.pop();
  64.  
  65. int u = node.vertex;
  66.  
  67. for (auto i : graph.adjList[u])
  68. {
  69. int v = i.to;
  70. int weight = i.weight;
  71.  
  72. if (!done[v] && (dist[u] + weight) < dist[v])
  73. {
  74. dist[v] = dist[u] + weight;
  75. // prev[v] = u;
  76. min_heap.push({ v, dist[v] });
  77. }
  78. }
  79. done[u] = true;
  80. }
  81.  
  82. for (int i = 1; i < N; ++i)
  83. {
  84. cout << dist[i] << " ";
  85. }
  86. }
  87.  
  88.  
  89.  
  90.  
  91. int main()
  92. {
  93. // initialize edges as per above diagram
  94. vector<Edge> edges =
  95. {
  96. {1, 2, 0}, {1, 3, 2}, {1, 5, 5}, {2, 4, 4}, {5, 6, 8},
  97. {6, 7, 1}//, {4, 1, 1}, {4, 2, 8}, {4, 3, 2}
  98. };
  99.  
  100. // Number of nodes in the graph
  101. int N = 8;
  102.  
  103. // construct graph
  104. Graph graph(edges, N);
  105.  
  106. shortestPath(graph, 5, N);
  107. int _; cin >> _;
  108. return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement