Algorithms & Data Structures Homework 8 HS 18 Exercise Class (Room & TA): Submitted by: Peer Feedback by: Points:

Similar documents
Data Structures (INE2011)

1 PYTHAGORAS THEOREM 1. Given a right angled triangle, the square of the hypotenuse is equal to the sum of the squares of the other two sides.

22: Union Find. CS 473u - Algorithms - Spring April 14, We want to maintain a collection of sets, under the operations of:

Chapter 4 State-Space Planning

Counting Paths Between Vertices. Isomorphism of Graphs. Isomorphism of Graphs. Isomorphism of Graphs. Isomorphism of Graphs. Isomorphism of Graphs

Linear Algebra Introduction

Technische Universität München Winter term 2009/10 I7 Prof. J. Esparza / J. Křetínský / M. Luttenberger 11. Februar Solution

Global alignment. Genome Rearrangements Finding preserved genes. Lecture 18

5. Every rational number have either terminating or repeating (recurring) decimal representation.

Discrete Structures, Test 2 Monday, March 28, 2016 SOLUTIONS, VERSION α

Section 1.3 Triangles

Solutions for HW9. Bipartite: put the red vertices in V 1 and the black in V 2. Not bipartite!

Welcome. Balanced search trees. Balanced Search Trees. Inge Li Gørtz

Lecture 3. In this lecture, we will discuss algorithms for solving systems of linear equations.

CS 360 Exam 2 Fall 2014 Name

12.4 Similarity in Right Triangles

Intermediate Math Circles Wednesday 17 October 2012 Geometry II: Side Lengths

QUADRATIC EQUATION. Contents

CISC 320 Introduction to Algorithms Spring 2014

Computational Biology Lecture 18: Genome rearrangements, finding maximal matches Saad Mneimneh

Project 6: Minigoals Towards Simplifying and Rewriting Expressions

p-adic Egyptian Fractions

A Lower Bound for the Length of a Partial Transversal in a Latin Square, Revised Version

I1 = I2 I1 = I2 + I3 I1 + I2 = I3 + I4 I 3

Lecture 6: Coding theory

NON-DETERMINISTIC FSA

System Validation (IN4387) November 2, 2012, 14:00-17:00

Lecture 3: Equivalence Relations

Introduction to Olympiad Inequalities

CS241 Week 6 Tutorial Solutions

Exercise sheet 6: Solutions

Designing Information Devices and Systems I Spring 2018 Homework 7

CS 491G Combinatorial Optimization Lecture Notes

AVL Trees. D Oisín Kidney. August 2, 2018

Matrices SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics (c) 1. Definition of a Matrix

The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, SPRING SEMESTER MACHINES AND THEIR LANGUAGES ANSWERS

Fast index for approximate string matching

Algorithm Design and Analysis

Tutorial Worksheet. 1. Find all solutions to the linear system by following the given steps. x + 2y + 3z = 2 2x + 3y + z = 4.

CS 275 Automata and Formal Language Theory

(a) A partition P of [a, b] is a finite subset of [a, b] containing a and b. If Q is another partition and P Q, then Q is a refinement of P.

, g. Exercise 1. Generator polynomials of a convolutional code, given in binary form, are g. Solution 1.

Spacetime and the Quantum World Questions Fall 2010

PYTHAGORAS THEOREM WHAT S IN CHAPTER 1? IN THIS CHAPTER YOU WILL:

Algorithm Design and Analysis

2.4 Linear Inequalities and Interval Notation

CSE 332. Sorting. Data Abstractions. CSE 332: Data Abstractions. QuickSort Cutoff 1. Where We Are 2. Bounding The MAXIMUM Problem 4

Discrete Structures Lecture 11

GM1 Consolidation Worksheet

Probability. b a b. a b 32.

Instructions. An 8.5 x 11 Cheat Sheet may also be used as an aid for this test. MUST be original handwriting.

Part I: Study the theorem statement.

CS 573 Automata Theory and Formal Languages

Computing data with spreadsheets. Enter the following into the corresponding cells: A1: n B1: triangle C1: sqrt

Lecture Notes No. 10

Suffix Trays and Suffix Trists: Structures for Faster Text Indexing

THE PYTHAGOREAN THEOREM

Coalgebra, Lecture 15: Equations for Deterministic Automata

Arrow s Impossibility Theorem

Mid-Term Examination - Spring 2014 Mathematical Programming with Applications to Economics Total Score: 45; Time: 3 hours

Intermediate Math Circles Wednesday, November 14, 2018 Finite Automata II. Nickolas Rollick a b b. a b 4

8 THREE PHASE A.C. CIRCUITS

T b a(f) [f ] +. P b a(f) = Conclude that if f is in AC then it is the difference of two monotone absolutely continuous functions.

6.5 Improper integrals

MAT 403 NOTES 4. f + f =

Finite State Automata and Determinisation

The Word Problem in Quandles

TOPIC: LINEAR ALGEBRA MATRICES

PAIR OF LINEAR EQUATIONS IN TWO VARIABLES

Generalization of 2-Corner Frequency Source Models Used in SMSIM

Part 4. Integration (with Proofs)

CS 2204 DIGITAL LOGIC & STATE MACHINE DESIGN SPRING 2014

CS 330 Formal Methods and Models Dana Richards, George Mason University, Spring 2016 Quiz Solutions

Symmetrical Components 1

Arrow s Impossibility Theorem

Connected-components. Summary of lecture 9. Algorithms and Data Structures Disjoint sets. Example: connected components in graphs

Nondeterministic Finite Automata

Green s Theorem. (2x e y ) da. (2x e y ) dx dy. x 2 xe y. (1 e y ) dy. y=1. = y e y. y=0. = 2 e

Chapter 8 Roots and Radicals

CS311 Computational Structures Regular Languages and Regular Grammars. Lecture 6

Polynomials. Polynomials. Curriculum Ready ACMNA:

Activities. 4.1 Pythagoras' Theorem 4.2 Spirals 4.3 Clinometers 4.4 Radar 4.5 Posting Parcels 4.6 Interlocking Pipes 4.7 Sine Rule Notes and Solutions

Algebra Basics. Algebra Basics. Curriculum Ready ACMNA: 133, 175, 176, 177, 179.

ILLUSTRATING THE EXTENSION OF A SPECIAL PROPERTY OF CUBIC POLYNOMIALS TO NTH DEGREE POLYNOMIALS

Numbers and indices. 1.1 Fractions. GCSE C Example 1. Handy hint. Key point

for all x in [a,b], then the area of the region bounded by the graphs of f and g and the vertical lines x = a and x = b is b [ ( ) ( )] A= f x g x dx

Trigonometry Revision Sheet Q5 of Paper 2

Lecture 08: Feb. 08, 2019

Parse trees, ambiguity, and Chomsky normal form

Expand the Shares Together: Envy-free Mechanisms with a Small Number of Cuts

Torsion in Groups of Integral Triangles

Lesson 2: The Pythagorean Theorem and Similar Triangles. A Brief Review of the Pythagorean Theorem.

Farey Fractions. Rickard Fernström. U.U.D.M. Project Report 2017:24. Department of Mathematics Uppsala University

where the box contains a finite number of gates from the given collection. Examples of gates that are commonly used are the following: a b

Assignment 1 Automata, Languages, and Computability. 1 Finite State Automata and Regular Languages

Lecture 3. XML Into RDBMS. XML and Databases. Memory Representations. Memory Representations. Traversals and Pre/Post-Encoding. Memory Representations

Exercise 3 Logic Control

The Regulated and Riemann Integrals

MATH FIELD DAY Contestants Insructions Team Essay. 1. Your team has forty minutes to answer this set of questions.

Section 6: Area, Volume, and Average Value

Transcription:

Eidgenössishe Tehnishe Hohshule Zürih Eole polytehnique fédérle de Zurih Politenio federle di Zurigo Federl Institute of Tehnology t Zurih Deprtement of Computer Siene. Novemer 0 Mrkus Püshel, Dvid Steurer Algorithms & Dt Strutures Homework HS Exerise Clss (Room & TA): Sumitted y: Peer Feedk y: Points: Exerise. Serh Trees.. Drw the resulting tree when the keys,,7,,,,, in this order re inserted into n initilly empty nturl serh tree. 7. Delete key in the ove tree, nd fterwrds key 7 in the resulting tree. Key hs one hild, so it n just e repled y :

7 Key 7 must either e repled y its suessor key,, or its preesessor key,. If key 7 is repled y its suessor: If key 7 is insted repled y its predeessor:. Drw the resulting tree when the keys re inserted into n initilly empty AVL tree. Insert nd then :

Insert 7: Rotte left. Pivot = 7 7 Insert nd then : 7 Rotte left. Pivot = Rotte right. Pivot = 7 7 Insert : Rotte left. Pivot = 7 7 Insert nd :

7. Delete key 7 in the ove tree, nd fterwrds key in the resulting tree. Delete 7: Delete : Rotte right. Pivot = Exerise. Tree Trversls. There re three essentil wys to trverse inry trees. The first one is Preorder(T ), whih t first visits the root v, then T l (v) nd then T r (v), where T l (v) is the left sutree of v nd T r (v) is the right sutree of v. The seond one is Postorder(T ), whih t first visits T l (v), then T r (v) nd then v. The third one is Inorder(T ), whih t first visits T l (v), then v nd then T r (v). In eh se the left nd right sutrees re visited reursively in the sme order.

. Consider this pseudoode for the Preorder proedure: Algorithm : Preorder(T ) if T is non-empty then v Root(T ); Visit(v); Preorder(T l (v)); Preorder(T r (v)); end Write pseudoodes for Postorder nd Inorder proedures. Algorithm : Postorder(T ) if T is non-empty then v Root(T ); Postorder(T l (v)); Postorder(T r (v)); Visit(v); end Algorithm : Inorder(T ) if T is non-empty then v Root(T ); Inorder(T l (v)); Visit(v); Inorder(T r (v)); end. For the ove serh trees in.. nd.. give the Preorder, the Postorder, the Inorder of the nodes. For the tree in..: Preorder:,,, 7,,,,. Postorder:,,,,, 7,,. Inorder:,,,,,, 7,. For the tree in..: Preorder:,,,,, 7,,. Postorder:,,,,,, 7,. Inorder:,,,,,, 7,.. Drw the inry tree with keys,,,,,, 7, suh tht the Preorder strts with,,, 7 nd the Postorder ends with,, 7,.

7 Exerise. Advned Serh Trees ( Point). In this exerise, we wish to extend the funtionlity of serh tree. We onsider inry serh tree over integers. In ddition to finding numer, we wnt to e le to nswer the following questions:. How mny elements in the tree re multiples of nd greter thn given numer k?. How mny elements in the tree re multiples of nd (stritly) etween two given numers k nd k, with k < k? Disuss how you n modify the tree so tht you n nswer these questions effiiently. Desrie how the insertion nd the removl opertion must e hnged ordingly. Inlude disussion of the running times of the modified lgorithms. Solution In ddition to the vlue of the key, we store t eh node v of the tree the numer g v of elements tht re multiples of nd re in the right sutree of v. When sked for the numer of elements tht re multiples of nd greter thn k, we look for the element k in the tree. Every time we go to the left sutree of node v (in the se where k is smller thn the key in v), we inrement ounter y g v (initilly the ounter is zero), or y g v + if v is multiple of nd greter thn k. If we go to the right sutree, we keep the ounter unhnged. If we find k in node v, then we dd one lst time g v to the ounter. Otherwise, we end up in lef v of the tree. Then, if the key of v is smller or equl to k, the ounter is lredy set to the orret numer. Otherwise, we inrese the ounter y one if the key in v is multiple of. To nswer how mny numers re multiple of nd etween k nd k in the tree, we need to determine only the vlues L, L of elements tht re multiple of nd lrger thn k nd k respetively. We hve just seen how to find these vlues. Sutrting L from L, we otin how mny suh numers x suh tht k < x k re in the tree. If k exists in the tree nd is multiple of, we thus hve to remove one from this numer. We n esily hek for this se when omputing L. The insertion of n element i works s follows. We first serh for i. If it is lredy in the tree, we do nothing. If i is not multiple of, we insert it in the lef where the serh ended nd we set g i 0. If i is multiple of, we dditionlly trverse the tree gin (i.e., serh for i gin) nd whenever we meet node v ontining smller key (i.e., we turn right ), we inrese g v y one sine i is inserted in its right sutree. The removl of n element i works s follows. Agin, we first serh for i. If it is not in the tree, we do nothing. Otherwise we ontinue in i to find its symmetril predeessor n. We will lter reple i y n. First, we need to updte ll ounters. If i is multiple of, we trverse the tree gin from the root to i (i.e., serh for i), nd whenever we turn right in node v, we derement the vlue g v. Similrly,

if n is multiple of, we derement the ounters on the pth from i to n t every right turn. Due to the properties of the symmetri predeessor, it holds tht g n = 0. We now set n in the old position of i. Furthermore, we set g n g i, sine n ws originlly in the left sutree of i. All new tree opertions require n dditionl effort tht is onstnt in every visited node, therefore there is no impt on the symptoti running time of Insert, Serh nd Remove. Exerise. Mximum Depth Differene of two Leves. Consider n AVL tree of height h. Wht is the mximum possile differene of the depths of two leves? Imging whih struture suh trees need to hve, nd drw exmples of orresponding trees for every h {,, }. Derive reursive formul (depending on h), solve it nd use indution to prove the orretness of your solution. Provide detiled explntion of your onsidertions. Note: For the proof the priniple of omplete indution n e used. Let A(n) e sttement for numer n N. If, for every n N, the vlidity of ll sttements A(m) for m {,..., n } implies the vlidity of A(n), then A(n) is true for every n N. ( n N : ( m {,..., n } : A(m) ) ) A(n) n N : A(n). () Thus, omplete indution llows multiple se ses nd indutive hypotheses. For n AVL-tree T with root node v nd height h, we n distinguish the following ses: Both su-trees T l (v) nd T r (v) hve height h T l (v) hs height h nd T r (v) hs height h, or T l (v) hs height h nd T r (v) hs height h As we re interested in the mximum depth differene of two leves, we n disregrd the first se, nd fous on su-trees tht hve heights tht differ y. Without loss of generlity, we n tke the seond se, ssuming tht the left su-tree will hve height of h, while the right su-tree will hve height of h. If the left su-tree is n AVL-tree of height h, then the right tree must e n AVL-tree of height h. This omes from the properties of n AVL tree, euse if t ny time they differ y more thn one, relning is done to restore this property. As result of this, the entire tree T will hve height of h nd s suh there will e lef on the left-sutree with this depth. The figure elow illustrtes the AVL trees of height h {,, }: In generl, we onsider trees with the following struture: 7

The left sutree T l (v) ontins lef of depth h (while T l (v) hs height of h ), the right sutree T r (v) ontins lef of depth h (while T r (v) hs height h ). The mximum possile differene of the depths of two leves in the tree (with height h) is therefore greter thn the mximum differene of the depths of two leves in the right sutree (with height h ). For h = nd h =, the mximum depth differene is extly. As result, we hve the following reursive formul for the mximum differene of the depths of two leves in tree of height h: D() =, D() =, D(h) = + D(h ) for ll h. () From the ove, we n ssume tht D(h) = h/. We prove this ssumption using indution over h. Bse se I (h = ): D() = = /. Bse se II (h = ): D() = = /. Indution hypothesis: Assume tht the property holds for some h: D(h ) = (h )/. Indutive step: ((h ) h): From the reursive definition of D(h), we hve: D(h) = + D(h ) = + (h )/ = + h/ = + h/ = h/. () Exerise. One-Column Cndy Crush ( Points.). Consider olumn of n ndies, nd ssume tht if three or more djent ndies in this olumn re equl, then these ndies n e removed, nd the olumn shrinks. Removing the ndies is done with the following tie reking rule: The ndies re removed from top to ottom, i.e., when there is more thn one group tht n e removed t the sme time, the upper group is removed first. We re interested in the numer of ndies tht n not e removed. You get this olumn of ndies stored on stk S, suh tht the first (topmost) ndy of the olumn is on the top of this stk. Rell tht the opertions on stk re top(), pop(), nd push(v) where v is ndy. Moreover, you n ess the numer of ndies in the stk. Assume tht ll these opertions require onstnt time. Your tsk is to design liner time lgorithm tht returns the numer of the remining ndies. Your lgorithm is llowed to use stk S plus one dditionl stk T, for whih you n ssume tht it is initilly empty. On top of tht, you re llowed to use only O() extr memory spe. Provide n nlysis of the tul running time of your lgorithm. We ssume tht n >, otherwise the nswer is trivil. We strt with n oservtion: whenever the topmost group of ndies e, e,..., e is removed from the olumn, then either this removl

T e S Figure : Exmple for the exeution of the lgorithm. leds to three or more other equl ndies e, e,..., e tht re now djent ut were split efore into two groups y the es, or the next topmost group to e removed is further down in the olumn. The ide of our lgorithm is s follows: Split the olumn into tree prts, S, e, nd T, where e is single ndy nd S nd T re stks. We will keep the following invrints: No group of ndies in T plus e n e removed The remining olumn is given y the ndies in T kwrds, e, nd the ndies in S forwrds S > 0 Initilly, the first ndy of S is popped into e. Then, intuitively the following step is repeted until S is empty.. Chek whether the top ndies in S nd T (if they exists) re oth equl to e.. If no, then e does not elong to the next group to remove. Therefore, push e to T nd pop the the top ndy of S into e.. If yes, then you hve found the topmost group of ndies to remove. Remove thus ll equl ndies on the top of T nd S. Reple the ndy in e with the top ndy of T, or if no suh ndy exists with the top ndy of S. When the lgorithm termintes, ll ndies tht nnot e removed re in T or e. Consider the pseudoode in Algorithm. An exmple is given in Figure. The running time of the lgorithm is s follows: in eh step (eh itertion in the outer while loop), the lgorithm does x pops from S (nd no pushes), nd onstnt numer of other opertions. So the totl numer of pops from S is n nd the numer of other opertions is O(#of steps) whih is lso t most n (sine when S = 0 the lgorithm termintes). Therefore, the running time of the lgorithm is in Θ(n). Sumission: On Mondy, 9..0, hnd in your solution to your TA efore the exerise lss strts. 9

Algorithm : One-Column_Cndy_Crush(S) e = S.pop(); while S > 0 do if ( T > 0 nd e == T.top() nd e == S.top()) then //Remove the mthing ndy from T (There n only e one!!! WHY?) T.pop(); //Remove the mthing ndies from S 7 while ( S > 0 nd S.top() == e) do S.pop(); 9 end 0 //Find new middle ndy e if ( T > 0) then e = T.pop(); else if ( S > 0) then e = S.pop(); else //Out of ndies 7 return 0; end 9 else 0 //e nnot e removed now, move it to T T.push(e); e = S.pop(); end end //No more ndies n e removed return + T ; 0