Lecture 2 DP
Lecture 2 DP
1 4
S A B 5
T
5 6
• Apply the greedy method :
the shortest path from S to T :
1+2+5=8
2 5 13
S B E T
16 2
5
C 2
F
2 d(B, T)
S B T
d(C, T)
5
C
5 d(E , T )
B E T
d(F , T )
16
F
3/8/2009 ADA Unit -4 I.S Borse 23
Backward approach (forward reasoning)
• d(S, A) = 1
d(S, B) = 2
d(S, C) = 5
• d(S,D)=min{d(S, A)+d(A, D),d(S, B)+d(B, D)}
= min{ 1+4, 2+9 } = 5
d(S,E)=min{d(S, A)+d(A, E),d(S, B)+d(B, E)}
= min{ 1+11, 2+5 } = 7
d(S,F)=min{d(S, A)+d(A, F),d(S, B)+d(B, F)}
= min{ 2+16, 5+2 } = 7
(k=5)
Stage 5
cost(5,12) = 0.0
Stage 4
cost(4,9) = min {4+cost(5,12)} = 4
cost(4,10) = min {2+cost(5,12)} = 2
cost(4,11) = min {5+cost(5,12)} = 5
Stage 3
cost(3,6) = min {6+cost(4,9), 5+cost(4,10)} = 7
cost(3,7) = min {4+cost(4,9), 3+cost(4,10)} = 5
cost(3,8) = min {5+cost(4,10), 6+cost(4,11)} = 7
– Stage 2
• cost(2,2) = min {4+cost(3,6), 2+cost(3,7), 1+cost(3,8)} = 7
• cost(2,3) = min {2+cost(3,6), 7+cost(3,7)} = 9
• cost(2,4) = min {11+cost(3,8)} = 18
• cost(2,5) = min {11+cost(3,7), 8+cost(3,8)} = 15
– Stage 1
• cost(1,1) = min {9+cost(2,2), 7+cost(2,3), 3+cost(2,4), 2+cost(2,5)} = 16
– Important notes: avoiding the recomputation of cost(3,6), cost(3,7), and
cost(3,8) in computing cost(2,2)
3/8/2009 ADA Unit -4 I.S Borse 17
Multistage Graphs
• void Fgraph (graph G, int k, int n, int p[] )
• // The input is a k-stage graph G = (V,E) with n vertices indexed in order
• // of stages. E is a set of edges and c[i][j] is the cost of <i, j>.
• // p[1 : k] is a minimum-cost path.
• {
• float cost[MAXSIZE]; int d[MAXSIZE], r;
• cost[n] = 0.0;
• for (int j=n-1; j >= 1; j--)
• { // Compute cost[j].
• let r be a vertex such that <j, r> is an edge
• of G and c[j][r] + cost[r] is minimum;
• cost[j] = c[j][r] + cost[r];
• d[j] = r;
• }
• // Find a minimum-cost path.
• p[1] = 1; p[k] =n ;
• for ( j=2; j <= k-1; j++) p[j] = d[ p[ j-1 ] ];
• }
3/8/2009 ADA Unit -4 I.S Borse 19
Multistage Graphs
Backward approach
maximize Pi x i subject to W x 1 i n
M i i
1 i n
xi = 0 or 1, 1 i n
• e. g.
i Wi Pi
1 10 40 M = 10
2 3 20
3 5 30