Maruf_Hasan

dijkstra by struct

Apr 7th, 2019
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define INF 1e18+7
  4. #define M 100100
  5. #define ll long long
  6. vector<ll>edge[M],cost[M];
  7. ll parent[M];
  8. ll s,desti;
  9. bool visited[M];
  10.  
  11. struct data
  12. {
  13. ll city,dist;
  14. bool operator<(const data& p) const
  15. {
  16. return dist>p.dist;
  17. }
  18. };
  19.  
  20. ll dijkstra(ll source,ll destination)
  21. {
  22. ll d[M];
  23. for(int i=0;i<M;i++)
  24. {
  25. d[i]=INF;
  26. parent[i]=-1;
  27. }
  28. priority_queue<data>q;
  29. data u,v;
  30. u.city=source;
  31. u.dist=0;
  32. q.push(u);
  33. d[source]=0;
  34. while(!q.empty())
  35. {
  36. u=q.top();
  37. q.pop();
  38. ll ucost=d[u.city];
  39. //cout<<u.city<<endl;
  40. for(ll i=0;i<edge[u.city].size();i++)
  41. {
  42. v.city=edge[u.city][i];
  43. v.dist=cost[u.city][i]+ucost;
  44. //relaxing
  45. if(d[v.city]>v.dist)
  46. {
  47. d[v.city]=v.dist;
  48. parent[v.city]=u.city;
  49. //cout<<v.city<<endl;
  50. q.push(v);
  51. }
  52. }
  53. }
  54.  
  55. return d[destination];
  56. }
  57. void printpath(int x)
  58. {
  59. if(x==1)
  60. {
  61. cout<<1<<" ";
  62. return;
  63. }
  64. printpath(parent[x]);
  65. cout<<x<<" ";
  66. }
  67.  
  68. int main()
  69. {
  70. ll n,m;
  71. cin>>n>>m;
  72. data get;
  73. while(m--)
  74. {
  75. ll a,b,w;
  76. cin>>a>>b>>w;
  77. edge[a].push_back(b);
  78. edge[b].push_back(a);
  79. cost[a].push_back(w);
  80. cost[b].push_back(w);
  81. }
  82. ll prime= dijkstra(1,n);
  83. if(prime==INF)
  84. {
  85. cout<<-1<<endl;
  86. }
  87. else
  88. {
  89. printpath(n);
  90. }
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment