Advertisement
Korotkodul

ЗОШ Dijkstra WA 5 неориентированный граф

Jan 12th, 2022
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 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. void Dij(int s){
  45. d.assign(n, inf);
  46. pr.assign(n, -1);
  47. Q.insert({0, s});
  48. d[0] = 0;
  49. while (!Q.empty()){
  50. int v = Q.begin() -> second;
  51. Q.erase(Q.begin());
  52. for (ed e: G[v]){
  53. if (d[e.to] > d[v] + e.w){
  54. Q.erase({d[e.to], e.to});
  55. d[e.to] = d[v] + e.w;
  56. pr[e.to] = v;
  57.  
  58. Q.insert({d[e.to], e.to});
  59. }
  60. }
  61. }
  62. }
  63.  
  64. int main()
  65. {
  66. ios::sync_with_stdio(0);
  67. cin.tie(0);
  68. cout.tie(0);
  69. cin>>n>>m>>s>>f;
  70. --s;
  71. --f;
  72. G.resize(n);
  73. for (int i=0;i<m;++i){
  74. int a,b,w;
  75. cin>>a>>b>>w;
  76. a--;
  77. b--;
  78. G[a].push_back({a, b, w});
  79. G[b].push_back({b, a, w});
  80. }
  81. Dij(s);
  82. if (d[f] == inf) {
  83. cout<<-1;
  84. exit(0);
  85. }
  86. cout<<d[f]<<"\n";
  87. int v=f;
  88. vec <int> way ;
  89. while (v>=0){
  90. way.push_back(v);
  91. v = pr[v];
  92. }
  93. reverse(way.begin(), way.end());
  94. cv(way);
  95. }
  96.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement