fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <limits>
  4.  
  5. using namespace std;
  6.  
  7. const int64_t MAX = 1000010;
  8. const int64_t QSIZE = 3000000;
  9.  
  10. int64_t N, M, a, b, c, h, inizio, fine;
  11. vector<vector<int64_t>> graph(MAX);
  12. vector<vector<int64_t>> peso(MAX);
  13. vector<int64_t> gsize(MAX, 0);
  14. vector<int64_t> gcapa(MAX, 1);
  15. vector<bool> visited(MAX, false);
  16. vector<int64_t> dist(MAX, numeric_limits<int64_t>::max());
  17. vector<int64_t> S(QSIZE), E(QSIZE), P(QSIZE);
  18. vector<int64_t> q1(QSIZE), q2(QSIZE);
  19.  
  20. void bfs(int64_t partenza, int64_t arrivo, vector<int64_t>& res) {
  21. int64_t qhead = 0, qcount = 1, first, second;
  22. q1[0] = partenza;
  23. q2[0] = 0;
  24.  
  25. fill(visited.begin(), visited.begin() + N, false);
  26.  
  27. while (qcount > 0) {
  28. first = q1[qhead];
  29. second = q2[qhead];
  30. qhead = (qhead + 1) % QSIZE;
  31. qcount--;
  32.  
  33. if (visited[first]) {
  34. if (second < res[first]) {
  35. res[first] = second;
  36. } else {
  37. continue;
  38. }
  39. }
  40.  
  41. visited[first] = true;
  42. res[first] = second;
  43.  
  44. for (int64_t j = 0; j < gsize[first]; j++) {
  45. q1[(qhead + qcount) % QSIZE] = graph[first][j];
  46. q2[(qhead + qcount) % QSIZE] = second + peso[first][j];
  47. qcount++;
  48. }
  49. }
  50. }
  51.  
  52. int main() {
  53. cin >> N >> M;
  54. for (h = 0; h < M; h++) {
  55. cin >> S[h] >> E[h] >> P[h];
  56. }
  57.  
  58. for (h = 0; h < N; h++) {
  59. graph[h].resize(1);
  60. peso[h].resize(1);
  61. dist[h] = numeric_limits<int64_t>::max();
  62. }
  63.  
  64. for (h = 0; h < M; h++) {
  65. a = S[h];
  66. b = E[h];
  67. c = P[h];
  68.  
  69. if (gsize[a] == gcapa[a]) {
  70. gcapa[a] *= 2;
  71. graph[a].resize(gcapa[a]);
  72. peso[a].resize(gcapa[a]);
  73. }
  74.  
  75. graph[a][gsize[a]] = b;
  76. peso[a][gsize[a]] = c;
  77. gsize[a]++;
  78. }
  79.  
  80. inizio = 0;
  81. for (h = 1; h <= N; h++) {
  82. fine = h;
  83. bfs(inizio, fine, dist);
  84. }
  85.  
  86. for (h = 0; h < N; h++) {
  87. if (dist[h] != numeric_limits<int64_t>::max()) {
  88. cout << dist[h] << ' ';
  89. } else {
  90. cout << "-1 ";
  91. }
  92. }
  93.  
  94. return 0;
  95. }
Success #stdin #stdout 0.04s 190776KB
stdin
2 1
1 0 1

stdout
0 -1