Skip to content

Instantly share code, notes, and snippets.

@sunprinceS
Last active October 30, 2017 19:17
Show Gist options
  • Save sunprinceS/5c93f48db7d3b476f3829becbc2f2743 to your computer and use it in GitHub Desktop.
Save sunprinceS/5c93f48db7d3b476f3829becbc2f2743 to your computer and use it in GitHub Desktop.
std::vector<int> bellman_ford(const Graph& g,int s){
std::vector<int> dist(g.num_v,INT_MAX);
dist[s] = 0;
for(std::size_t i=0;i<g.num_v-1;++i){
for(auto e:g.edges){
if(dist[e.edge.first] != INT_MAX && dist[e.edge.first] + e.weight < dist[e.edge.second])
dist[e.edge.second] = dist[e.edge.first] + e.weight;
}
}
for(std::size_t i=0;i<g.num_v-1;++i){
for(auto e:g.edges){
if(dist[e.edge.first] == INT_MIN)
dist[e.edge.second] = INT_MIN;
// d[v] change in round |V|-1,|V| -> negative cycle
else if(dist[e.edge.first] != INT_MAX && dist[e.edge.first] + e.weight < dist[e.edge.second])
dist[e.edge.second] = INT_MIN;
}
}
return dist;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment