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|).

  • $\begingroup$ Have you taken a look at this question, for instance? $\endgroup$ – dkaeae May 17 at 15:11
  • $\begingroup$ The problem in the given algorithm is that it only finds a negative cycle that is reachable from the starting vertex. Am I wrong? $\endgroup$ – Sama Assi May 17 at 15:15
  • $\begingroup$ Well, if your graph is connected (in the sense that there is one vertex from which all other vertices are reachable) anyway, then it doesn't seem to matter. And, if the graph is not connected, you only need break it down to its components. $\endgroup$ – dkaeae May 17 at 15:34
  • $\begingroup$ It's not component. How would it help me breaking the graph to its components? $\endgroup$ – Sama Assi May 17 at 15:36
  • $\begingroup$ If you have $k$ disjoint components, then you run the algorithm in the linked question on each component. You can even do so in parallel. $\endgroup$ – dkaeae May 17 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.