Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Jaehyun Park
Todays Lecture
of difference constraints
Output: the path between two given nodes and that minimizes the total weight (or cost, length)
Sometimes,
we want to compute all-pair shortest paths Sometimes, we want to compute shortest paths from to all other nodes
Floyd-Warshall Algorithm
Given a directed weighted graph Outputs a matrix where is the shortest distance from node to Can detect a negative-weight cycle Runs in 3 time Extremely easy to code
Coding
Floyd-Warshall Pseudocode
all and :
= min , +
If + < 0 for some and , then the graph has a negative weight cycle Done!
But
The optimal path for , , may or may not have as an intermediate node
it does, , , = , , 1 + , , 1 Otherwise, , , = , , 1
If
turns out that we dont need a separate matrix for each ; overwriting the existing values is fine
Dijkstras Algorithm
Outputs a vector where is the shortest distance from to node Time complexity depends on the implementation:
Can
be 2 + , log , log
Very similar to Prims algorithm Intuition: Find the closest node to , and then the second closest one, then the third, etc.
Dijkstras Algorithm
Maintain a set of nodes , the shortest distances to which are decided Also maintain a vector , the shortest distance estimate from Initially, = , and = cost , Repeat until = :
with the smallest , and add it to For each edge of cost :
Find
= min , +
Bellman-Ford Algorithm
Given a directed weighted graph and a source Outputs a vector where is the shortest distance from to node Can detect a negative-weight cycle Runs in time Extremely easy to code
Coding
Bellman-Ford Pseudocode
> + :
the graph contains a negative-weight cycle
Then
A shortest path can have at most 1 edges At the th iteration, all shortest paths of or less edges are computed After 1 iterations, all distances are final: for every edge of cost , + holds
Unless
there is a negative-weight cycle This is how the negative-weight cycle detection works
Graph Construction
Create node for every variable Make an imaginary source node Create zero-weight edges from to all other nodes Rewrite the given inequalities as +
For
What happens?
For every edge with cost , the shortest distance vector will satisfy +
Setting
cycle From our construction, the given constraints contain 2 1 + 1 , 3 2 + 2 , etc. Adding all of them gives 0 (somethingnegative) i.e. the given constraints were impossible to satisfy
It turns out that our solution minimizes the span of the variables: max min
We