DP - 07
DP - 07
Dynamic Programming II
7-2
Shortest Path
Suppose that every arc e of a digraph G has length (or cost, or weight, or ) len(e) But now we allow negative lengths (weights) Then we can naturally define the length of a directed path in G, and the distance between any two nodes The s-t-Shortest Path Problem Instance: Digraph G with lengths of arcs, and nodes s,t Objective: Find a shortest path between s and t
7-3
<0
t
Greediness fails 2
s
-6 1
t
7-4
7-5
Shortest v t path can use i 1 arcs. Then OPT(i,v) = OPT(i 1,v) Or it can use i arcs and the first arc is vw. Then OPT(i,v) = len(vw) + OPT(i 1,w) OPT (i, v) = min{OPT (i 1, v), min{OPT (i 1, w) + len(vw)}}
wV
7-6
7-7
Example
a
6 -1
d
-3 4
v e t a b c d
-4
b
0
0
1
0 -3 3 4 2
2
0 -3 0 3 3 0
3
0 -4 -2 3 3 0
4
0 -6 -2 3 2 0
5
0 -6 -2 3 0 0
-2 2 -3
8
c
7-8
Proof. Soundness follows by induction from the recurrent relation for the optimal value. DIY. Running time: 2 We fill up a table with n entries. Each of them requires O(n) time
7-9
A big improvement for sparse graphs Proof. Consider the computation of the array entry M[i,v]: M[i,v] = min{ M[i 1, v], minw V { M[ i 1, w] + len(vw) }} We need only compute the minimum over all nodes w for which v has an edge to w Let nv denote the number of such edges
7-10
7-11
7-12
7-13
7-14
0>
k 1 i =1
7-15
7-16
<0 <0
t
7-17
As is easily seen, G contains a negative cycle if and only if A(G) contains a negative cycle C such that t is reachable from C QED
7-18
7-19
7-20
7-21
7-22
Alignments
Let X = x1, x2 ,K, xm and Y = y1 , y2 ,K, yn be two strings A matching is a set of ordered pairs, such that an element of each set occurs at most once. A matching is an alignment if there no crossing pairs: if (i,j) and (i,j) are in the matching and i < i then j < j o o o o c c c c c c u u u u r r r r r r a r a r n e n e c n c n e c e c e e
7-23
The Problem
Let M be an alignment between X and Y. Each position of X or Y that is not matched in M is called a gap. Each pair (i,j) M such that xi y j is called a mismatch The cost of M is given as follows: - There is > 0, a gap penalty. For each gap in M we incur a cost of - For each pair of letters p,q in the alphabet, there is a mismatch cost pq . For each (i,j) M we pay the mismatch cost xi y j . Usually, pp = 0. - The cost of M is the sum its gap penalties and mismatch costs
7-24
7-25
7-26
The Idea
Corollary In an optimal alignment M, at least one of the following is true (i) (m,n) M; or (ii) the m-th position of X is not matched; or (iii) the n-th position of Y is not matched. Let OPT(i,j) denote the minimum cost of an alignment between To get OPT(m,n) we (i) pay xm yn and then align x1, x2 ,K, xm1 and y1 , y2 ,K, yn1 as well as possible, to get OPT (m, n) = OPT (m 1, n 1) + xm yn
7-27
7-28
Alignment: Algorithm
Alignment(X,Y)
array M[0..m,0..n] set M[i,0]:=i for each i set M[0,j]:=j for each j for i=1 to m do for j=1 to n do set M[i,j]:=min{M[i-1,j-1]+ M[i,j-1]+} endfor endfor return M[m,n]
, M[i-1,j]+,