Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- vector<int> dist;
- // Step 1: Initialize distances
- dist.assign(V, INT_MAX);
- dist.[start] = 0;
- // Step 2: Relax
- for (int i = 1; i <= V-1; i++)
- {
- for (int j = 0; j < E; j++)
- {
- int u = edge[j].src;
- int v = edge[j].dest;
- int weight = edge[j].weight;
- if ((dist[u] < INT_MAX) && (dist[u] + weight < dist[v]))
- dist[v] = dist[u] + weight;
- }
- }
- // Step 3: Check negative-weight cycle
- for (int i = 0; i < E; i++)
- {
- int u = edge[i].src;
- int v = edge[i].dest;
- int weight = edge[i].weight;
- if ((dist[u] != INT_MAX) && (dist[u] + weight < dist[v]))
- printf("Graph contains negative weight cycle");
- }
Advertisement
Add Comment
Please, Sign In to add comment