Professional Documents
Culture Documents
L
L
• If we use Bellman Ford algorithm – then advantage is that –ve weight cycles can
now be present –O(V2 E), for dense graphs O(V4).
• wij= 0 if i = j
= ∞ if i ≠ j, (i, j) does not belong to E
= the weight of the directed edge (i, j), if i ≠ j, and (i, j) belongs to E
Some more trivia
• Assume –ve weight edges are allowed, but no –ve weight cycles are allowed.
• Output is an n x n matrix D = (dij), where entry dij contains the weight of a
shortest path from vertex i to vertex j.
• Also will compute predecessor matrix π = (πij),
• where πij = nil if either i = j, or there is no path from i to j,
• otherwise it is the predecessor of j in some shortest path from i.
Floyd-Warshall Algorithm
• -ve weight edges may be present, but we assume that there are no -ve weight
cycles.
• A recursive solution:
• The weight of a shortest path from vertex i to vertex j for which all intermediate vertices
are in the set {1, 2, …., k}.
• When k = 0, a path from vertex i to vertex j with no intermediate vertex at all.
O(n3)
An example
Another DP problem(Longest Common Sub-sequence
problem)
• A sample application
• A strand of DNA can be expressed as a string over the finite set {A, C, G, T}.
• For example, the DNA of one organism may be –
S1 = ACCGGTCGAGTGCGCGGAAGCCGGCCGAA, S2 = GTCGTTCGGAATGCCGTTGCTCTGTAAA.
• Now we want to measure how closely related the two organisms are? By, comparing two strands of
DNA.
• Given 2 sequences X = <x1, x2, ……………., xm> and Y = <y1, y2, ……………., yn>, find a
maximum length common subsequence of X and Y.
• Eg. X = <ABCDEFG>, Y = <BCEDGF>, then <BCDF>, <BCDG>, <BCEF> and <BCEG> are all
LCS for these 2 sequences. (Note that it have to be a strictly increasing sequence).
• To find an LCS of X and Y, we may need to find the LCSs of X and Yn-1
and of Xm-1 and Y .
O(mn)