fork download
  1. #include <climits>
  2. #include <vector>
  3. #include <iostream>
  4. #include <algorithm>
  5. #include <queue>
  6.  
  7. void print( std::vector<int> & a )
  8. {
  9. for (auto i : a)
  10. std::cout << i << " ";
  11. std::cout << std::endl;
  12. }
  13.  
  14. class Graph
  15. {
  16. private:
  17. std::vector<std::vector<std::pair<int, int>>> adj;
  18. std::vector<int> distances;
  19. std::vector<int> path;
  20. const int INF = INT_MAX;
  21. int vertexes_count = 0, edges_count = 0;
  22. void relax (int start, int end, int length);
  23. public:
  24. typedef std::vector<int> result;
  25. Graph();
  26. Graph(int vertexes, int edges);
  27. ~Graph();
  28. void input();
  29. void output();
  30. result dijkstra(int start);
  31. };
  32.  
  33. Graph::Graph() {}
  34.  
  35. Graph::~Graph() {}
  36.  
  37. Graph::Graph(int vertexes, int edges)
  38. {
  39. vertexes_count = vertexes;
  40. edges_count = edges;
  41. adj.resize(vertexes + 1);
  42. distances.resize(vertexes + 1, INF);
  43. path.resize(vertexes + 1, -1);
  44. }
  45.  
  46. void Graph::input()
  47. {
  48. int start = 0, end = 0, length = 0;
  49. for (int i = 0; i < edges_count; ++i)
  50. {
  51. std::cin >> start >> end >> length;
  52. adj[start].push_back (std::make_pair(length, end));
  53. adj[end].push_back (std::make_pair(length, start));
  54. }
  55. }
  56.  
  57. Graph::result
  58. Graph::dijkstra (int start)
  59. {
  60. distances[start] = 0;
  61. path[start] = start;
  62. std::priority_queue<std::pair<int, int>,
  63. std::vector<std::pair<int, int>>,
  64. std::greater<std::pair<int, int>>> q;
  65. q.push(std::make_pair(0, start));
  66. while (!q.empty())
  67. {
  68. int current = q.top().second;
  69. int len = q.top().first;
  70. q.pop();
  71. for (int i = 0; i < adj[current].size(); ++i)
  72. {
  73. int to = adj[current][i].second;
  74. int length = adj[current][i].first;
  75. // Relaxations
  76. if (distances[to] > distances[current] + length)
  77. {
  78. path[to] = current;
  79. distances[to] = distances[current] + length;
  80. q.push(std::make_pair(distances[to], to));
  81. }
  82. }
  83. }
  84. // Replace INF by -1
  85. //std::replace (distances.begin(), distances.end(), INF, -1);
  86. print(distances);
  87. return distances;
  88. }
  89.  
  90.  
  91. int main() {
  92. int ntests = 0, nodes = 0, edges = 0, start = 0;
  93. std::cin >> ntests;
  94. for (int i = 0; i < ntests; ++i)
  95. {
  96. std::cin >> nodes >> edges;
  97. Graph g(nodes, edges);
  98. g.input();
  99. std::cin >> start;
  100. auto result = g.dijkstra (start);
  101. print(result);
  102. }
  103. return 0;
  104. }
Success #stdin #stdout 0s 3468KB
stdin
1
4 4
1 2 24
1 4 20
3 1 3
4 3 12
1
stdout
2147483647 0 24 3 15 
2147483647 0 24 3 15