25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 174<br />

We are now ready to construct the optimization algorithm in detail. We recall the following definitions,<br />

which are based on optimal trees T ij consisting of nodes with keys k i+1 ... k j :<br />

1. a i : the frequency of a search for k i .<br />

2. b j : the frequency of a search argument x between k j <strong>and</strong> k j+1 .<br />

3. w ij : the weight of T ij .<br />

4. p ij : the weighted path length of T ij .<br />

5. r ij : the index of the root of T ij .<br />

We declare the following arrays:<br />

a: ARRAY n+1 OF INTEGER; (*a[0] not used*)<br />

b: ARRAY n+1 OF INTEGER;<br />

p,w,r: ARRAY n+1, n+1 OF INTEGER;<br />

Assume that the weights w ij have been computed from a <strong>and</strong> b in a straightforward way. Now consider w<br />

as the argument of the procedure OptTree to be developed <strong>and</strong> consider r as its result, because r<br />

describes the tree structure completely. p may be considered an intermediate result. Starting out by<br />

considering the smallest possible subtrees, namely those consisting of no nodes at all, we proceed to larger<br />

<strong>and</strong> larger trees. Let us denote the width j-i of the subtree T ij by h. Then we can trivially determine the<br />

values p ii for all trees with h = 0 according to the definition of p ij :<br />

FOR i := 0 TO n DO p[i,i] := b[i] END<br />

In the case h = 1 we deal with trees consisting of a single node, which plainly is also the root (see Fig.<br />

4.38).<br />

FOR i := 0 TO n-1 DO<br />

j := i+1; p[i,j] := w[i,j] + p[i,i] + p[j,j]; r[i,j] := j<br />

END<br />

k j|a j<br />

b j-1<br />

b j<br />

w j-1, j-1<br />

w j-1, j<br />

Fig. 4.38. Optimal search tree with single node<br />

Note that i denotes the left index limit <strong>and</strong> j the right index limit in the considered tree T ij . For the cases<br />

h > 1 we use a repetitive statement with h ranging from 2 to n, the case h = n spanning the entire tree<br />

T 0,n . In each case the minimal path length p ij <strong>and</strong> the associated root index r ij are determined by a simple<br />

repetitive statement with an index k ranging over the interval given for r ij :<br />

FOR h := 2 TO n DO<br />

FOR i := 0 TO n-h DO<br />

j := i+h;<br />

find k <strong>and</strong> min = MIN k: i < k < j : (p i,k-1 + p kj ) such that r i,j-1 < k < r i+1,j ;<br />

p[i,j] := min + w[i,j]; r[i,j] := k<br />

END<br />

END

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

Saved successfully!

Ooh no, something went wrong!