1 advanced algorithms all-pairs sps dp algorithm floyd-warshall alg
Post on 21-Dec-2015
253 views
TRANSCRIPT
1
Advanced Algorithms
All-pairs SPs DP algorithm
Floyd-Warshall alg.
2
APSP Problem
Given a directed graph G = (V, E), weight function w : E → R, |V| = n determine the length of the shortest path between all pairs of vertices in G.
In other words, we want to create an n × n matrix of shortest-path distances δ(u, v).
Here we assume that there are no cycles with zero or negative cost.
Could run BELLMAN-FORD once from each vertex:
• O(V2E) - which is O(V4) if the graph is dense (E = Ө(V2)).
3
APSP (cont.)
If no negative-weight edges, could run Dijkstra.s algorithm once from each vertex:
O(V E lg V) with binary heap - O(V3lg V) if dense,
O(V2lg V + V E) with Fibonacci heap - O(V3) if dense.
We will see how to do in O(V3) in all cases, with no fancy data structure.
4
Terminologies
G = (V, E) where V are numbered 1, 2, .. n=|V|
Input : , n n matrix Output: , n n matrix
5
Dynamic Programming Approach
Optimal substructure property holds Define subproblem:
: minimum weight of any path from vertex i to j that contains at most m edges.
Recursive solution Base case : m = 0
6
Recursive Solution cont.
Goal:
Example:
7
Build DP-table
Compute in order
= W
Go from
8
Pseudo-code cont.
Time complexity:
Extend:
Slow-Apsp:
Can we do better ?
9
Matrix Multiplication
Extend procedure same as matrix multiplication L’ = L W !
=L(m)
W(m)
Goal: compute W(n-1)
Only need to compute , , , …, W2
W1
W(n-1)
W4
10
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
11
Faster Algorithm
Time complexity:
12
Floyd-Warshall Algorithm
Structure of a shortest path
13
Structure of a shortest path (cont.)
14
Recursive solution
Recursive solution: : the weight of shortest path from vertex i to j
where all intermediate vertices are from set {1, 2, … , k}.
Goal: To compute = D
(n)
15
Pseudo-code
Time complexity:
16
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
17
Constructing a shortest Path
Compute a sequence of matrices Π(0), Π(1), Π(2),…, Π(n), where Π= Π(n).
18
Construct a shortest path
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
19
Thank you.