Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung...

20
Pr¨ ufung Datenstrukturen und Algorithmen (D-MATH RW) Felix Friedrich, Departement Informatik ETH Z¨ urich, 7.8.2017. Name, Vorname: .................................................................. Legi-Nummer: .................................................................. Ich best¨ atige mit meiner Unterschrift, dass ich diese Pr¨ ufung unter regul¨ aren Bedingungen ablegen konnte, und dass ich die allgemeinen Richtlinien gelesen und verstanden habe. I confirm with my signature that I was able to take this exam under regular conditions and that I have read and understood the general guidelines. Unterschrift: Allgemeine Richtlinien: General guidelines: 1. Dauer der Pr¨ ufung: 120 Minuten. Exam duration: 120 minutes. 2. Erlaubte Unterlagen: W¨ orterbuch (f¨ ur gesprochene Spra- chen). 4 A4 Seiten handgeschrieben oder 11pt Schrift- gr¨ osse. Permitted examination aids: dictionary (for spoken lan- guages). 4 A4 pages hand written or 11pt font size 3. Ben¨ utzen Sie einen Kugelschreiber (blau oder schwarz) und keinen Bleistift. Bitte schreiben Sie leserlich. Nur lesbare Resultate werden bewertet. Use a pen (black or blue), not a pencil. Please write legibly. We will only consider solutions that we can read. 4. osungen sind direkt auf das Aufgabenblatt in die daf¨ ur vorgesehenen Boxen zu schreiben (und direkt darunter, falls mehr Platz ben¨ otigt wird). Ung¨ ultige L¨ osungen sind deut- lich durchzustreichen! Korrekturen bei Multiple-Choice Auf- gaben bitte unmissverst¨ andlich anbringen! Solutions must be written directly onto the exam sheets in the provided boxes (and directly below, if more space is needed). Invalid solutions need to be crossed out clearly. Provide corrections to answers of multiple choice questions without any ambiguity! 5. Es gibt keine Negativpunkte f¨ ur falsche Antworten. There are no negative points for false answers. 6. St¨ orungen durch irgendjemanden oder irgendetwas melden Sie bitte sofort der Aufsichtsperson. If you feel disturbed by anyone or anything, let the supervisor of the exam know immediately. 7. Wir sammeln die Pr¨ ufung zum Schluss ein. Wichtig: stellen Sie unbedingt selbst sicher, dass Ihre Pr¨ ufung von einem Assistenten eingezogen wird. Stecken Sie keine Pr¨ ufung ein und lassen Sie Ihre Pr¨ ufung nicht einfach am Platz liegen. Dasselbe gilt, wenn Sie fr¨ uher abgeben wollen: bitte mel- den Sie sich lautlos, und wir holen die Pr¨ ufung ab. Vor- zeitige Abgaben sind nur bis 15 Minuten vor Pr¨ ufungsende oglich. We collect the exams at the end. Important: you must ensure that your exam has been collected by an as- sistant. Do not take any exam with you and do not leave your exam behind on your desk. The same ap- plies when you want to finish early: please contact us silently and we will collect the exam. Handing in your exam ahead of time is only possible until 15 minutes before the exam ends. 8. Wenn Sie zur Toilette m¨ ussen, melden Sie dies einer Auf- sichtsperson durch Handzeichen. If you need to go to the toilet, raise your hand and wait for a supervisor. 9. Wir beantworten keine inhaltlichen Fragen w¨ ahrend der Pr¨ ufung. Kommentare zur Aufgabe schreiben Sie bitte auf das Aufgabenblatt. We will not answer any content-related questions du- ring the exam. Please write comments referring to the tasks on the exam sheets. Question: 1 2 3 4 5 6 Total Points: 10 7 10 8 7 7 49 Score:

Transcript of Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung...

Page 1: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

PrufungDatenstrukturen und Algorithmen (D-MATH RW)

Felix Friedrich, Departement InformatikETH Zurich, 7.8.2017.

Name, Vorname: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Legi-Nummer: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Ich bestatige mit meiner Unterschrift, dass ichdiese Prufung unter regularen Bedingungenablegen konnte, und dass ich die allgemeinenRichtlinien gelesen und verstanden habe.

I confirm with my signature that I was ableto take this exam under regular conditionsand that I have read and understood thegeneral guidelines.

Unterschrift:

Allgemeine Richtlinien: General guidelines:

1. Dauer der Prufung: 120 Minuten. Exam duration: 120 minutes.

2. Erlaubte Unterlagen: Worterbuch (fur gesprochene Spra-chen). 4 A4 Seiten handgeschrieben oder ≥ 11pt Schrift-grosse.

Permitted examination aids: dictionary (for spoken lan-guages). 4 A4 pages hand written or ≥ 11pt font size

3. Benutzen Sie einen Kugelschreiber (blau oder schwarz) undkeinen Bleistift. Bitte schreiben Sie leserlich. Nur lesbareResultate werden bewertet.

Use a pen (black or blue), not a pencil. Please writelegibly. We will only consider solutions that we canread.

4. Losungen sind direkt auf das Aufgabenblatt in die dafurvorgesehenen Boxen zu schreiben (und direkt darunter, fallsmehr Platz benotigt wird). Ungultige Losungen sind deut-lich durchzustreichen! Korrekturen bei Multiple-Choice Auf-gaben bitte unmissverstandlich anbringen!

Solutions must be written directly onto the examsheets in the provided boxes (and directly below, ifmore space is needed). Invalid solutions need to becrossed out clearly. Provide corrections to answers ofmultiple choice questions without any ambiguity!

5. Es gibt keine Negativpunkte fur falsche Antworten. There are no negative points for false answers.

6. Storungen durch irgendjemanden oder irgendetwas meldenSie bitte sofort der Aufsichtsperson.

If you feel disturbed by anyone or anything, let thesupervisor of the exam know immediately.

7. Wir sammeln die Prufung zum Schluss ein. Wichtig: stellenSie unbedingt selbst sicher, dass Ihre Prufung von einemAssistenten eingezogen wird. Stecken Sie keine Prufung einund lassen Sie Ihre Prufung nicht einfach am Platz liegen.Dasselbe gilt, wenn Sie fruher abgeben wollen: bitte mel-den Sie sich lautlos, und wir holen die Prufung ab. Vor-zeitige Abgaben sind nur bis 15 Minuten vor Prufungsendemoglich.

We collect the exams at the end. Important: you mustensure that your exam has been collected by an as-sistant. Do not take any exam with you and do notleave your exam behind on your desk. The same ap-plies when you want to finish early: please contact ussilently and we will collect the exam. Handing in yourexam ahead of time is only possible until 15 minutesbefore the exam ends.

8. Wenn Sie zur Toilette mussen, melden Sie dies einer Auf-sichtsperson durch Handzeichen.

If you need to go to the toilet, raise your hand andwait for a supervisor.

9. Wir beantworten keine inhaltlichen Fragen wahrend derPrufung. Kommentare zur Aufgabe schreiben Sie bitte aufdas Aufgabenblatt.

We will not answer any content-related questions du-ring the exam. Please write comments referring to thetasks on the exam sheets.

Question: 1 2 3 4 5 6 Total

Points: 10 7 10 8 7 7 49

Score:

Page 2: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 2/20 Prufung 7.8.2017

Generelle Anmerkung / General Remark

Verwenden Sie die Notation, Algorithmen undDatenstrukturen aus der Vorlesung. Falls Sieandere Methoden verwenden, mussen Sie die-se kurz so erklaren, dass Ihre Ergebnisse nach-vollziehbar sind.

Use notation, algorithms and data struc-tures from the course. If you use differentmethods, you need to explain them suchthat your results are reproducible.

Aufgabe 1: Verschiedenes (10P)

1) In dieser Aufgabe sollen nur Ergebnisse an-gegeben werden. Sie konnen sie direkt beiden Einzelteilen notieren.

In this task only results have to be pro-vided. You can note them down in theparts.

2) Als Ordnung verwenden wir fur Buchsta-ben die alphabetische Reihenfolge, fur Zah-len die aufsteigende Anordnung gemass ih-rer Grosse.

As the order of characters we take thelexicographic order and for numbers wetake the increasing order according totheir sizes.

(a)/1P Gegeben seinen Daten der Lange n. Wie vie-le der folgenden Operationen fuhrt der Algo-rithmus Sortieren durch Auswahl im schlech-testen Fall durch?

Given data with length n. How many ofthe following operations are executed bythe algorithm Selection Sort in the worstcase?

Anzahl Vergleiche/Number Comparisons : © Θ(n) © Θ(n log n) © Θ(n2)

Anzahl Vertauschungen/Number Swaps : © Θ(n) © Θ(n log n) © Θ(n2)

(b)/1P Fuhren Sie auf dem folgenden Array zweiweitere Iterationen des Algorithmus Quick-sort aus. Als Pivot wird jeweils das erste Ele-ment des (Sub-)Arrays genommen.

Execute two further iterations of the al-gorithm Quicksort on the following array.The first element of the (sub-)array ser-ves as the pivot.

8 7 10 15 3 6 9 5 2 132 7 5 6 3 8 9 15 10 13

Page 3: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 3/20 Prufung 7.8.2017

(c) /1PIm folgenden ist eine Hashtabelle dargestellt.Es wird offenes Hashing mit der Hashfunk-tion h(k) = k mod 11 verwendet. Kolli-sionen werden mit linearem Sondieren auf-gelost. Die Sondierung lauft immer nachlinks. Vervollstandigen Sie die angegebeneEinfugereihenfolge so, dass die Belegung ent-steht, wenn man mit einer zu Anfang lee-ren Hashtabelle startet. Wie viele Kollisionensind insgesamt aufgetreten?

In the following a hash table is displayed.We use open hashing with the hash func-tion h(k) = h mod 11. Collisions are re-solved using linear probing. Probing al-ways goes left. Complete the given in-sertion order such that the hash table asgiven would be produced from an initial-ly empty hash table. How many collisionstook place overal?

0 1 2 3 4 5 6 7 8 9 10

3 516 29718

Einfugereihenfolge/Insertion Order: 3, 5, 16,

Anzahl Kollisionen/Number collisions: © 3 © 4 © 5 © 6 © 7

(d) /1PGegeben sind acht Buchstaben mit re-lativer Haufigkeit (Anzahl Zugriffe) wiefolgt. Erstellen Sie mit Hilfe des Huffman-Algorithmus einen optimalen Codierungs-baum. Tragen Sie den resultierenden Codein der Tabelle ein.

Eight characters (keys) with relative fre-quency (number accesses) are given asfollows. Using the Huffman algorithmprovide an optimal code tree. Enter thecorresponding code into the table.

char a b c d e ffreq 5 6 31 33 7 8Code

Page 4: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 4/20 Prufung 7.8.2017

(e)/1P Markieren Sie im Graphen unten die Kanteneines minimalen Spannbaums.

In the graph below mark the edges of aMinimum Spanning Tree.

7

2

6

3

1

3

5

6

1

4

1

4

1

7

3

5

Gegeben seien nun folgende Daten, eine Se-quenz von Zahlen

Now consider the following data, a se-quence of numbers.

1, 3, 4, 2, 6, 5, 7

Vervollstandigen Sie folgende Figuren, sodass sie deutlich machen, wie die jeweiligeDatenstruktur – wie in Vorlesung und Ubun-gen gezeigt – aussieht, wenn die Werte inobiger Reihenfolge (von links nach rechts)eingefugt werden.

Complete the following figures such thatthey illustrate the respective data struc-tures – as presented in lectures and exer-cises – after insertion of the given datain the order above (from left to right).

(f)/1P Binarer (unbalancierter) Suchbaum Binary (unbalanced) search tree

root

Page 5: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 5/20 Prufung 7.8.2017

(g) /1PMax-Heap (als Baum reprasentiert). Tipp:zeichnen Sie sich Zwischenschritte auf.

Max-Heap (represented as Tree). Hint:draw intermediate steps.

root

(h) /1PAVL-Baum. Zeichnen Sie den Baum nach je-der Balancierung neu.

AVL-Tree. Draw a new tree after eachbalancing.

Page 6: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 6/20 Prufung 7.8.2017

(i)/1P Betrachten Sie einen binaren Suchbaum alsgerichteten Graph. Kreuzen Sie an, was imallgemeinen stimmt.

Consider a binary search tree as a direc-ted graph. Mark what is generally cor-rect.

©Die Traversierung in Hauptreihenfolgeist eine Breitensuche

The preorder traversal is a breadthfirst search

©Die Traversierung in Hauptreihenfolgeist eine Tiefensuche

The preorder traversal is a depth firstsearch

©Die Traversierung in Nebenreihenfolgeist eine Breitensuche

The postorder traversal is a breadthfirst search

©Die Traversierung in symmetrischerReinhenfolge ist eine Tiefensuche

The In-order traversal is a depth firstsearch

(j)/1P Ein Compiler muss eine grosse Menge Sym-bole (Zeichenketten) verwalten. Es mussmoglich sein, wahrend der Kompilation vieleNamen neu einzutragen und effizient danachzu suchen. Loschen steht nicht im Vorder-grund. Welche Datenstruktur schlagen Siefur die Verwaltung der Symbole vor?

A compiler has to manage a large numberof symbols (strings). It has to be possibleto add a lot of names during compilationand to search for a symbol efficiently. De-letion is not of importance. Which datastructure do you propose to use for themanagement of the symbols?

.

Aufgabe 2: Asymptotik (7P)

(a)/1P Geben Sie fur die untenstehenden Funktio-nen eine Reihenfolge an, so dass folgendesgilt: Wenn eine Funktion f links von einerFunktion g steht, dann gilt f ∈ O(g).Beispiel: die drei Funktionen n3, n5 und n7

sind bereits in der entsprechenden Reihenfol-ge, da n3 ∈ O(n5) und n5 ∈ O(n7).

Provide an order for the following func-tions such that the following holds: If afunction f is left of a function g then itholds that f ∈ O(g). Example: the func-tions n3, n5 and n7 are already in the re-spective order because n3 ∈ O(n5) andn5 ∈ O(n7).

√n log n, n log

√n, 1/n, log(

n∑i=1

i), n!, nn

Page 7: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 7/20 Prufung 7.8.2017

(b) /3PGegeben Sei die folgende Rekursionsglei-chung:

Consider the following recursion:

T (n) =

3 · T (n− 1) + 2n, n > 01 n = 0

Geben Sie eine geschlossene (nicht rekursi-ve), einfache Formel fur T (n) an und bewei-sen Sie diese mittels vollstandiger Induktion.Hinweis:Fur q 6= 1 gilt ∑k

i=0 qi = qk+1−1q−1 .

Provide a closed (non-recursive), simpleformula for T (n) and prove it using ma-thematical induction.Hint:For q 6= 1 it holds that ∑k

i=0 qi = qk+1−1q−1 .

Page 8: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 8/20 Prufung 7.8.2017

In den folgenden Aufgabenteilen wird jeweilsangenommen, dass die Funktion g mit g(n)aufgerufen wird. Geben Sie jeweils die asym-ptotische Anzahl von Aufrufen der Funkti-on f() in Abhangigkeit von n ∈ N mit Θ-Notation moglichst knapp an. Die Funktionf ruft sich nicht selbst auf. Sie mussen IhreAntworten nicht begrunden.

In the following parts of this task we assu-me that the function g is called as g(n).Provide the asymptotic number of callsof f() as a function of n ∈ N using Θnotation as tight as possible. The functi-on f does not call itself. You do not haveto justify your answers.

(c)/1P

void g(int n){for (int i = 1; i<n ; i*=2 )

f()}

Anzahl Aufrufe von f / Number Calls of f

(d)/1P

void g(int n){if (n > 0){

g(n-1);}f();

}

Anzahl Aufrufe von f / Number Calls of f

(e)/1P

void g(int n){if (n > 0){

g(n-1);g(n-1);

}else{

f();}

}

Anzahl Aufrufe von f / Number Calls of f

Page 9: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 9/20 Prufung 7.8.2017

Page 10: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 10/20 Prufung 7.8.2017

Aufgabe 3: Dynamic Programming (10P)

Es soll eine Stromleitung von einem bestehen-den Startmast S zu einem bestehenden End-mast E mit Abstand n km durch unwegsamesGelande verlegt werden. Kosten verursachenzum einen das Aufstellen der Stromleitungs-masten und zum anderen das Verbinden mitStromkabeln.Eine Firma A bietet Ihnen an, Leitungsmastenaufzustellen. Sie gibt Ihnen zu Punkten, wel-che sich aquidistant mit jeweils 1 km Abstandzwischen S und E befinden, jeweils die Kostenmi (0 < i < n) fur das Aufstellen eines Mastsan. Die Kosten variieren wegen des unwegsa-men Gelandes.Eine andere Firma B bietet Ihnen an, zwi-schen den Leitungsmasten Drahte zu span-nen. Die Kosten sind jedoch (nichtlinear) vomAbstand der zu verbindenden Leitungsma-sten abhangig. Es ist nun Ihre Aufgabe, ei-ne moglichst gunstige Konstellation von Lei-tungsmasten zu finden.Nachfolgend finden Sie eine Beispieltabellemit Angeboten.

A power cable from some existing powermast S to an existing end mast E with adistance of n km shall be installed in roughterrain. The costs are determined by theinstallation of the power masts and by theconnection with power cables.A company A offers to install the powermasts. For the installation of a powermast, to given points that are placed equi-distantly with a distance of 1 km each bet-ween S and E the company quotes a pricemi (0 < i < n). The costs vary becauseof the rough terrain.A different company B offers to installpower cables between the masts. Howe-ver, the costs depend (in a non-linear fa-shion) on the distance of the masts to beconnected. Now, it is your task to find thecheapest constellation of power masts.Below you see an example table with thecompany’s offers.

Firma / Company AMast / mast M0 = S M1 M2 M3 M4 M5 M6 = EPunkt bei km / Point at km 0 1 2 3 4 5 6Kosten / costs m 0 4 3 4 2 4 0Firma / Company BAbstand / distance d (km) 1 2 3 4 5 6 7Kosten / costs ld 1 4 9 16 25 36 49

Beispiel: eine Verlegung mit Masten an denPunkten 2, 3 und 5 kostet 4 + 3 + 4 = 11 furdie Masten plus 4 + 1 + 4 + 1 = 10 fur dieKabel (von 0 nach 2, 2 nach 3, 3 nach 5 und5 nach 6), also insgesamt 21.

Example: an installation of masts at thepoints 2, 3 and 5 causes costs 4 + 3 + 4 =11 for the masts plus 4 + 1 + 4 + 1 = 10for the cables (from 0 to 2, 2 to 3, 3 to 5,and 5 to 6), thus overal costs of 21.

Geben Sie einen Algorithmus an, der nach demPrinzip der dynamischen Programmierung ar-beitet und die kleinstmoglichen Kosten (wieoben beschrieben) berechnet. Gehen Sie in Ih-rer Losung auf die folgenden Aspekte ein.(Der triviale Algorithmus, der alle Losungenaufzahlt, ergibt keine Punkte.)

Provide a dynamic programming algo-rithm for computing the minimum cost(as described above). Address the followi-ng aspects in your solution.(The trivial algorithm that simply enume-rates all possible solutions does not giveany points.)

Page 11: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 11/20 Prufung 7.8.2017

(a) /4P(I)Was ist die Bedeutung eines Tabellenein-trags, und welche Grosse hat die DP-TabelleT ?

What is the meaning of a table entry andwhat is the size of the DP-table T ?

Tabellengrosse / table size:

Bedeutung Eintrag / entry meaning:

(II)Wie berechnet sich ein Eintrag der Tabelleaus den vorher berechneten Eintragen?

How can an entry be computed from thevalues of previously computed entries?

(III)In welcher Reihenfolge konnen die Eintrageberechnet werden?

In which order can the entries be compu-ted?

(IV) Wie kann der Wert des minimalen Preisesaus der Tabelle erhalten werden?

How can the value of the minimum pricebe obtained from the DP table?

Page 12: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 12/20 Prufung 7.8.2017

(b)/3P Zusatzlich zu den optimalen Kosten wollenSie nun auch angeben, an welchen Orten dieMasten aufgestellt werden sollen. Beschrei-ben Sie detailiert, wie Sie das bewerkstelli-gen.

In addition to the optimal costs you nowwant to provide the locations of themasts. Describe in detail how you can de-termine this.

(c)/1P Geben Sie nun eine gunstigste Verlegung furobiges Beispielszenario an. An welchen Ortenwurden Sie Masten aufstellen und wieviel ko-stet das?

Provide an optimal setup for the examplescenario above. Where would you placemasts and what are the costs?

(d)/2P Geben Sie die Laufzeiten fur die Berechnungder optimalen Kosten und die Berechnungder Orte in Θ-Notation moglichst knapp mitBegrundung an.

Provide the run-times for the computati-on of the optimal costs and the compu-tation of the placements in Θ notation astight as possible with short explanation.

Page 13: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 13/20 Prufung 7.8.2017

Aufgabe 4. (8P)

Gegeben sei ein bergiges Wandergebiet mitn interessanten Zielpunkten pi(1 ≤ i ≤ n)welche jeweils auf Hohen h(pi) ∈ R(1 ≤i ≤ n) liegen. Ausserdem gibt es eine MengeW ⊂ {{pi, pj}, 1 ≤ i, j ≤ n} von moglichenWanderwegen zwischen den Punkten. Jederinteressante Punkt ist mit maximal funf We-gen erreichbar. Ein Wanderer mochte von p1nach pn wandern. Er mochte moglichst weni-ge Hohenmeter durchlaufen, sucht also nacheinem Weg (pij

), 1 ≤ j ≤ n mit minimalerSumme ∑k−1

j=1 |h(pij)− h(pij+1)|.

Consider a hiking region in the mountainswith n interesting destinations pi(1 ≤ i ≤n) that are located at heights h(pi) ∈R(1 ≤ i ≤ n). Moreover, there is a setW ⊂ {{pi, pj}, 1 ≤ i, j ≤ n} of possi-ble paths between the destination pointsgiven. Every destination can be reachedwith a maximum of 5 different paths.A wanderer wants to hike from p1 topn. He wants to climb and descend aslittle as possible, thus he searches for apath (pij

), 1 ≤ j ≤ n with minimal sum∑k−1j=1 |h(pij

)− h(pij+1)|.

p1450

p21500

p31200

p4−200

p5900

p6800

p7500

(a) /3PGeben Sie den verwendeten Graph und einenmoglichst effizienten Algorithmus zur Be-stimmung eines gewunschten Weges an. Ge-ben Sie die Laufzeit Ihres Algorithmus (imschlechtesten Fall) in Abhangigkeit von derAnzahl n der interessanten Punkte an.

Provide the used graph and an efficientalgorithm for the determination of thebest possible path. Provide asymptoticrunning time of your algorithm (in theworst case) depending on the number nof destinations.

Page 14: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 14/20 Prufung 7.8.2017

(b)/3P Da das Wandergebiet sehr beliebt ist, stehenam Punkt p1 immerzu beliebig viele Wande-rer zur Wanderung bereit und laufen nach pn.Die durchlaufene Hohe spielt nun keine Rollemehr. Ein findiger Busunternehmer mochtegenugend Busse zum Abholen der Wande-rer am Punkt pn bereitstellen. Zu jedemWegstuck zwischen zwei interessanten Punk-ten kennt er die maximale Anzahl Wanderer,die den Weg pro Stunde durchlaufen konnen.Wie kann der Busunternehmer herausfinden,wie viele Wanderer beim Punkt pn maximalpro Stunde abgeholt werden mussen?Geben Sie auch hier die Laufzeit des Algo-rithmus in Abhangigkeit von der Anzahl in-teressanter Punkte n an.

Because the hiking area is very popular,at point p1 there are always wanderer rea-dy to start their hiking tour to pn. Thealtitude difference is not of importance. Abus tour operator want to provide enoughbusses to pick up the wanderer at pointpn. For each way between two destina-tions the operator knows the maximalnumber of wanderers that can pass perhour. How can the bus operator find outhow many wanderers have to be pickedup at point pn maximally per hour?Again provide the asymptotic runtime ofthe algorithm depending on the numberof destinations n.

(c)/2P Ein Wanderer zeichnet die Hohendaten ei-ner sehr langen Tour im Minutentakt auf.Hinterher mochte er den anstrengendstenTeil seiner Wanderung anzeichnen und suchtdafur den zusammenhangenden Teil derStrecke, in dem er am meisten Hohenmeterzuruckgelegt hat. Der Teil der Strecke kannauch Gefalle enthalten, welches mit entspre-chend negativer Steigung aber auch im Ge-gensatz zu (a) oben negativ zahlt.Geben Sie einen Algorithmus an, mitdem man den zusammenhangenden Teilder Strecke mit den meisten Hohenmeternmoglichst effizient bestimmen kann. Wieviele Schritte macht der Algorithmus inAbhangigkeit von der Anzahl Datenpunktem?

A wanderer records the height data of avery long tour, one sample per minute.Afterwards he wants to mark the mostexhausting part of the tour and thereforeis looking for the contiguous part withthe largest (positive) height difference.The part can contain descending pieces,but in contrast to (a) above now they docount negative.Provide an algorithm that efficiently candetermine the piece of the tour withthe largest height difference. How manysteps does the algorithm require depen-ding on the number data points m?

Page 15: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 15/20 Prufung 7.8.2017

Aufgabe 5: Parallele Programmierung (7P)

(a) /1PAngenommen ein Programm sei zu 80% pa-rallelisierbar und erreiche auf mehreren Pro-zessorkernen einen Speedup von 3. Berech-nen Sie mit Hilfe von Amdahls Gesetz dieminimale Anzahl verwendeter Kerne.

Consider a program that is 80% paralle-lizable and reaches a speedup of a factorof 3 on multiple processor cores are used.Calculate the minimum number of usedprocessor cores using Amdahl’s law.

(b) /1PWie gross ist unter denselben Voraussetzun-gen (80% Parallelisierbarkeit) der maximalerreichbare Speedup mit beliebig vielen Pro-zessorkernen?

What is the maximum possible speedupunder the same conditions (80% paral-lelizability) with an unlimited number ofprocessor cores?

(c) /2PGeben Sie fur folgenden Taskgraphen eineobere Schranke an fur die Ausfuhrungszeitbei Einsatz von beliebig vielen Prozessor-kernen und bei drei Kernen unter Verwen-dung eines beliebigen gierigen Schedulers.Die Zahlen in den Knoten bezeichnen die je-weilige Ausfuhrungszeit in Nanosekunden.

For the following task graph provide anupper bound for the execution time whenan unlimited number of processor cores isused and the execution time when threecores are used and an arbitrary greedyscheduler is employed. The number in thenodes provide execution time in nanose-conds.

1

3 2 4

3 2 3 2

3 2

5

T∞ = T3 ≤

Page 16: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 16/20 Prufung 7.8.2017

Das Programm auf der nachsten Seite wirdmit einem optimierenden Compiler kompi-liert und auf moderner Hardware ausgefuhrt.

The program on the next page is com-piled with an optimizing compiler and isexecuted on modern hardware.

(d)/1P Auf ein und demselben System wird manch-mal “cold and dry”, manchmal “warm andwet” und manchmal “warm and dry” ausge-geben. Wie nennt man dieses Verhalten undwarum tritt es auf?

On the same system, sometimes you seethe output “cold and dry”, sometimes“‘warm and wet” and sometimes “warmand dry”. How ist this behavior called andwhy does it happen?

(e)/1P Auf einem anderen System bleibt die Funk-tion report sogar in einer Endlosschlei-fe hangen, haben Sie auch dafur eine Er-klarung?

On a different system the functionreport is even blocked in an endlessloop. Can you explain this?

(f)/1P Beschreiben Sie ganz kurz / stichwort-artig, wie Sie das Verhalten der KlasseWeather unter Beibehaltung ihrer beabsich-tigten Funktionalitat und Verwendung meh-rerer Threads deterministisch machen.

Describe, very shortly / in note form,how you would render the behavior of theclass Weather deterministic such that itprovides the intended functionality whenmultiple threads are used.

Page 17: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 17/20 Prufung 7.8.2017

#include <iostream>#include <thread>

class Weather{int temp = 0;int rain = 0;bool data = false;

public:

// report the current weather data in words// as soon as data are availablevoid report(){

while (!data);if (temp < 20)

std::cout << "cold and ";else

std::cout << "warm and ";if (rain > 0)

std::cout << "wet";else

std::cout << "dry";}

// provide weather datavoid update(int t, int r){

data = true;temp = t;rain = r;

}};

int main(){

Weather w;std::thread t1([&]{w.report();});std::thread t2([&]{w.update(20,10);});t2.join(); t1.join();return 0;

}

Page 18: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 18/20 Prufung 7.8.2017

Aufgabe 6: Parallele Programmierung (7P)

Eine Verkehrssimulation enthalt eine Mengevon Objekten, die eigenstandig (als Threadsimplementiert) agieren. Darunter auch Autosund Kinder. Nun soll ein Zebrastreifen zur Si-mulation hinzugenommen werden, mit folgen-der Semantik:

(A) Zu jeder Zeit konnen maximal zwei Autosden Zebrastreifen befahren.

(B) Zu jeder Zeit konnen bis zu 20 Kinder denZebrastreifen betreten.

(C) Zu keiner Zeit konnen Autos und Kindergemeinsam auf dem Zebrastreifen sein.

Wir setzen voraus, dass Autos und Kinder so-fort anhalten (konnen), wenn die Strasse be-legt ist.

A traffic simulation comprises a set of ob-jects that act autonomously (implementedas threads). Amongst such objects thereare cars and children. Now a zebra crossingshall be implemented providing the follo-wing semantics:

(A) At each point in time a maximal num-ber of two cars can be on the zebracrossing.

(B) At each point in time a number of atmost 20 children can be on the zebracrossing.

(C) At no point in time cars and childrencan be on the zebra crossing together.

For simplicity we assume that childrenand cars (can) stop immediately when thecrossing is already occupied.

(a)/4P Vervollstandigen Sie nachfolgenden Code so,dass obige Semantik implementiert wird. DieAutos und Kinder betreten und verlassenden Zebrastreifen jeweils mit den Funktionencar_enter, kid_enter, car_leave undkid_leave der Klasse Zebra. Es ist nichtgefordert, dass Ihre Implementation die Au-tos den Zebrastreifen in der Reihenfolge ih-rer Ankunft passieren lassen. Ebenso gibt es(noch) keine Vorrangregeln.

Complement the following code suchthat the semantics from above areimplemented. Cars and children enterand leave the zebra crossing callingthe functions car_enter, kid_enter,car_leave und kid_leave of the classZebra, respectively. It is not requiredthat cars pass the zebra crossing in theorder of their arrival. Moreover, there areno priority rules (yet).

// includes and shortcuts on this page in order to save space

#include <mutex> // for std::mutex and std::unique_lock#include <condition_variable> // for std::condition_variable

using unique_lock = std::unique_lock<std::mutex>;

// program continues on the right hand side

Page 19: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 19/20 Prufung 7.8.2017

class Zebra{private:int kids = 0;int cars = 0;

public:void car_enter(){

}void car_leave(){

}void kid_enter(){

}void kid_leave(){

}}

Page 20: Datenstrukturen und Algorithmen (D-MATH RW)...Datenstrukturen und Algorithmen 2/20 Pr¨ufung 7.8.2017 Generelle Anmerkung / General Remark Verwenden Sie die Notation, Algorithmen und

Datenstrukturen und Algorithmen 20/20 Prufung 7.8.2017

(b)/3P Es wird nun eine Vorrangregel eingefuhrt:Kinder mussen nie auf Autos warten (wel-che nicht bereits auf dem Zebrastreifen sind).Wie implementieren sie das genau?

Now a priority rule is introduced: Child-ren may not have to wait for cars (thatare not already on the zebra crossing).How exactly do you implement this?