bhupixb

Dijkstra Perfect

Dec 13th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. #define int long long
  5. #define P pair < int, int >
  6. #define PP pair < int, P >
  7. #define f first
  8. #define s second
  9. #define fast ios_base::sync_with_stdio(NULL);cin.tie(NULL);cout.tie(NULL);
  10. const int N = 2e5 + 5;
  11. vector < pair < int, int > > v[N];
  12. int dist[N], vis[N];
  13. int parent[N];
  14. void Dijkstra(int node){
  15. fill(dist, dist + (int)1e5 + 1, 1e16);
  16. priority_queue < PP, vector < PP > , greater < PP > > q;
  17. // pair < int = Dist, pair < int = current_node, int = parent > >
  18. dist[node] = 0;
  19. q.push({0, {node, node}});
  20.  
  21. while(!q.empty()){
  22. auto temp = q.top();
  23. q.pop();
  24. if(vis[temp.s.f])
  25. continue;
  26. dist[temp.s.f] = temp.f;
  27. parent[temp.s.f] = temp.s.s;
  28. for(auto it : v[temp.s.f]){
  29. q.push({it.s + temp.f, {it.f, temp.s.f}});
  30. }
  31. vis[temp.s.f] = 1;
  32. }
  33.  
  34. }
  35. signed main(){
  36. fast;
  37. int n, m, l, r, wt;
  38. cin >> n >> m;
  39. stack < int > st;
  40. for(int i = 1; i <= m; ++i){
  41. cin >> l >> r >> wt;
  42. v[l].push_back({r, wt});
  43. v[r].push_back({l, wt});
  44. }
  45. Dijkstra(1);
  46. if(dist[n] == 1e16)
  47. return cout << -1,0;
  48. int x = n;
  49. while(parent[x] != x)
  50. st.push(x), x = parent[x];
  51. cout << 1 << ' ';
  52. while(!st.empty())
  53. cout << st.top() << ' ', st.pop();
  54. return 0;
  55. }
Add Comment
Please, Sign In to add comment