HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Finding negative cycle using Bellman Ford

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
cyclebellmanfordusingfindingnegative

Problem

Given a graph with |V| vertexes and |E| edges, I have to find a negative cycle, if there is one, in a graph.
The wanted complexity is O(|V|*|E|).

I was thinking about using Bellman-Ford to solve the question doing this:
Do |V| iterations of Bellman-Ford, 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.

The problem is, that no start vertex is given, and Bellman-Ford notes wether there is reachable negative cycle via the start vertex or not.
Assume that if we start from vertex a there won't be negative cycle and if the start vertex was b there will be one.
So if I choose a as a start vertex I'll miss the negative graph.

How can I solve that?
I thought about trying all the vertexes as start vertex but it won't be O(|E|*|V|).

Solution

Choosing a arbitrary vertex as source may not reach the negative cycle in the graph.

Assuming the graph is directed. The cycle may not be visited if there are vertices that the source node cannot reach, such as: (assuming $V_0$ is the source)

-
Graph containing different components or

-
There are vertices behind the source vertex.

So, the solution is to:

  • Set Dist[v]=0 for all v that has 0 in-degree (or alternatively, add an additional vertex as source, which connects to all other vertices with 0-weighted edges. (similar to Johnson's algorithm))



  • Run Bellman-Ford for V-1 iterations



  • Perform an additional iteration for marking negative paths (by ancestor backtracking)



  • Maintaining the minimum cycle while perform a BFS starting from the 0-in-degree vertices.

Context

StackExchange Computer Science Q#109485, answer score: 2

Revisions (0)

No revisions yet.