chapter 8 dynamic programming. dynamic programming is a general algorithm design technique dynamic...

33
Chapter 8 Chapter 8 Dynamic Dynamic Programming Programming

Upload: lisa-randall

Post on 17-Dec-2015

237 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Chapter 8Chapter 8

Dynamic ProgrammingDynamic Programming

Page 2: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Dynamic ProgrammingDynamic Programming

DDynamic Programming ynamic Programming is a general algorithm design technique is a general algorithm design technique for solving problems defined by recurrences with overlappingfor solving problems defined by recurrences with overlapping subproblemssubproblems

• Invented by American mathematician Richard Bellman in the Invented by American mathematician Richard Bellman in the 1950s to solve optimization problems and later assimilated by CS1950s to solve optimization problems and later assimilated by CS

• “ “Programming” here means “planning”Programming” here means “planning”

• Main idea:Main idea:- set up a recurrence relating a solution to a larger instance set up a recurrence relating a solution to a larger instance

to solutions of some smaller instancesto solutions of some smaller instances- solve smaller instances once- solve smaller instances once- record solutions in a table record solutions in a table - extract solution to the initial instance from that tableextract solution to the initial instance from that table

Page 3: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Example: Fibonacci numbersExample: Fibonacci numbers

• Recall definition of Fibonacci numbers:Recall definition of Fibonacci numbers:

FF((nn)) = F = F((nn-1)-1) + F + F((nn-2)-2)FF(0)(0) = = 00FF(1)(1) = = 11

• Computing the Computing the nnthth Fibonacci number recursively (top-down): Fibonacci number recursively (top-down):

FF((nn))

FF((n-n-1) 1) + F + F((n-n-2)2)

FF((n-n-2) 2) + F+ F((n-n-3) 3) FF((n-n-3) 3) + F+ F((n-n-4)4)

......

Page 4: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Example: Fibonacci numbers (cont.)Example: Fibonacci numbers (cont.)

Computing the Computing the nnthth Fibonacci number using bottom-up iteration and Fibonacci number using bottom-up iteration and recording results:recording results:

FF(0)(0) = = 00 FF(1)(1) = = 11 FF(2)(2) = = 1+0 = 11+0 = 1 … … FF((nn-2) = -2) = FF((nn-1) = -1) = FF((nn) = ) = FF((nn-1)-1) + F + F((nn-2)-2)

Efficiency:Efficiency: - time- time - space- space

0

1

1

. . .

F(n-2)

F(n-1)

F(n)

Page 5: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Example 2: Coin-row problemExample 2: Coin-row problem

There is a row of There is a row of nn coins whose values are some positive coins whose values are some positive integers c₁, c₂,...,cintegers c₁, c₂,...,cnn, , not necessarily distinct. The goal is to not necessarily distinct. The goal is to

pick up the maximum amount of money subject to the pick up the maximum amount of money subject to the constraint that no two coins adjacent in the initial row can constraint that no two coins adjacent in the initial row can be picked up.be picked up.

E.g.: 5, 1, 2, 10, 6, 2. What is the best selection?E.g.: 5, 1, 2, 10, 6, 2. What is the best selection?

Page 6: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

DP solution to the coin-row problemDP solution to the coin-row problem

Let F(Let F(nn) be the maximum amount that can be picked up from ) be the maximum amount that can be picked up from the row of n coins. To derive a recurrence for F(the row of n coins. To derive a recurrence for F(nn), we ), we partition all the allowed coin selections into two groups:partition all the allowed coin selections into two groups:

those without last coin – the max amount is ?those without last coin – the max amount is ? those with the last coin -- the max amount is ?those with the last coin -- the max amount is ?

Thus we have the following recurrence Thus we have the following recurrence

F(F(nn) = max{c) = max{cn n + F(+ F(nn-2), F(-2), F(nn-1)} for -1)} for n n > 1, > 1,

F(0) = 0, F(1)=c₁F(0) = 0, F(1)=c₁

Page 7: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

DP solution to the coin-row problem (cont.)DP solution to the coin-row problem (cont.)

F(F(nn) = max{c) = max{cnn + F(+ F(nn-2), F(-2), F(nn-1)} for -1)} for n n > 1, > 1,

F(0) = 0, F(1)=c₁F(0) = 0, F(1)=c₁

IndexIndex 00 11 22 33 44 55 66

CoinsCoins ---- 55 11 22 1010 66 22

F( )F( )

Max amount:Max amount:

Coins of optimal solution:Coins of optimal solution:

Time efficiency:Time efficiency:

Space efficiency:Space efficiency:

Page 8: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Example 3: Path countingExample 3: Path counting

Consider the problem of counting the number of shortest Consider the problem of counting the number of shortest paths from point A to point B in a city with perfectly paths from point A to point B in a city with perfectly horizontal streets and vertical avenueshorizontal streets and vertical avenues

A

B

1

Page 9: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Example 4: Coin-collecting by robotExample 4: Coin-collecting by robot

Several coins are placed in cells of an Several coins are placed in cells of an nn××mm board. A robot, board. A robot, located in the upper left cell of the board, needs to collect as located in the upper left cell of the board, needs to collect as many of the coins as possible and bring them to the bottom many of the coins as possible and bring them to the bottom right cell. On each step, the robot can move either one cell to right cell. On each step, the robot can move either one cell to the right or one cell down from its current location. the right or one cell down from its current location.

1 2 3 4 5 6

1

2

3

4

5

Page 10: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Solution to the coin-collecting problemSolution to the coin-collecting problem

Let F(Let F(ii,,jj) be the largest number of coins the robot can collect ) be the largest number of coins the robot can collect and bring to cell (and bring to cell (ii,,jj) in the ) in the iith row and th row and jjth column.th column.

The largest number of coins that can be brought to cell (The largest number of coins that can be brought to cell (ii,,jj):):

from the left neighbor ?from the left neighbor ?from the neighbor above? from the neighbor above?

The recurrence: The recurrence: F(F(ii, , jj) = max{F() = max{F(ii-1, -1, jj), F(), F(ii, , jj-1)} + c-1)} + cij ij for 1 ≤ for 1 ≤ i i ≤ ≤ nn, 1 ≤ , 1 ≤ j j ≤ ≤ mmwherewhere c cijij = 1= 1 if there is a coin in cell (if there is a coin in cell (i,ji,j), and), and ccijij = 0 otherwise= 0 otherwise

F(0, F(0, jj) = 0 for 1 ≤ ) = 0 for 1 ≤ j j ≤ ≤ m m and F( and F(ii, 0) = 0 for 1 ≤ , 0) = 0 for 1 ≤ i i ≤ ≤ n.n.

Page 11: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Solution to the coin-collecting problem Solution to the coin-collecting problem (cont.)(cont.)

F(F(ii, , jj) = max{F() = max{F(ii-1, -1, jj), F(), F(ii, , jj-1)} + c-1)} + cij ij for 1 ≤ for 1 ≤ i i ≤ ≤ nn, 1 ≤ , 1 ≤ j j ≤ ≤ mm

wherewhere c cijij = 1= 1 if there is a coin in cell (if there is a coin in cell (i,ji,j), and), and ccijij = 0 otherwise= 0 otherwise

F(0, F(0, jj) = 0 for 1 ≤ ) = 0 for 1 ≤ j j ≤ ≤ m m and F( and F(ii, 0) = 0 for 1 ≤ , 0) = 0 for 1 ≤ i i ≤ ≤ n.n.1 2 3 4 5 6

1

2

3

4

5

Page 12: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Other Examples of DP algorithmsOther Examples of DP algorithms

• Computing a binomial coefficientComputing a binomial coefficient

• Warshall’s algorithm for transitive closureWarshall’s algorithm for transitive closure

• Floyd’s algorithm for all-pairs shortest pathsFloyd’s algorithm for all-pairs shortest paths

• Constructing an optimal binary search treeConstructing an optimal binary search tree

• Some instances of difficult discrete optimization problems:Some instances of difficult discrete optimization problems: - traveling salesman- traveling salesman - knapsack- knapsack

Page 13: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Computing a binomial coefficient by DPComputing a binomial coefficient by DP

Binomial coefficients are coefficients of the binomial formula:Binomial coefficients are coefficients of the binomial formula:((a + ba + b))nn = = CC((nn,0),0)aannbb0 0 + . . . + + . . . + CC((nn,,kk))aan-kn-kbbkk + . . . + . . . + CC((nn,,nn))aa00bbnn

Recurrence: Recurrence: CC((nn,,kk) = ) = CC((n-n-1,1,kk) + ) + CC((nn-1,-1,kk-1) for -1) for n > k n > k > 0> 0 CC((nn,0) = 1, ,0) = 1, CC((nn,,nn) = 1 for ) = 1 for n n 0 0 Value of Value of CC((nn,,kk) can be computed by filling a table:) can be computed by filling a table:

0 1 2 . . . 0 1 2 . . . kk-1 -1 kk 0 10 1 1 1 11 1 1 .. .. .. n-n-1 1 CC((n-n-1,1,kk-1) -1) CC((n-n-1,1,kk) ) nn CC((nn,,kk) )

Page 14: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Computing Computing CC((n,kn,k): pseudocode and analysis): pseudocode and analysis

Time efficiency: Time efficiency: ΘΘ((nknk))

Space efficiency: Space efficiency: ΘΘ((nknk))

Page 15: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s Algorithm: Transitive ClosureWarshall’s Algorithm: Transitive Closure

Definition: Definition:

the transitive closure of a directed graph with n vertices the transitive closure of a directed graph with n vertices can be defined as the n-by-n Boolean matrix T, in which the can be defined as the n-by-n Boolean matrix T, in which the element ith row (1<= i <= n) and jth column is 1 if there element ith row (1<= i <= n) and jth column is 1 if there exists a nontrivial directed path (a directed path of a exists a nontrivial directed path (a directed path of a positive length) from the ith vertex to the jth vertex positive length) from the ith vertex to the jth vertex otherwise totherwise tijij is 0. is 0.

Page 16: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s Algorithm: Transitive ClosureWarshall’s Algorithm: Transitive Closure

• Computes the transitive closure of a relationComputes the transitive closure of a relation

• Alternatively: existence of all nontrivial paths in a digraphAlternatively: existence of all nontrivial paths in a digraph

• Example of transitive closure:Example of transitive closure:

3

42

1

0 0 1 01 0 0 10 0 0 00 1 0 0

0 0 1 01 1 11 1 10 0 0 011 1 1 11 1

3

42

1

Page 17: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s AlgorithmWarshall’s Algorithm

Constructs transitive closure Constructs transitive closure TT as the last matrix in the sequence as the last matrix in the sequence of of nn-by--by-n n matrices matrices RR(0)(0), … ,, … , RR((kk)), … ,, … , RR((nn)) wherewhereRR((kk))[[ii,,jj] = 1 iff there is nontrivial path from ] = 1 iff there is nontrivial path from ii to to jj with only first with only first k k vertices allowed as intermediate vertices allowed as intermediate Note that Note that RR(0) (0) = = A A (adjacency matrix)(adjacency matrix),, RR((nn))

= T = T (transitive closure)(transitive closure)

3

42

13

42

13

42

13

42

1

R(0)

0 0 1 01 0 0 10 0 0 00 1 0 0

R(1)

0 0 1 01 0 11 10 0 0 00 1 0 0

R(2)

0 0 1 01 0 1 10 0 0 01 1 1 1 11 1

R(3)

0 0 1 01 0 1 10 0 0 01 1 1 1

R(4)

0 0 1 01 11 1 10 0 0 01 1 1 1

3

42

1

Page 18: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s Algorithm (recurrence)Warshall’s Algorithm (recurrence)

On theOn the k- k-th iteration, the algorithm determines for every pair of th iteration, the algorithm determines for every pair of vertices vertices i, ji, j if a path exists from if a path exists from i i andand j j with just vertices 1,…,with just vertices 1,…,k k allowedallowed asas intermediateintermediate

RR((kk-1)-1)[[i,ji,j] (path using just 1 ,…,] (path using just 1 ,…,k-k-1)1) RR((kk))[[i,ji,j] = or ] = or

RR((kk-1)-1)[[i,ki,k] and ] and RR((kk-1)-1)[[k,jk,j] (path from ] (path from i i to to kk and from and from kk to to ii using just 1 ,…,using just 1 ,…,k-k-1)1)

i

j

k

{

Page 19: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s Algorithm (matrix generation)Warshall’s Algorithm (matrix generation)

Recurrence relating elements Recurrence relating elements RR((kk)) to elements of to elements of RR((kk-1)-1) is: is:

RR((kk))[[i,ji,j] = ] = RR((kk-1)-1)[[i,ji,j] or] or ((RR((kk-1)-1)[[i,ki,k] and ] and RR((kk-1)-1)[[k,jk,j])])

It implies the following rules for generating It implies the following rules for generating RR((kk)) from from RR((kk-1)-1)::

Rule 1Rule 1 If an element in row If an element in row i i and column and column jj is 1 in is 1 in RR((k-k-1)1), , it remains 1 in it remains 1 in RR((kk))

Rule 2 Rule 2 If an element in row If an element in row i i and column and column jj is 0 in is 0 in RR((k-k-1)1),, it has to be changed to 1 in it has to be changed to 1 in RR((kk)) if and only if if and only if the element in its row the element in its row ii and column and column kk and the element and the element in its column in its column jj and row and row kk are both 1’s in are both 1’s in RR((k-k-1)1)

Page 20: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s Algorithm (example)Warshall’s Algorithm (example)

3

42

1 0 0 1 01 0 0 10 0 0 00 1 0 0

R(0) =

0 0 1 01 0 1 10 0 0 00 1 0 0

R(1) =

0 0 1 01 0 1 10 0 0 01 1 1 1

R(2) =

0 0 1 01 0 1 10 0 0 01 1 1 1

R(3) =

0 0 1 01 1 1 10 0 0 01 1 1 1

R(4) =

Page 21: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Warshall’s Algorithm (pseudocode and analysis)Warshall’s Algorithm (pseudocode and analysis)

Time efficiency: Time efficiency: ΘΘ((nn33))

Space efficiency: Matrices can be written over their predecessorsSpace efficiency: Matrices can be written over their predecessors

Page 22: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Floyd’s Algorithm: All pairs shortest pathsFloyd’s Algorithm: All pairs shortest paths

Problem: In a weighted (di)graph, find shortest paths betweenProblem: In a weighted (di)graph, find shortest paths between every pair of vertices every pair of vertices

Same idea: construct solution through series of matrices Same idea: construct solution through series of matrices DD(0)(0), …,, …, D D ((nn)) using increasing subsets of the vertices allowed using increasing subsets of the vertices allowed as intermediate as intermediate

Example:Example: 3

42

14

16

1

5

3

Page 23: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Floyd’s Algorithm (matrix generation)Floyd’s Algorithm (matrix generation)

On theOn the k- k-th iteration, the algorithm determines shortest paths th iteration, the algorithm determines shortest paths between every pair of vertices between every pair of vertices i, j i, j that use only vertices among 1,that use only vertices among 1,…,…,k k as intermediateas intermediate

DD((kk))[[i,ji,j] = min {] = min {DD((kk-1)-1)[[i,ji,j], ], DD((kk-1)-1)[[i,ki,k] + ] + DD((kk-1)-1)[[k,jk,j]}]}

i

j

k

DD((kk-1)-1)[[i,ji,j]]

DD((kk-1)-1)[[i,ki,k]]

DD((kk-1)-1)[[k,jk,j]]

Page 24: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Floyd’s Algorithm (example)Floyd’s Algorithm (example)

0 ∞ 3 ∞ 2 0 ∞ ∞∞ 7 0 16 ∞ ∞ 0

D(0) =

0 ∞ 3 ∞ 2 0 5 ∞∞ 7 0 16 ∞ 9 0

D(1) =

0 ∞ 3 ∞2 0 5 ∞9 7 0 16 ∞ 9 0

D(2) =

0 10 3 42 0 5 69 7 0 16 16 9 0

D(3) =

0 10 3 42 0 5 67 7 0 16 16 9 0

D(4) =

31

3

2

6 7

4

1 2

Page 25: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Floyd’s Algorithm (pseudocode and analysis)Floyd’s Algorithm (pseudocode and analysis)

Time efficiency: Time efficiency: ΘΘ((nn33))

Space efficiency: Matrices can be written over their predecessorsSpace efficiency: Matrices can be written over their predecessors

Note: Shortest paths themselves can be found, tooNote: Shortest paths themselves can be found, too

Page 26: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Optimal Binary Search TreesOptimal Binary Search Trees

Problem: Given Problem: Given n n keys keys aa1 1 < …< < …< aan n and probabilities and probabilities pp11 ≤ ≤ … ≤ … ≤ ppnn

searching for them, find a BST with a minimumsearching for them, find a BST with a minimum

average number of comparisons in successful search. average number of comparisons in successful search.

Since total number of BSTs with Since total number of BSTs with n n nodes is given by nodes is given by C(2C(2nn,,nn)/()/(nn+1), which grows exponentially, brute force is hopeless. +1), which grows exponentially, brute force is hopeless.

Example: What is an optimal BST for keys Example: What is an optimal BST for keys AA, , BB,, C C, and , and D D withwith search probabilities 0.1, 0.2, 0.4, and 0.3, respectively? search probabilities 0.1, 0.2, 0.4, and 0.3, respectively?

Optimal binary search tree is one for which the average Optimal binary search tree is one for which the average number of comparisons in the search is as small as possible. number of comparisons in the search is as small as possible.

Limit this to:Limit this to:

Page 27: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

DP for Optimal BST ProblemDP for Optimal BST Problem

Let Let CC[[i,ji,j] be minimum average number of comparisons made in ] be minimum average number of comparisons made in T[T[i,ji,j], optimal BST for keys ], optimal BST for keys aaii < …< < …< aajj ,, where 1 ≤ where 1 ≤ i i ≤ ≤ j j ≤ ≤ n. n.

Consider optimal BST among all BSTs with some Consider optimal BST among all BSTs with some aak k ((i i ≤ ≤ k k ≤≤ jj ) )

as their root; T[as their root; T[i,ji,j] is the best among them. ] is the best among them.

a

OptimalBST for

a , ..., a

OptimalBST for

a , ..., ai

k

k-1 k+1 j

CC[[i,ji,j] =] =

min {min {ppk k · · 1 +1 +

∑ ∑ ppss (level (level aas s in T[in T[i,k-i,k-1] +1)1] +1) ++

∑ ∑ ppss (level (level aass in T[in T[k+k+11,j,j] +1)}] +1)}

i i ≤ ≤ k k ≤≤ jj

s s == ii

k-k-11

s =s =k+k+11

jj

Page 28: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

goal0

0

C[i,j]

0

1

n+1

0 1 n

p 1

p2

np

i

j

DP for Optimal BST Problem (cont.)DP for Optimal BST Problem (cont.)

After simplifications, we obtain the recurrence for After simplifications, we obtain the recurrence for CC[[i,ji,j]:]:

CC[[i,ji,j] = ] = min {min {CC[[ii,,kk-1] + -1] + CC[[kk+1,+1,jj]} + ]} + ∑∑ ppss forfor 1 1 ≤≤ i i ≤≤ j j ≤≤ nn

CC[[i,ii,i] = ] = ppi i for 1 for 1 ≤≤ i i ≤≤ j j ≤≤ nn

s s == ii

jj

i i ≤≤ k k ≤≤ jj

Page 29: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Example: key Example: key A B C DA B C D

probability 0.1 0.2 0.4 0.3probability 0.1 0.2 0.4 0.3

The tables below are filled diagonal by diagonal: the left one is filled The tables below are filled diagonal by diagonal: the left one is filled using the recurrence using the recurrence CC[[i,ji,j] = ] = min {min {CC[[ii,,kk-1] + -1] + CC[[kk+1,+1,jj]} + ∑ ]} + ∑ pps , s , CC[[i,ii,i] = ] = ppi i ;;

the right one, for trees’ roots, records the right one, for trees’ roots, records kk’s values giving the minima’s values giving the minima

00 11 22 33 44

11 00 .1.1 .4.4 1.11.1 1.71.7

22 00 .2.2 .8.8 1.41.4

33 00 .4.4 1.01.0

44 00 .3.3

55 00

00 11 22 33 44

11 11 22 33 33

22 22 33 33

33 33 33

44 44

55

i i ≤ ≤ k k ≤≤ jj s s == ii

jj

optimal BSToptimal BST

B

A

C

D

i i jji i jj

Page 30: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Optimal Binary Search TreesOptimal Binary Search Trees

Page 31: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Analysis DP for Optimal BST ProblemAnalysis DP for Optimal BST Problem

Time efficiency: Time efficiency: ΘΘ((nn33) but can be reduced to ) but can be reduced to ΘΘ((nn22)) by takingby taking advantage of monotonicity of entries in the advantage of monotonicity of entries in the root table, i.e., root table, i.e., RR[[i,ji,j] is always in the range ] is always in the range between between RR[[i,ji,j-1] and R[-1] and R[ii+1,j]+1,j]

Space efficiency: Space efficiency: ΘΘ((nn22))

Method can be expended to include unsuccessful searchesMethod can be expended to include unsuccessful searches

Page 32: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Knapsack Problem by DPKnapsack Problem by DP

Given Given nn items of items of

integer weights: integer weights: ww1 1 ww22 … w … wnn

values: values: vv1 1 vv22 … v … vnn

a knapsack of integer capacity a knapsack of integer capacity WW find most valuable subset of the items that fit into the knapsackfind most valuable subset of the items that fit into the knapsack

Consider instance defined by first Consider instance defined by first i i items and capacity items and capacity j j ((j j WW))..

Let Let VV[[ii,,jj] be optimal value of such instance. Then] be optimal value of such instance. Then

max {max {VV[[ii-1,-1,jj], ], vvii + + VV[[ii-1,-1,j- j- wwii]} if ]} if j- j- wwi i 0 0VV[[ii,,jj] =] =

VV[[ii-1,-1,jj] if ] if j- j- wwi i < 0< 0

Initial conditions: Initial conditions: VV[0,[0,jj] = 0 and ] = 0 and VV[[ii,0] = 0,0] = 0

Page 33: Chapter 8 Dynamic Programming. Dynamic Programming is a general algorithm design technique Dynamic Programming is a general algorithm design technique

Knapsack Problem by DP (example)Knapsack Problem by DP (example)

Example: Knapsack of capacity Example: Knapsack of capacity W W = 5= 5item weight value item weight value 1 2 $121 2 $12 2 1 $102 1 $10 3 3 $203 3 $20 4 2 $15 capacity 4 2 $15 capacity jj

0 1 2 3 40 1 2 3 4 55 00

ww1 1 = 2, = 2, vv11== 12 112 1

ww2 2 = 1, = 1, vv22== 10 210 2

ww3 3 = 3, = 3, vv33== 20 320 3

ww4 4 = 2, = 2, vv44== 15 415 4 ??