Weighted shortest path (1)
Write a program that, given a directed graph with positive costs at the arcs, and two vertices x and y, computes the minimum cost to go from x to y.
“I don’t know how many of you have ever met Dijkstra, but you probably know that arrogance in computer science is measured in nano-Dijkstras.” - Alan Kay
(some context for the quotation)
Input: Input consists of several cases. Every case begins with the number of vertices n and the number of arcs m. Follow m triples u\ v\ c, indicating that there is an arc u \rightarrow v of cost c, where u \neq v and 1 \leq c \leq 10^4. Finally, we have x and y.
Assume 1 \leq n \leq 10^4, 0 \leq m \leq 5n, and that for every pair of vertices u and v there is at most one arc of the kind u \rightarrow v. All numbers are integers. Vertices are numbered from 0 to n−1.
Output: For every case, print the minimum cost to go from x to y, if this is possible. If there is no path from x to y, state so.
For this exercise a basic implementation of Dijkstra’s algorithm is enough.
//Weighted Shortest path - 1
#include<iostream>
#include<vector>
#include<queue>
#include<limits.h>
using namespace std;
using vertex = int;
using graph = vector<vector<pair<vertex,int>>>;// for the adjacency list of a weighted directed graph
using P = pair<int,vertex>; //distance, vertex
<int> dijkstra(const graph& g, vertex s){
vectorint n = g.size();
<int> D(n, INT_MAX);
vector<bool> marked(n,false);
vector<P, vector<P>, greater<P>> pq;
priority_queue[s] = 0;
D.push({D[s],s});
pqwhile (not pq.empty()){
int u = pq.top().second;
.pop();
pqif (not marked[u]){
[u] = true;
markedfor (auto i : g[u]){
= i.first;//the neighbor
vertex neigh int w = i.second;// the weight
if (D[neigh] > D[u] + w){
[neigh] = D[u] + w;
D.push({D[neigh],neigh});
pq}
}
}
}
return D;
}
int main(){
int n, m;
while(cin >> n >> m){
(n);
graph gfor (int k = 0; k < m; ++k){
int u, v, c;
>> u >> v >> c;
cin [u].push_back({v,c});
g}
, y;
vertex x>> x >> y;
cin <int> D = dijkstra(g, x);
vectorif (D[y] == INT_MAX) cout << "no path from " << x << " to " << y << endl;
else cout << D[y] << endl;
}
}