D_L3

SDA - test 6 - 2019-2020 - Еконт

Jan 8th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <climits>
  7. #include <unordered_map>
  8. #include <queue>
  9.  
  10. using namespace std;
  11.  
  12. unordered_map<int, unordered_map<int, int>> graph;
  13. int distances[2 * 100000];
  14.  
  15. void fillDistances(int start) {
  16. priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> next;
  17.  
  18. next.push({ 0, start });
  19.  
  20. while (!next.empty()) {
  21. int currIdx = next.top().second;
  22. int currDist = next.top().first;
  23. next.pop();
  24.  
  25. if (distances[currIdx] <= currDist)
  26. continue;
  27.  
  28. distances[currIdx] = currDist;
  29.  
  30. for (auto neighbour : graph[currIdx]) {
  31. int nextIdx = neighbour.first;
  32. int nextDist = neighbour.second + currDist;
  33. if (distances[nextIdx] <= nextDist)
  34. continue;
  35. next.push({ nextDist, nextIdx });
  36. }
  37. }
  38. }
  39.  
  40. int main() {
  41. int n, m, u, v, w, start;
  42. cin >> n >> m;
  43.  
  44. for (size_t i = 0; i < n; i++)
  45. {
  46. distances[i] = INT_MAX;
  47. }
  48.  
  49. for (int i = 0; i < m; i++) {
  50. cin >> u >> v >> w;
  51. u--;
  52. v--;
  53. if(graph[u][v] == 0 || graph[u][v] > w){
  54. graph[u][v] = w;
  55. graph[v][u] = w;
  56. }
  57. }
  58.  
  59. cin >> start;
  60. start--;
  61. fillDistances(start);
  62.  
  63. for (int i = 0; i < n; i++) {
  64. if (i == start)
  65. continue;
  66. if (distances[i] == INT_MAX)
  67. distances[i] = -1;
  68. cout << distances[i] << " ";
  69. }
  70.  
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment