BellmanFord.cpp 876 B

12345678910111213141516171819202122232425262728293031
  1. // Bellman-Ford algorithm
  2. // compute shortest path in a directed graphdefaults
  3. // even with negative coststypede
  4. // find negative cycles
  5. // COMPLEXITY: O(nm)
  6. typedef struct Edge{
  7. int u, v, w;
  8. Edge(int u, int v, int w) : u(u), v(v), w(w) {}
  9. }Edge;
  10. vector<Edge> edges;
  11. int dist[10000];
  12. int nodenum, edgenum;
  13. const int INF = 1000000000;
  14. // set dest[*] = INF, dist[src] = 0
  15. // fill edges, nodenum, edgenum
  16. void relax(int u, int v, int w) {
  17. if(dist[v] > dist[u] + w) {
  18. dist[v] = dist[u] + w;
  19. // predecessor[v] = u
  20. }
  21. }
  22. // return false if there is a negative cycle
  23. bool BellmanFord() {
  24. for(int i = 0; i < nodenum-1; i++)
  25. for(int j = 0; j < edgenum; j++) // (if there is no changes we can break)
  26. relax(edges[j].u, edges[j].v, edges[j].w);
  27. for(int i = 0; i < edgenum; i++)
  28. if(dist[edges[i].u] + edges[i].w < dist[edges[i].v])
  29. return false;
  30. return true;
  31. }