Fastrail08

Shortest path in directed graphs

Aug 24th, 2025
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> djikstra(int n, vector<vector<pair<int, int> > > &adj){
  5.     priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
  6.     vector<int> distance(n, INT_MAX), parent(n, -1);
  7.    
  8.     //Start djikstra from source
  9.     pq.emplace(0, 0);
  10.     distance[0] = 0;
  11.    
  12.     while(!pq.empty()){
  13.         pair<int, int> top = pq.top();
  14.         pq.pop();
  15.        
  16.         int node = top.second, nodeDist = top.first;
  17.        
  18.         //Ignore those occurences which are not the best, popped out after the first occurence
  19.         if(distance[node] < nodeDist){
  20.             continue;
  21.         }
  22.        
  23.         for(int i = 0; i < adj[node].size(); i++){
  24.             int child = adj[node][i].first, childDist = adj[node][i].second + nodeDist;
  25.             if(childDist < distance[child]){
  26.                 pq.emplace(childDist, child);
  27.                 distance[child] = childDist;
  28.                 parent[child] = node;
  29.             }
  30.         }        
  31.     }
  32.    
  33.     vector<int> path;
  34.     if(distance[n - 1] != INT_MAX){
  35.         path.push_back(distance[n - 1]);
  36.         for(int i = n - 1; i >= 0;){
  37.             //Revert back to 1 based indexing
  38.             path.push_back(i + 1);
  39.             i = parent[i];
  40.         }
  41.         reverse(path.begin() + 1, path.end());
  42.     }
  43.     else{
  44.         path.push_back(-1);
  45.     }
  46.    
  47.     return path;
  48. }
  49.  
  50. vector<int> shortestPath(int n, int m, vector<vector<int> > &edges){
  51.     vector<vector<pair<int, int> > > adj(n, vector<pair<int, int> >());
  52.     for(int i = 0; i < m; i++){
  53.         //Convert 1 based indexing to 0 based
  54.         int u = edges[i][0] - 1, v = edges[i][1] - 1, w = edges[i][2];
  55.         adj[u].emplace_back(v, w);
  56.         adj[v].emplace_back(u, w);
  57.     }
  58.     return djikstra(n, adj);
  59. }
  60.  
  61. int main() {
  62.     // your code goes here
  63.     int n, m;
  64.     cin >> n >> m;
  65.     vector<vector<int> > edges(m, vector<int>(3));
  66.     for(int i = 0; i < m; i++){
  67.         cin >> edges[i][0] >> edges[i][1] >> edges[i][2];
  68.     }
  69.    
  70.     vector<int> path = shortestPath(n, m, edges);
  71.     for(int i : path){
  72.         cout << i << " ";
  73.     }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment