Skip to content

Commit 8d9bddc

Browse files
authored
Merge pull request #1299 from svaderia/patch-2
Added more information in finding negative cycle using Bellman-Ford
2 parents 799b157 + e6903c9 commit 8d9bddc

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

src/graph/finding-negative-cycle-in-graph.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ Bellman-Ford algorithm allows you to check whether there exists a cycle of negat
1919
The details of the algorithm are described in the article on the [Bellman-Ford](bellman_ford.md) algorithm.
2020
Here we'll describe only its application to this problem.
2121

22+
The standard implementation of Bellman-Ford looks for a negative cycle reachable from some starting vertex $v$ ; however, the algorithm can be modified to just looking for any negative cycle in the graph.
23+
For this we need to put all the distance  $d[i]$  to zero and not infinity — as if we are looking for the shortest path from all vertices simultaneously; the validity of the detection of a negative cycle is not affected.
24+
2225
Do $N$ iterations of Bellman-Ford algorithm. If there were no changes on the last iteration, there is no cycle of negative weight in the graph. Otherwise take a vertex the distance to which has changed, and go from it via its ancestors until a cycle is found. This cycle will be the desired cycle of negative weight.
2326

2427
### Implementation
@@ -40,12 +43,10 @@ void solve()
4043
for (int i = 0; i < n; ++i) {
4144
x = -1;
4245
for (Edge e : edges) {
43-
if(d[e.a] < INF){
44-
if (d[e.a] + e.cost < d[e.b]) {
45-
d[e.b] = max(-INF, d[e.a] + e.cost);
46-
p[e.b] = e.a;
47-
x = e.b;
48-
}
46+
if (d[e.a] + e.cost < d[e.b]) {
47+
d[e.b] = max(-INF, d[e.a] + e.cost);
48+
p[e.b] = e.a;
49+
x = e.b;
4950
}
5051
}
5152
}

0 commit comments

Comments
 (0)