Advertisement
Josif_tepe

Untitled

May 27th, 2021
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include<vector>
  3. #include<queue>
  4. using namespace std;
  5. struct node
  6. {
  7.     int idx, distance;
  8.     node () {}
  9.     node(int _idx, int _distance) {
  10.         idx = _idx;
  11.         distance = _distance;
  12.     }
  13.     bool operator < (const node &tmp) const {
  14.         return distance > tmp.distance;
  15.     }
  16. };
  17. int main()
  18. {
  19.     int n, m;
  20.     cin >> n >> m;
  21.     vector<pair<int, int> > graph[n + 1];
  22.     for(int i = 0; i < m; i++) {
  23.         int a, b, c;
  24.         cin >> a >> b >> c;
  25.         graph[a].push_back(make_pair(b, c));
  26.         graph[b].push_back(make_pair(a, c));
  27.     }
  28.     bool visited[n + 1];
  29.     int dist[n + 1];
  30.    
  31.     int parent[n + 1]; // node i ima dojdeno od parent[i]
  32.    
  33.     for(int i = 0; i <= n; i++) {
  34.         visited[i] = false;
  35.         dist[i] = 2e9;
  36.         parent[i] = -1;
  37.     }
  38.     dist[1] = 0;
  39.     priority_queue<node> pq;
  40.     pq.push(node(1, 0));
  41.     while(!pq.empty()) {
  42.         node c = pq.top();
  43.         pq.pop();
  44.         visited[c.idx] = true;
  45.        
  46.         for(int i = 0; i < graph[c.idx].size(); i++) {
  47.             int sosed = graph[c.idx][i].first;
  48.             int d = graph[c.idx][i].second;
  49.             if(!visited[sosed] and d + c.distance < dist[sosed]) {
  50.                 dist[sosed] = d + c.distance;
  51.                 pq.push(node(sosed, d + c.distance));
  52.                 parent[sosed] = c.idx;
  53.             }
  54.         }
  55.     }
  56.    
  57.     cout << dist[n] << endl;
  58.    
  59.     int E = n;
  60.     cout << E << " ";
  61.    
  62.     while(E != 1) {
  63.         E = parent[E];
  64.         cout << E << " ";
  65.     }
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement