2

I have a graph that has both positive and negative weights. Some of the nodes have multiple weights, for example node A has two edges with different weights connected to node B. Can Floyd Warshall algorithm handle this?

I have tried using Bellman Ford, I can calculate the distances but I can't reliably construct the path.

Mostafa Fakhraei
  • 3,409
  • 3
  • 11
  • 25
  • 1
    If there are two edges from A to B with different weights, then you would discard the edge with the higher weight. – user3386109 Jan 07 '23 at 19:23

1 Answers1

1

Floyd-Warshall stores edges in a matrix. Therefore, it can't account for multiple edges between a pair of nodes. Still, when constructing the initial matrix, just store the "best" (smallest) edge between each pair.

That said, Bellman-Ford is perhaps more convenient for detecting negative cycles. The reason is that, in Bellman-Ford with negative cycles, the absolute values of distances grow polynomially throughout the algorithm. However, with Floyd-Warshall, they grow exponentially, which will perhaps result in overflow unless extra care is taken at each step.

Gassa
  • 8,546
  • 3
  • 29
  • 49
  • One thing I found is that sometimes when the path goes through a node it chooses one weight but when it cycles back to the source node it goes through that same node but via the other weight, but this way complicates constructing the path. I'm doing a negative log transform to the weights so I can detect negative cycles. – Rodrigo Pina Jan 08 '23 at 00:55