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 126<br />

Weight: 10 11 12 13 14 15 16 17 18 19<br />

Value: 18 20 17 19 25 21 27 23 25 24<br />

limw ↓<br />

maxv<br />

10 * 18<br />

20 * 27<br />

30 * * 52<br />

40 * * * 70<br />

50 * * * * 84<br />

60 * * * * * 99<br />

70 * * * * * 115<br />

80 * * * * * * 130<br />

90 * * * * * * 139<br />

100 * * * * * * * 157<br />

110 * * * * * * * * 172<br />

120 * * * * * * * * 183<br />

Table 3.5. Sample Output from Optimal Selection Program.<br />

The asterisks mark the objects that form the optimal sets opts for the total weight limits ranging from 10<br />

to 120.<br />

This backtracking scheme with a limitation factor curtailing the growth of the potential search tree is also<br />

known as branch <strong>and</strong> bound algorithm.<br />

Exercises<br />

3.1. (Towers of Hanoi). Given are three rods <strong>and</strong> n disks of different sizes. The disks can be stacked up<br />

on the rods, thereby forming towers. Let the n disks initially be placed on rod A in the order of decreasing<br />

size, as shown in Fig. 3.9 for n = 3. The task is to move the n disks from rod A to rod C such that they are<br />

ordered in the original way. This has to be achieved under the constraints that<br />

1. In each step exactly one disk is moved from one rod to another rod.<br />

2. A disk may never be placed on top of a smaller disk.<br />

3. Rod B may be used as an auxiliary store.<br />

Find an algorithm that performs this task. Note that a tower may conveniently be considered as consisting<br />

of the single disk at the top, <strong>and</strong> the tower consisting of the remaining disks. Describe the algorithm as a<br />

recursive program.<br />

0<br />

1<br />

2<br />

Fig. 3.9. The towers of Hanoi<br />

A B C<br />

3.2. Write a procedure that generates all n! permutations of n elements a 0 , ..., a n-1 in situ, i.e., without<br />

the aid of another array. Upon generating the next permutation, a parametric procedure Q is to be called<br />

which may, for instance, output the generated permutation.<br />

Hint: Consider the task of generating all permutations of the elements a 0 , ..., a m-1 as consisting of the<br />

m subtasks of generating all permutations of a 0 , ..., a m-2 followed by a m-1 , where in the i-th subtask the<br />

two elements a i <strong>and</strong> a m-1 had initially been interchanged.

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

Saved successfully!

Ooh no, something went wrong!