| 1 | #include<bits/stdc++.h> |
| 2 | using namespace std; |
| 3 | int main(){ |
| 4 | int n=5,m=6,source=1; |
| 5 | vector<pair<int,int> > g[n+1]; // assuming 1 based indexing of graph |
| 6 | // Constructing the graph |
| 7 | g[1].push_back({2,2}); |
| 8 | g[1].push_back({4,1}); |
| 9 | g[2].push_back({1,2}); |
| 10 | g[2].push_back({5,5}); |
| 11 | g[2].push_back({3,4}); |
| 12 | g[3].push_back({2,4}); |
| 13 | g[3].push_back({4,3}); |
| 14 | g[3].push_back({5,1}); |
| 15 | g[4].push_back({1,1}); |
| 16 | g[4].push_back({3,3}); |
| 17 | g[5].push_back({2,5}); |
| 18 | g[5].push_back({3,1}); |
| 19 | // Dijkstra's algorithm begins from here |
| 20 | priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int>>> pq; |
| 21 | vector<int> distTo(n+1,INT_MAX);//1-indexed array for calculating shortest paths |
| 22 | distTo[source] = 0; |
| 23 | pq.push(make_pair(0,source)); // (dist,source) |
| 24 | while( !pq.empty() ){ |
| 25 | int dist = pq.top().first; |
| 26 | int prev = pq.top().second; |
| 27 | pq.pop(); |
| 28 | vector<pair<int,int> >::iterator it; |
| 29 | for( it = g[prev].begin() ; it != g[prev].end() ; it++){ |
| 30 | int next = it->first; |
| 31 | int nextDist = it->second; |
| 32 | if( distTo[next] > distTo[prev] + nextDist){ |
| 33 | distTo[next] = distTo[prev] + nextDist; |
| 34 | pq.push(make_pair(distTo[next], next)); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | cout << "The distances from source " << source << " are : \n"; |
| 39 | for(int i = 1 ; i<=n ; i++) cout << distTo[i] << " "; |
| 40 | cout << "\n"; |
| 41 | return 0; |
| 42 | } |
| 43 | |
| 44 | /* |
| 45 | Output: |