25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

PROCEDURE WriteTree (i, j, level: INTEGER);<br />

VAR k: INTEGER; (*uses global writer W*)<br />

BEGIN<br />

IF i < j THEN<br />

WriteTree(i, r[i, j]-1, level+1);<br />

FOR k := 1 TO level DO Texts.Write(W, TAB) END;<br />

Texts.WriteString(W, key[r[i, j]]); Texts.WriteLn(W);<br />

WriteTree(r[i, j], j, level+1)<br />

END<br />

END WriteTree;<br />

PROCEDURE Find (VAR S: Texts.Scanner);<br />

VAR i, j, n: INTEGER; (*uses global writer W*)<br />

BEGIN<br />

Texts.Scan(S); b[0] := SHORT(S.i);<br />

n := 0; Texts.Scan(S); (*input: a, key, b*)<br />

WHILE S.class = Texts.Int DO<br />

INC(n); a[n] := SHORT(S.i); Texts.Scan(S); COPY(S.s, key[n]);<br />

Texts.Scan(S); b[n] := SHORT(S.i); Texts.Scan(S)<br />

END;<br />

(*compute w from a <strong>and</strong> b*)<br />

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

w[i, i] := b[i];<br />

FOR j := i+1 TO n DO<br />

w[i, j] := w[i, j-1] + a[j] + b[j]<br />

END<br />

END;<br />

Texts.WriteString(W, "Total weight = ");<br />

Texts.WriteInt(W, w[0, n], 6); Texts.WriteLn(W);<br />

Texts.WriteString(W, "Path length of balanced tree = ");<br />

Texts.WriteInt(W, BalTree(0, n), 6); Texts.WriteLn(W);<br />

WriteTree(0, n, 0); Texts.WriteLn(W);<br />

ComputeOptTree(n);<br />

Texts.WriteString(W, "Path length of optimal tree = ");<br />

Texts.WriteInt(W, p[0, n], 6); Texts.WriteLn(W);<br />

WriteTree(0, n, 0); Texts.WriteLn(W);<br />

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

w[i, i] := 0;<br />

FOR j := i+1 TO n DO w[i, j] := w[i, j-1] + a[j] END<br />

END;<br />

ComputeOptTree(n);<br />

Texts.WriteString(W, "optimal tree not considering b"); Texts.WriteLn(W);<br />

WriteTree(0, n, 0); Texts.WriteLn(W)<br />

END Find;<br />

As an example, let us consider the following input data of a tree with 3 keys:<br />

20 1 Albert 10 2 Ernst 1 5 Peter 1<br />

b 0 = 20<br />

a 1 = 1 key 1 = Albert b 1 = 10

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

Saved successfully!

Ooh no, something went wrong!