18.04.2013 Views

The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998

The.Algorithm.Design.Manual.Springer-Verlag.1998

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>The</strong> Partition Problem<br />

Figure: Dynamic programming matrices M and D in partitioning<br />

<strong>The</strong> implementation above in fact runs faster than advertised. Our original analysis assumed that it took time to update<br />

each cell of the matrix. This is because we selected the best of up to n possible points to place the divider, each of which<br />

requires the sum of up to n possible terms. In fact, it is easy to avoid the need to compute these sums by storing the set of n<br />

prefix sums , since . This enables us to evaluate the recurrence in linear time per cell, yielding<br />

an algorithm.<br />

By studying the recurrence relation and the dynamic programming matrices of Figures and , you should be able to<br />

convince yourself that the final value of M(n,k) will be the cost of the largest range in the optimal partition. However, what<br />

good is that? For most applications, what we need is the actual partition that does the job. Without it, all we are left with is a<br />

coupon for a great price on an out-of-stock item.<br />

<strong>The</strong> second matrix, D, is used to reconstruct the optimal partition. Whenever we update the value of M[i,j], we record which<br />

divider position was required to achieve that value. To reconstruct the path used to get to the optimal solution, we work<br />

backward from D[n,k] and add a divider at each specified position. This backwards walking is best achieved by a recursive<br />

subroutine:<br />

ReconstructPartition(S,D,n,k)<br />

If (k = 1) then print the first partition<br />

else<br />

ReconstructPartition(S,D,D[n,k],k-1)<br />

Print the kth partition { }<br />

It is important to catch the distinction between storing the value of a cell and what decision/move it took to get there. <strong>The</strong> latter<br />

is not used in the computation but is presumably the real thing that you are interested in. For most of the examples in this<br />

chapter, we will not worry about reconstructing the answer. However, study this example closely to ensure that you know how<br />

to obtain the winning configuration when you need it.<br />

file:///E|/BOOK/BOOK2/NODE45.HTM (4 of 5) [19/1/2003 1:28:44]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!