Skip to content

Instantly share code, notes, and snippets.

@e-mon
Created May 7, 2015 14:44
Show Gist options
  • Save e-mon/7f00370a2271e0d5a80a to your computer and use it in GitHub Desktop.
Save e-mon/7f00370a2271e0d5a80a to your computer and use it in GitHub Desktop.
struct edge{
int to;
int cost;
bool operator>(const edge &e)const{
return cost > e.cost;
}
bool operator<(const edge &e)const{
return cost < e.cost;
}
};
void dijkstra(vector<vector<edge> > &g, vector<int> &dist, vector<int> &prev, int s){
priority_queue<edge, vector<edge>, greater<edge> > pq;
int V = g.size();
fill(dist.begin(),dist.end(),INF);
dist[s] = 0;
pq.push((edge){s,0});
while(!pq.empty()){
auto v = pq.top(); pq.pop();
if(dist[v.to] < v.cost) continue;
for(auto next_v:g[v.to]){
if(next_v.to != v.to and next_v.cost + dist[v.to] < dist[next_v.to]){
dist[next_v.to] = next_v.cost + dist[v.to];
pq.push((edge){next_v.to,dist[next_v.to]});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment