Advertisement
Korotkodul

ЗОШ Dijkstra OK

Jan 13th, 2022
52
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 <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <string>
  7. #include <stack>
  8. #include <set>
  9. #include <map>
  10. #define pii pair <int,int>
  11. #define vec vector
  12. using namespace std;
  13. using ll = long long;
  14. using ld = long double;
  15. using db = double;
  16. void cv(vector <int> &v){
  17. for (auto x: v) cout<<x+1<<' ';
  18. cout<<"\n";
  19. }
  20.  
  21. void cvl(vector <ll> &v){
  22. for (auto x: v) cout<<x<<' ';
  23. cout<<"\n";
  24. }
  25.  
  26.  
  27. void cvv(vector <vector <int> > &v){
  28. for (auto x: v) cv(x);
  29. cout<<"\n";
  30. }
  31. struct ed{
  32. int fr, to, w;
  33. };
  34.  
  35. const int inf = 2e9;
  36.  
  37. int n,m,s,f;
  38. vec <vec <ed>> G;
  39. vec <int> d;
  40. vec <int> pr;
  41.  
  42. set <pii> Q;
  43.  
  44. vector <bool> was;
  45.  
  46. void Dij(int s){
  47. d.assign(n, inf);
  48. pr.assign(n, -1);
  49. Q.insert({0, s});
  50. was.assign(n, 0);
  51. d[s] = 0;
  52. while (!Q.empty()){
  53. int v = Q.begin() -> second;
  54. Q.erase(Q.begin());
  55. //was[v] = 1;
  56. for (ed e: G[v]){
  57. //if (was[e.to]) continue;
  58. if (d[e.to] > d[v] + e.w){
  59. Q.erase({d[e.to], e.to});
  60. d[e.to] = d[v] + e.w;
  61. pr[e.to] = v;
  62.  
  63. Q.insert({d[e.to], e.to});
  64. }
  65. }
  66. }
  67. }
  68.  
  69. int main()
  70. {
  71. ios::sync_with_stdio(0);
  72. cin.tie(0);
  73. cout.tie(0);
  74. cin>>n>>m>>s>>f;
  75. --s;
  76. --f;
  77. G.resize(n);
  78. for (int i=0;i<m;++i){
  79. int a,b,w;
  80. cin>>a>>b>>w;
  81. a--;
  82. b--;
  83. G[a].push_back({a, b, w});
  84. G[b].push_back({b, a, w});
  85. }
  86. Dij(s);
  87. if (d[f] == inf) {
  88. cout<<-1;
  89. exit(0);
  90. }
  91. cout<<d[f]<<"\n";
  92. int v=f;
  93. vec <int> way ;
  94. while (v>=0){
  95. way.push_back(v);
  96. v = pr[v];
  97. }
  98. reverse(way.begin(), way.end());
  99. //cv(way);
  100. }
  101.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement