fork download
  1. #include <vector>
  2. #include <utility>
  3. #include <set>
  4. #include <iostream>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. int64_t update, previous;
  10. set<pair<int64_t, int>> dist;
  11. auto it = dist.begin();
  12. int ind = 0, n, i, j;
  13. pair<int64_t, int>p;
  14.  
  15. using Graph = std::vector<std::vector<std::pair<int, int64_t>>>;
  16.  
  17. void dij(Graph& tree, std::vector<bool>& decided, std::vector<int64_t>& d, std::vector<int>& path) {
  18. ind = 0;
  19. while (!dist.empty()) {
  20. it = dist.begin();
  21. if (it == dist.end()) return;
  22. ind = it->second;
  23. dist.erase(it);
  24. decided[ind] = 1;
  25. for (j = 0; j < tree[ind].size(); j++) {
  26. update = d[ind] + tree[ind][j].second;
  27. previous = d[tree[ind][j].first];
  28. if (update < previous) {
  29. p = make_pair(previous, tree[ind][j].first);
  30. //cout<<p.first<<" intermediate "<<p.second<<endl;
  31. dist.erase(dist.find(p));
  32. p = make_pair(update, tree[ind][j].first);
  33. dist.insert(p);
  34. path[tree[ind][j].first] = ind;
  35. }
  36. d[tree[ind][j].first] = min(update, previous);
  37. }
  38. }
  39. }
  40.  
  41. int main()
  42. {
  43. int64_t edges;
  44. int64_t x, y, weight;
  45. cin >> n >> edges;
  46. Graph graph(n);
  47. for (i = 0; i < edges; i++) {
  48. cin >> x >> y >> weight;
  49. x--; y--;
  50. graph[x].push_back({ y, weight });
  51. graph[y].push_back({ x, weight });
  52. }
  53. int src = 1;
  54. src--;
  55. std::vector<int64_t> d(n);
  56. for (i = 0; i < n; i++) {
  57. if (src == i) {
  58. dist.insert({ 0, i });
  59. d[i] = 0;
  60. }
  61. else {
  62. dist.insert({ 1e18, i });
  63. d[i] = 1e18;
  64. }
  65. }
  66. std::vector<bool> decided(n);
  67. std::vector<int> path(n, -1);
  68. for (int i = 1; i < n; i++) path[i] = -2;
  69. dij(graph, decided, d, path);
  70. if (path[n - 1] == -2) cout << -1;
  71. else {
  72. vector<int> s;
  73. int final = n - 1;
  74. while (final != -1) {
  75. s.push_back(final);
  76. final = path[final];
  77. }
  78. reverse(s.begin(), s.end());
  79. for (auto pi : s) cout << pi + 1 << " ";
  80. }
  81. cout << endl;
  82. }
  83.  
Success #stdin #stdout 0s 4768KB
stdin
100 50
1 23 133
1 87 16
2 9 78
3 12 117
3 39 19
5 25 219
5 47 130
5 97 157
6 50 114
9 11 25
9 39 227
10 45 187
10 77 120
12 19 85
13 43 247
14 16 4
15 33 223
16 33 1
19 69 204
20 35 119
20 43 213
20 86 19
22 40 233
23 33 61
23 79 152
26 89 213
27 57 129
28 42 220
31 68 84
31 69 183
32 39 145
32 100 117
33 49 198
34 48 78
37 66 200
37 91 77
39 44 235
41 70 109
42 92 33
44 74 196
48 73 26
51 57 216
53 70 158
63 98 220
66 72 148
80 93 150
81 99 54
83 84 129
83 89 177
95 100 16
stdout
-1