Advertisement
Saleh127

Dijkstra (shortest path -node)

Jan 17th, 2021
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define test int t; cin>>t; for(int cs=1;cs<=t;cs++)
  5.  
  6. vector<pair<ll,ll>>g[100005]; ///storing edges with weight;
  7. ll path[100005]; ///one node comes from which node;
  8. vector<ll>ans; ///store the shortest path;
  9.  
  10. int main()
  11. {
  12. ios_base::sync_with_stdio(0);
  13. cin.tie(0);
  14. cout.tie(0);
  15.  
  16. ll n,m,i,j,k,l,a,b,c;
  17.  
  18. cin>>n>>m;
  19.  
  20. ll cost[n+5]; ///cost to reach from node to another node
  21.  
  22. for(i=0; i<n+5; i++)
  23. {
  24. cost[i]=100000000000000;
  25. }
  26.  
  27. while(m--)
  28. {
  29. cin>>a>>b>>c;
  30. g[a].push_back({b,c});
  31. g[b].push_back({a,c});
  32. }
  33. cost[1]=0;
  34.  
  35. priority_queue<ll>q;
  36. q.push(1);
  37.  
  38. while(q.empty()==false)
  39. {
  40. ll u=q.top();
  41. q.pop();
  42.  
  43. for(auto i:g[u])
  44. {
  45. if(cost[i.first]> cost[u]+i.second)
  46. {
  47. ///relaxation;
  48. cost[i.first]=cost[u]+i.second;
  49. path[i.first]=u;
  50. q.push(i.first);
  51. }
  52. }
  53.  
  54. }
  55.  
  56. if(cost[n]==100000000000000) cout<<-1<<endl;
  57. else
  58. {
  59. while(path[n]!=0)
  60. {
  61. ///storing path
  62. ans.push_back(n);
  63. n=path[n];
  64. }
  65.  
  66. ans.push_back(1);
  67.  
  68. reverse(ans.begin(),ans.end());
  69.  
  70. for(auto y:ans)
  71. {
  72. cout<<y<<" ";
  73. }
  74. cout<<endl;
  75. }
  76.  
  77. return 0;
  78. }
  79.  
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement