10/24/ Rotations. 2. // s left subtree s right subtree 3. if // link s parent to elseif == else 11. // put x on s left

Size: px
Start display at page:

Download "10/24/ Rotations. 2. // s left subtree s right subtree 3. if // link s parent to elseif == else 11. // put x on s left"

Transcription

1 13.2 Rotations MAT AA+DS, Fall Oct LEFT-ROTATE(, ) 1. // set 2. // s left subtree s right subtree 3. if // link s parent to 6. if == elseif == else 11. // put x on s left 12.. = MAT AA+DS, Fall Oct

2 13.3 Insertion RB-INSERT ) while if else 8. z. = 9. if == elseif else = RED 17.RB-INSERT-FIXUP(, ) MAT AA+DS, Fall Oct All instances of NIL in TREE-INSERT are replaced by 2. We set and to in lines of RB-INSERT, in order to maintain the proper tree structure 3. We color red in line Coloring red may cause a violation of one of the red-black properties, hence, we call RB-INSERT-FIXUP ) in line 17 to restore the red-black properties by recoloring nodes and performing rotations MAT AA+DS, Fall Oct

3 Which of the red-black properties might be violated upon the call to RB-INSERT-FIXUP? Property 1 certainly continues to hold, as does property 3, since both children of the newly inserted red node are the sentinel Property 5 (equal number of black nodes on every path) is satis ed as well, because node replaces the (black) sentinel, and node is red with sentinel children The only properties that might be violated are property 2 (the root is black) and property 4 (a red node cannot have a red child) Both possible violations are due to being colored red Property 2 is violated if is the root, and property 4 is violated if s parent is red MAT AA+DS, Fall Oct A node after insertion Both and are red, a violation of property 4 occurs Uncle is red We recolor nodes and move the pointer up the tree, resulting in the tree shown MAT AA+DS, Fall Oct

4 and its parent are both red, but s uncle is black is the right child of We perform a left rotation MAT AA+DS, Fall Oct Now, is the left child of its parent Recoloring and right rotation yield a legal redblack tree MAT AA+DS, Fall Oct

5 RB-INSERT-FIXUP ) 1. while == RED 2. if == if == RED // case 1 5. =BLACK 6. y =BLACK 7. = RED elseif == // case LEFT-ROTATE ) // case =BLACK 13. =RED 14. RIGHT-ROTATE ) 15. else (same as then clause with right and left exchanged) 16. = BLACK MAT AA+DS, Fall Oct The while loop in lines 1 15 maintains the following three-part invariant at the start of each iteration of the loop: a) Node is red. b) If is the root, then is black. c) If the tree violates any of the red-black properties, then it violates at most one of them, and the violation is of either property 2 or 4. If it violates property 2, then is the root and is red. If it violates property 4, then both and are red. MAT AA+DS, Fall Oct

6 Analysis The height of a RBT on nodes is (lg ) => lines 1 16 of RB-INSERT take (lg ) time In -FIXUP, the while loop repeats only in case 1, then the pointer moves two levels up The total number of times the while loop can be executed is (lg ) Thus, RB-INSERT takes a total of (lg ) time It never performs more than two rotations, the while loop terminates if case 2 or 3 is executed MAT AA+DS, Fall Oct Deletion First, we need to customize TRANSPLANT that TREE-DELETE calls so that it applies to a RBT: RB-TRANSPLANT ) 1. if == elseif == else 6.. =. MAT AA+DS, Fall Oct

7 RB-DELETE ) if == RB-TRANSPLANT ) 6. elseif == RB-TRANSPLANT 9. else =TREE-MINIMUM ) if == else RB-TRANSPLANT RB-TRANSPLANT ) if - - == BLACK 22. RB-DELETE-FIXUP ) MAT AA+DS, Fall Oct The main differences between RB-DELETE and TREE-DELETE: Line 1 sets to point to node when it has < 2 children and is therefore removed. When has two children, line 9 sets to point to s successor and will move into s position in the tree. Node s color might change, a variable stores s color before any changes occur. When has two children, then and node moves into node s original position; line 20 gives the same color as. If s original color was black, then removing or moving could cause violations of the red-black properties. MAT AA+DS, Fall Oct

8 We keep track of the node that moves into s original position. The assignments (lines 4, 7, 11) set to point to either s only child or, if has no children, the sentinel. Since node moves into s original position, the attribute is always set to point to the original position in the tree of s parent. Unless is s original parent, the assignment to takes place (line 6 of RB-TRANSPLANT). When s original parent is, we do not want to point to s parent, we are removing it from the tree. Node will move up to take s position, setting to (line 13) causes to point to the original position of s parent, even if. MAT AA+DS, Fall Oct If node was black, we might have introduced violations of the red-black properties. RB-DELETE- FIXUP restores the red-black properties. If was red, the red-black properties still hold when is removed or moved, for the following reasons: 1. No black-heights in the tree have changed. 2. Because takes s place in the tree, along with s color, we cannot have two adjacent red nodes at s new position. In addition, if was not s right child, then s original right child replaces. If is red, then must be black, and so replacing by cannot cause two red nodes to become adjacent. 3. Since could not have been the root if it was red, the root remains black. MAT AA+DS, Fall Oct

9 RB-DELETE-FIXUP(, ) 1. while and == BLACK 1. if == 2. // case 1 4. if == RED 5. BLACK 6. == RED 7. LEFT-ROTATE ) 8. // case 2 9. if. left.color= BLACK and. right.color == BLACK 10. = RED 11. // case elseif. right.color == BLACK 13.. left.color BLACK 14. == RED 15. RIGHT-ROTATE ) 16. // case = BLACK 19.. right.color BLACK 20. LEFT-ROTATE ) else (same as then clause with right/left exchanged) 23. = BLACK MAT AA+DS, Fall Oct RB-DELETE-FIXUP restores properties 1, 2, and 4 The goal of the while loop (lines 1 22) is to move the extra black up the tree until 1. points to a red-and-black node, in which case we color (singly) black (line 23); 2. points to the root, in which case we simply remove the extra black; or 3. having performed suitable rotations and recolorings, we exit the loop MAT AA+DS, Fall Oct

10 Analysis Height of a RBT of nodes is (lg ), total cost without the call to -FIXUP is (lg ) time Within -FIXUP, cases 1, 3, and 4 lead to termination after a constant number of color changes and at most three rotations Only in case 2 the while loop can be repeated, and then the pointer moves up the tree at most (lg ) times, without rotations Thus, - FIXUP takes (lg ) time and performs 3 rotations, the overall time for RB-DELETE is (lg ) MAT AA+DS, Fall Oct IV Advanced Design and Analysis Techniques Dynamic Programming Greedy Algorithms Amortized Analysis 10

11 15 Dynamic Programming Divide-and-conquer algorithms partition the problem into disjoint subproblems, recurse, and then combine the solutions Dynamic programming applies when the subproblems overlap that is, when they share subsubproblems A dynamic-programming algorithm solves each subsubproblem just once and saves its answer in a table, thereby avoiding the work of recomputing the answer every time it solves each subsubproblem MAT AA+DS, Fall Oct We typically apply dynamic programming to optimization problems, which can have many possible solutions Each solution has a value, and we wish to nd a solution with the optimal (min or max) value We call such a solution an optimal solution, several solutions may achieve the optimal value 1. Characterize the structure of an optimal solution 2. Recursively de ne the value of an optimal solution 3. Compute the value of an optimal solution, typically in a bottom-up fashion 4. Construct an optimal solution from computed information MAT AA+DS, Fall Oct

12 15.1 Rod cutting Serling Enterprises buys long steel rods and cuts them into shorter rods, which it then sells Each cut is free The management wants to know the best way to cut up the rods We assume that we know, for =1,2,, the price in dollars that Serling charges for a rod of length inches Rod lengths are always an integral number MAT AA+DS, Fall Oct Length Price The rod-cutting problem is the following. Given a rod of length inches and a table of prices for =1,2,,, determine the maximum revenue obtainable by cutting up the rod and selling the pieces Note that if the price for a rod of length is large enough, an optimal solution may require no cutting at all MAT AA+DS, Fall Oct

13 We can cut up a rod of length in 2 different ways: we have an independent option of cutting, or not cutting, at distance inches from the left end, =1,2,, 1 When =4, there are 2 =8ways to cut up the rod, including the way with no cuts at all Cutting a 4-inch rod into two 2-inch pieces produces optimal revenue + = = 10 MAT AA+DS, Fall Oct If an optimal solution cuts the rod into pieces, for some, then an optimal decomposition of the rod into pieces of lengths,, provides maximum corresponding revenue We can frame the values for 1in terms of optimal revenues from shorter rods: = max,, MAT AA+DS, Fall Oct

14 To solve the original problem of size, we solve smaller problems of the same type Once we make the rst cut, we may consider the two pieces as independent instances of the rodcutting problem The overall optimal solution incorporates optimal solutions to the related two subproblems, maximizing revenue from each of those pieces The rod-cutting problem exhibits optimal substructure: optimal solutions incorporate optimal solutions to related subproblems, which we may solve independently MAT AA+DS, Fall Oct We view a decomposition as consisting of a rst piece of length cut off the left-hand end, and then a right-hand remainder of length Only the remainder, and not the rst piece, may be further divided Decomposition of a length- rod has a rst piece followed by some decomposition of the rest No cuts at all: rst piece has size and revenue and the remainder has size 0 with corresponding revenue =0 We thus obtain the following equation: = max MAT AA+DS, Fall Oct

15 The following procedure implements the computation implicit in equation in a straightforward, top-down, recursive manner CUT-ROD ) 1. if ==0 2. return for =1to 5. = max( +CUT-ROD ) 6. return MAT AA+DS, Fall Oct CUT-ROD takes as input array [1.. ]of prices and an integer If we ran CUT-ROD on a computer, we would nd that once the input size becomes moderately large, our program would take a long time to run For = 40, we would nd that our program takes at least several minutes, and most likely more than an hour In fact, we would nd that each time we increase by 1, our program s running time would approximately double MAT AA+DS, Fall Oct

16 CUT-ROD calls itself recursively over and over again with the same parameter values it solves the same subproblems repeatedly CUT-ROD calls CUT-ROD CUT-ROD calls CUT-ROD for each = 0,1,, The amount of work done, as a function of, grows explosively MAT AA+DS, Fall Oct Let ( ) denote the total number of calls made to CUT-ROD when called with its second parameter equal to This equals the number of nodes in a subtree whose root is labeled in the recursion tree The count includes the initial call at its root Thus, 0 =1and =1+ ) =2 the running time is exponential MAT AA+DS, Fall Oct

17 Using dynamic programming for optimal rod cutting We arrange for each subproblem to be solved only once, saving its solution We can just look the solution up again later Dynamic programming serves an example of a time-memory trade-off This approach runs in polynomial time when the number of distinct subproblems involved is polynomial in the input size and we can solve each such in polynomial time MAT AA+DS, Fall Oct In top-down approach with memoization, we write the procedure recursively modi ed to save the result of each subproblem The procedure now rst checks to see whether it has previously solved this subproblem. If so, it returns the saved value, if not, the it computes the value in the usual manner MEMO-CUT-ROD 1. let [0.. ] be a new array 2. for =1to return MEMO-CUT-ROD-AUX,, MAT AA+DS, Fall Oct

18 MEMO-CUT-ROD-AUX,, 1. if 0 2. return ] 3. if ==0 4. =0 5. else 6. for =1to 7. = max( ] + MEMO-CUT-ROD-AUX ) return MAT AA+DS, Fall Oct The bottom-up method typically depends on some natural notion of the size of a subproblem We sort the subproblems by size and solve them in size order, smallest rst When solving a subproblem, we have already solved all of the smaller subproblems its solution depends upon, we have saved their solutions We solve each subproblem only once, and when we rst see it, we have already solved all of its prerequisite subproblems MAT AA+DS, Fall Oct

19 BOTTOM-UP-CUT-ROD 1. let [0.. ] be a new array 2. 0 =0 3. for =1to for =1to 6. = max( ) return MAT AA+DS, Fall Oct The running time of BOTTOM-UP-CUT-ROD is ), due to its doubly-nested loop structure The number of iterations of its inner for loop, in lines 5 6, forms an arithmetic series The running time of its top-down counterpart, MEMO-CUT-ROD, is also A recursive call to previously solved subproblem returns immediately, MEMO-CUT-ROD solves each subproblem just once To solve a subproblem of size, the for loop of lines 6 7 iterates times The total number of iterations of this loop, over all recursive calls forms an arithmetic series MAT AA+DS, Fall Oct

20 Reconstructing a solution The solutions to the rod-cutting problem return the value of an optimal solution, but they do not return an actual solution: a list of piece sizes We can extend the dynamic-programming approach to record also a choice that led to the optimal value An extended version of BOTTOM-UP-CUT-ROD computes, for each rod size, not only the maximum revenue, but also, the optimal size of the rst piece to cut off MAT AA+DS, Fall Oct EXTENDED-BOTTOM-UP-CUT-ROD, 1. let [0.. ] and s[0.. ] be new arrays 2. 0 =0 3. for =1to for =1to 6. if ] 7. ] return and MAT AA+DS, Fall Oct

21 The following procedure prints out the complete list of piece sizes in an optimal decomposition of a rod of length : PRINT-CUT-ROD-SOLUTION 1. ) = EXTENDED-BOTTOM-UP-CUT-ROD 2. while >0 3. print 4. MAT AA+DS, Fall Oct In our example, the call EXTENDED-BOTTOM-UP- CUT-ROD, 10 would return the following arrays: ] ] A call to PRINT-CUT-ROD-SOLUTION, 10 would print just 10, but a call with = 7 would print the cuts 1 and 6, corresponding to the rst optimal decomposition for MAT AA+DS, Fall Oct

22 15.2 Matrix-chain multiplication Given a sequence (chain),, of matrices we wish to compute the product We can evaluate the expression using standard algorithm for multiplying pairs of matrices once we have parenthesized it to resolve all ambiguities in how the matrices are multiplied together Matrix multiplication is associative, and so all parenthesizations yield the same product MAT AA+DS, Fall Oct A product of matrices is fully parenthesized if it is either a single matrix or the product of two fully parenthesized matrix products, surrounded by parentheses For example, we can fully parenthesize the product in ve distinct ways: )) ( )) (( )( )) (( )) ) ((( ) ) ) MAT AA+DS, Fall Oct

23 How we parenthesize a chain of matrices has a dramatic impact on cost of product evaluation Standard algorithm for multiplying two matrices: MATRIX-MULTIPLY ) 1. if.columns.rows 2. error incompatible dimensions 3. else let be a new.rows.columns matrix 4. for = 1 to.rows 5. for = 1 to.columns 6. =0 7. for = 1 to.columns return MAT AA+DS, Fall Oct We can multiply two matrices and only if they are compatible: the number of columns of must equal the number of rows of If is a matrix and is a matrix, the resulting matrix is a matrix The time to compute is dominated by the number of scalar multiplications in line 8, which is We shall express costs in terms of the number of scalar multiplications. MAT AA+DS, Fall Oct

24 Consider matrix product of a chain of matrices with dimensions , 100 5, and 5 50 If we apply the parenthesization (( ), we perform = 5000 scalar multiplications to compute the 10 5matrix product, plus = 2500 further ones to multiply this matrix by a total of 7500 scalar multiplications If instead we use )), we perform = 25,000 scalar multiplications to compute the matrix product, plus another = 50,000 scalar multiplications to multiply by this matrix a total of 75,000 scalar multiplications Thus, computing the product according to the rst parenthesization is 10 times faster MAT AA+DS, Fall Oct

We augment RBTs to support operations on dynamic sets of intervals A closed interval is an ordered pair of real

We augment RBTs to support operations on dynamic sets of intervals A closed interval is an ordered pair of real 14.3 Interval trees We augment RBTs to support operations on dynamic sets of intervals A closed interval is an ordered pair of real numbers ], with Interval ]represents the set Open and half-open intervals

More information

Ensures that no such path is more than twice as long as any other, so that the tree is approximately balanced

Ensures that no such path is more than twice as long as any other, so that the tree is approximately balanced 13 Red-Black Trees A red-black tree (RBT) is a BST with one extra bit of storage per node: color, either RED or BLACK Constraining the node colors on any path from the root to a leaf Ensures that no such

More information

Algorithms. Ch.15 Dynamic Programming

Algorithms. Ch.15 Dynamic Programming Algorithms Ch.15 Dynamic Programming Dynamic Programming Not a specific algorithm, but a technique (like divide-and-conquer). Developed back in the day when programming meant tabular method (like linear

More information

CS 380 ALGORITHM DESIGN AND ANALYSIS

CS 380 ALGORITHM DESIGN AND ANALYSIS CS 380 ALGORITHM DESIGN AND ANALYSIS Lecture 14: Dynamic Programming Text Reference: Chapter 15 Dynamic Programming We know that we can use the divide-and-conquer technique to obtain efficient algorithms

More information

15.4 Longest common subsequence

15.4 Longest common subsequence 15.4 Longest common subsequence Biological applications often need to compare the DNA of two (or more) different organisms A strand of DNA consists of a string of molecules called bases, where the possible

More information

We assume uniform hashing (UH):

We assume uniform hashing (UH): We assume uniform hashing (UH): the probe sequence of each key is equally likely to be any of the! permutations of 0,1,, 1 UH generalizes the notion of SUH that produces not just a single number, but a

More information

Chapter 3 Dynamic programming

Chapter 3 Dynamic programming Chapter 3 Dynamic programming 1 Dynamic programming also solve a problem by combining the solutions to subproblems. But dynamic programming considers the situation that some subproblems will be called

More information

15.Dynamic Programming

15.Dynamic Programming 15.Dynamic Programming Dynamic Programming is an algorithm design technique for optimization problems: often minimizing or maximizing. Like divide and conquer, DP solves problems by combining solutions

More information

V Advanced Data Structures

V Advanced Data Structures V Advanced Data Structures B-Trees Fibonacci Heaps 18 B-Trees B-trees are similar to RBTs, but they are better at minimizing disk I/O operations Many database systems use B-trees, or variants of them,

More information

9/24/ Hash functions

9/24/ Hash functions 11.3 Hash functions A good hash function satis es (approximately) the assumption of SUH: each key is equally likely to hash to any of the slots, independently of the other keys We typically have no way

More information

Computer Sciences Department 1

Computer Sciences Department 1 1 Advanced Design and Analysis Techniques (15.1, 15.2, 15.3, 15.4 and 15.5) 3 Objectives Problem Formulation Examples The Basic Problem Principle of optimality Important techniques: dynamic programming

More information

V Advanced Data Structures

V Advanced Data Structures V Advanced Data Structures B-Trees Fibonacci Heaps 18 B-Trees B-trees are similar to RBTs, but they are better at minimizing disk I/O operations Many database systems use B-trees, or variants of them,

More information

Decreasing a key FIB-HEAP-DECREASE-KEY(,, ) 3.. NIL. 2. error new key is greater than current key 6. CASCADING-CUT(, )

Decreasing a key FIB-HEAP-DECREASE-KEY(,, ) 3.. NIL. 2. error new key is greater than current key 6. CASCADING-CUT(, ) Decreasing a key FIB-HEAP-DECREASE-KEY(,, ) 1. if >. 2. error new key is greater than current key 3.. 4.. 5. if NIL and.

More information

Lecture 4: Dynamic programming I

Lecture 4: Dynamic programming I Lecture : Dynamic programming I Dynamic programming is a powerful, tabular method that solves problems by combining solutions to subproblems. It was introduced by Bellman in the 950 s (when programming

More information

Today: Matrix Subarray (Divide & Conquer) Intro to Dynamic Programming (Rod cutting) COSC 581, Algorithms January 21, 2014

Today: Matrix Subarray (Divide & Conquer) Intro to Dynamic Programming (Rod cutting) COSC 581, Algorithms January 21, 2014 Today: Matrix Subarray (Divide & Conquer) Intro to Dynamic Programming (Rod cutting) COSC 581, Algorithms January 21, 2014 Reading Assignments Today s class: Chapter 4.1, 15.1 Reading assignment for next

More information

15.4 Longest common subsequence

15.4 Longest common subsequence 15.4 Longest common subsequence Biological applications often need to compare the DNA of two (or more) different organisms A strand of DNA consists of a string of molecules called bases, where the possible

More information

Properties of red-black trees

Properties of red-black trees Red-Black Trees Introduction We have seen that a binary search tree is a useful tool. I.e., if its height is h, then we can implement any basic operation on it in O(h) units of time. The problem: given

More information

18.3 Deleting a key from a B-tree

18.3 Deleting a key from a B-tree 18.3 Deleting a key from a B-tree B-TREE-DELETE deletes the key from the subtree rooted at We design it to guarantee that whenever it calls itself recursively on a node, the number of keys in is at least

More information

22 Elementary Graph Algorithms. There are two standard ways to represent a

22 Elementary Graph Algorithms. There are two standard ways to represent a VI Graph Algorithms Elementary Graph Algorithms Minimum Spanning Trees Single-Source Shortest Paths All-Pairs Shortest Paths 22 Elementary Graph Algorithms There are two standard ways to represent a graph

More information

22 Elementary Graph Algorithms. There are two standard ways to represent a

22 Elementary Graph Algorithms. There are two standard ways to represent a VI Graph Algorithms Elementary Graph Algorithms Minimum Spanning Trees Single-Source Shortest Paths All-Pairs Shortest Paths 22 Elementary Graph Algorithms There are two standard ways to represent a graph

More information

Advanced Algorithms and Data Structures

Advanced Algorithms and Data Structures Advanced Algorithms and Data Structures Prof. Tapio Elomaa tapio.elomaa@tut.fi Course Prerequisites A seven credit unit course Replaced OHJ-2156 Analysis of Algorithms We take things a bit further than

More information

Search Trees. Undirected graph Directed graph Tree Binary search tree

Search Trees. Undirected graph Directed graph Tree Binary search tree Search Trees Undirected graph Directed graph Tree Binary search tree 1 Binary Search Tree Binary search key property: Let x be a node in a binary search tree. If y is a node in the left subtree of x, then

More information

So far... Finished looking at lower bounds and linear sorts.

So far... Finished looking at lower bounds and linear sorts. So far... Finished looking at lower bounds and linear sorts. Next: Memoization -- Optimization problems - Dynamic programming A scheduling problem Matrix multiplication optimization Longest Common Subsequence

More information

Dynamic Programming. Design and Analysis of Algorithms. Entwurf und Analyse von Algorithmen. Irene Parada. Design and Analysis of Algorithms

Dynamic Programming. Design and Analysis of Algorithms. Entwurf und Analyse von Algorithmen. Irene Parada. Design and Analysis of Algorithms Entwurf und Analyse von Algorithmen Dynamic Programming Overview Introduction Example 1 When and how to apply this method Example 2 Final remarks Introduction: when recursion is inefficient Example: Calculation

More information

CS473-Algorithms I. Lecture 10. Dynamic Programming. Cevdet Aykanat - Bilkent University Computer Engineering Department

CS473-Algorithms I. Lecture 10. Dynamic Programming. Cevdet Aykanat - Bilkent University Computer Engineering Department CS473-Algorithms I Lecture 1 Dynamic Programming 1 Introduction An algorithm design paradigm like divide-and-conquer Programming : A tabular method (not writing computer code) Divide-and-Conquer (DAC):

More information

16 Greedy Algorithms

16 Greedy Algorithms 16 Greedy Algorithms Optimization algorithms typically go through a sequence of steps, with a set of choices at each For many optimization problems, using dynamic programming to determine the best choices

More information

Let the dynamic table support the operations TABLE-INSERT and TABLE-DELETE It is convenient to use the load factor ( )

Let the dynamic table support the operations TABLE-INSERT and TABLE-DELETE It is convenient to use the load factor ( ) 17.4 Dynamic tables Let us now study the problem of dynamically expanding and contracting a table We show that the amortized cost of insertion/ deletion is only (1) Though the actual cost of an operation

More information

Dynamic Programming Matrix-chain Multiplication

Dynamic Programming Matrix-chain Multiplication 1 / 32 Dynamic Programming Matrix-chain Multiplication CS 584: Algorithm Design and Analysis Daniel Leblanc 1 1 Senior Adjunct Instructor Portland State University Maseeh College of Engineering and Computer

More information

Data Structures and Algorithms Week 8

Data Structures and Algorithms Week 8 Data Structures and Algorithms Week 8 Dynamic programming Fibonacci numbers Optimization problems Matrix multiplication optimization Principles of dynamic programming Longest Common Subsequence Algorithm

More information

Dynamic Programming Group Exercises

Dynamic Programming Group Exercises Name: Name: Name: Dynamic Programming Group Exercises Adapted from material by Cole Frederick Please work the following problems in groups of 2 or 3. Use additional paper as needed, and staple the sheets

More information

- Main approach is recursive, but holds answers to subproblems in a table so that can be used again without re-computing

- Main approach is recursive, but holds answers to subproblems in a table so that can be used again without re-computing Dynamic Programming class 2 - Main approach is recursive, but holds answers to subproblems in a table so that can be used again without re-computing - Can be formulated both via recursion and saving in

More information

Algorithm Design Techniques part I

Algorithm Design Techniques part I Algorithm Design Techniques part I Divide-and-Conquer. Dynamic Programming DSA - lecture 8 - T.U.Cluj-Napoca - M. Joldos 1 Some Algorithm Design Techniques Top-Down Algorithms: Divide-and-Conquer Bottom-Up

More information

Introduction to Algorithms

Introduction to Algorithms Introduction to Algorithms Dynamic Programming Well known algorithm design techniques: Brute-Force (iterative) ti algorithms Divide-and-conquer algorithms Another strategy for designing algorithms is dynamic

More information

CS141: Intermediate Data Structures and Algorithms Dynamic Programming

CS141: Intermediate Data Structures and Algorithms Dynamic Programming CS141: Intermediate Data Structures and Algorithms Dynamic Programming Amr Magdy Programming? In this context, programming is a tabular method Other examples: Linear programing Integer programming 2 Rod

More information

1 i n (p i + r n i ) (Note that by allowing i to be n, we handle the case where the rod is not cut at all.)

1 i n (p i + r n i ) (Note that by allowing i to be n, we handle the case where the rod is not cut at all.) Dynamic programming is a problem solving method that is applicable to many different types of problems. I think it is best learned by example, so we will mostly do examples today. 1 Rod cutting Suppose

More information

A red-black tree is a balanced binary search tree with the following properties:

A red-black tree is a balanced binary search tree with the following properties: Binary search trees work best when they are balanced or the path length from root to any leaf is within some bounds. The red-black tree algorithm is a method for balancing trees. The name derives from

More information

Algorithms & Datastructures Laboratory Exercise Sheet 10

Algorithms & Datastructures Laboratory Exercise Sheet 10 Algorithms & Datastructures Laboratory Exercise Sheet Wolfgang Pausch Heiko Studt René Thiemann Tomas Vitvar

More information

Lecture 8. Dynamic Programming

Lecture 8. Dynamic Programming Lecture 8. Dynamic Programming T. H. Cormen, C. E. Leiserson and R. L. Rivest Introduction to Algorithms, 3rd Edition, MIT Press, 2009 Sungkyunkwan University Hyunseung Choo choo@skku.edu Copyright 2000-2018

More information

Unit 4: Dynamic Programming

Unit 4: Dynamic Programming Unit 4: Dynamic Programming Course contents: Assembly-line scheduling Matrix-chain multiplication Longest common subsequence Optimal binary search trees Applications: Cell flipping, rod cutting, optimal

More information

Algorithms. Red-Black Trees

Algorithms. Red-Black Trees Algorithms Red-Black Trees Red-Black Trees Balanced binary search trees guarantee an O(log n) running time Red-black-tree Binary search tree with an additional attribute for its nodes: color which can

More information

Dynamic Programming II

Dynamic Programming II June 9, 214 DP: Longest common subsequence biologists often need to find out how similar are 2 DNA sequences DNA sequences are strings of bases: A, C, T and G how to define similarity? DP: Longest common

More information

Algorithm classification

Algorithm classification Types of Algorithms Algorithm classification Algorithms that use a similar problem-solving approach can be grouped together We ll talk about a classification scheme for algorithms This classification scheme

More information

CS 758/858: Algorithms

CS 758/858: Algorithms CS 758/858: Algorithms http://www.cs.unh.edu/~ruml/cs758 1 handout: slides Wheeler Ruml (UNH) Class 7, CS 758 1 / 16 BST Deletion Single Child Immed. Succ. Deep Succ. Break Wheeler Ruml (UNH) Class 7,

More information

Worst-case running time for RANDOMIZED-SELECT

Worst-case running time for RANDOMIZED-SELECT Worst-case running time for RANDOMIZED-SELECT is ), even to nd the minimum The algorithm has a linear expected running time, though, and because it is randomized, no particular input elicits the worst-case

More information

Red-Black Trees. Based on materials by Dennis Frey, Yun Peng, Jian Chen, and Daniel Hood

Red-Black Trees. Based on materials by Dennis Frey, Yun Peng, Jian Chen, and Daniel Hood Red-Black Trees Based on materials by Dennis Frey, Yun Peng, Jian Chen, and Daniel Hood Quick Review of Binary Search Trees n Given a node n... q All elements of n s left subtree are less than n.data q

More information

Design and Analysis of Algorithms 演算法設計與分析. Lecture 7 April 15, 2015 洪國寶

Design and Analysis of Algorithms 演算法設計與分析. Lecture 7 April 15, 2015 洪國寶 Design and Analysis of Algorithms 演算法設計與分析 Lecture 7 April 15, 2015 洪國寶 1 Course information (5/5) Grading (Tentative) Homework 25% (You may collaborate when solving the homework, however when writing

More information

Framework for Design of Dynamic Programming Algorithms

Framework for Design of Dynamic Programming Algorithms CSE 441T/541T Advanced Algorithms September 22, 2010 Framework for Design of Dynamic Programming Algorithms Dynamic programming algorithms for combinatorial optimization generalize the strategy we studied

More information

CS 380 ALGORITHM DESIGN AND ANALYSIS

CS 380 ALGORITHM DESIGN AND ANALYSIS CS 380 ALGORITHM DESIGN AND ANALYSIS Lecture 12: Red-Black Trees Text Reference: Chapters 12, 13 Binary Search Trees (BST): Review Each node in tree T is a object x Contains attributes: Data Pointers to

More information

Homework3: Dynamic Programming - Answers

Homework3: Dynamic Programming - Answers Most Exercises are from your textbook: Homework3: Dynamic Programming - Answers 1. For the Rod Cutting problem (covered in lecture) modify the given top-down memoized algorithm (includes two procedures)

More information

2-3 Tree. Outline B-TREE. catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } ADD SLIDES ON DISJOINT SETS

2-3 Tree. Outline B-TREE. catch(...){ printf( Assignment::SolveProblem() AAAA!); } ADD SLIDES ON DISJOINT SETS Outline catch(...){ printf( "Assignment::SolveProblem() AAAA!"); } Balanced Search Trees 2-3 Trees 2-3-4 Trees Slide 4 Why care about advanced implementations? Same entries, different insertion sequence:

More information

CS521 \ Notes for the Final Exam

CS521 \ Notes for the Final Exam CS521 \ Notes for final exam 1 Ariel Stolerman Asymptotic Notations: CS521 \ Notes for the Final Exam Notation Definition Limit Big-O ( ) Small-o ( ) Big- ( ) Small- ( ) Big- ( ) Notes: ( ) ( ) ( ) ( )

More information

Unit-5 Dynamic Programming 2016

Unit-5 Dynamic Programming 2016 5 Dynamic programming Overview, Applications - shortest path in graph, matrix multiplication, travelling salesman problem, Fibonacci Series. 20% 12 Origin: Richard Bellman, 1957 Programming referred to

More information

Lecture 6: Analysis of Algorithms (CS )

Lecture 6: Analysis of Algorithms (CS ) Lecture 6: Analysis of Algorithms (CS583-002) Amarda Shehu October 08, 2014 1 Outline of Today s Class 2 Traversals Querying Insertion and Deletion Sorting with BSTs 3 Red-black Trees Height of a Red-black

More information

Lecture: Analysis of Algorithms (CS )

Lecture: Analysis of Algorithms (CS ) Lecture: Analysis of Algorithms (CS583-002) Amarda Shehu Fall 2017 1 Binary Search Trees Traversals, Querying, Insertion, and Deletion Sorting with BSTs 2 Example: Red-black Trees Height of a Red-black

More information

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I MCA 312: Design and Analysis of Algorithms [Part I : Medium Answer Type Questions] UNIT I 1) What is an Algorithm? What is the need to study Algorithms? 2) Define: a) Time Efficiency b) Space Efficiency

More information

Algorithms. 演算法 Data Structures (focus on Trees)

Algorithms. 演算法 Data Structures (focus on Trees) 演算法 Data Structures (focus on Trees) Professor Chien-Mo James Li 李建模 Graduate Institute of Electronics Engineering National Taiwan University 1 Dynamic Set Dynamic set is a set of elements that can grow

More information

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs Algorithms in Systems Engineering ISE 172 Lecture 16 Dr. Ted Ralphs ISE 172 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms

More information

/463 Algorithms - Fall 2013 Solution to Assignment 3

/463 Algorithms - Fall 2013 Solution to Assignment 3 600.363/463 Algorithms - Fall 2013 Solution to Assignment 3 (120 points) I (30 points) (Hint: This problem is similar to parenthesization in matrix-chain multiplication, except the special treatment on

More information

Dynamic Programming. An Enumeration Approach. Matrix Chain-Products. Matrix Chain-Products (not in book)

Dynamic Programming. An Enumeration Approach. Matrix Chain-Products. Matrix Chain-Products (not in book) Matrix Chain-Products (not in book) is a general algorithm design paradigm. Rather than give the general structure, let us first give a motivating example: Matrix Chain-Products Review: Matrix Multiplication.

More information

Dynamic Programming. Outline and Reading. Computing Fibonacci

Dynamic Programming. Outline and Reading. Computing Fibonacci Dynamic Programming Dynamic Programming version 1.2 1 Outline and Reading Matrix Chain-Product ( 5.3.1) The General Technique ( 5.3.2) -1 Knapsac Problem ( 5.3.3) Dynamic Programming version 1.2 2 Computing

More information

III Data Structures. Dynamic sets

III Data Structures. Dynamic sets III Data Structures Elementary Data Structures Hash Tables Binary Search Trees Red-Black Trees Dynamic sets Sets are fundamental to computer science Algorithms may require several different types of operations

More information

Dynamic Programming. Nothing to do with dynamic and nothing to do with programming.

Dynamic Programming. Nothing to do with dynamic and nothing to do with programming. Dynamic Programming Deliverables Dynamic Programming basics Binomial Coefficients Weighted Interval Scheduling Matrix Multiplication /1 Knapsack Longest Common Subsequence 6/12/212 6:56 PM copyright @

More information

CS350: Data Structures Red-Black Trees

CS350: Data Structures Red-Black Trees Red-Black Trees James Moscola Department of Engineering & Computer Science York College of Pennsylvania James Moscola Red-Black Tree An alternative to AVL trees Insertion can be done in a bottom-up or

More information

B Tree. Also, every non leaf node must have at least two successors and all leaf nodes must be at the same level.

B Tree. Also, every non leaf node must have at least two successors and all leaf nodes must be at the same level. B Tree If there is just one item in the node, then the B Tree is organised as a binar search tree: all items in the left sub tree must be less than the item in the node, and all items in the right sub

More information

CSci 231 Final Review

CSci 231 Final Review CSci 231 Final Review Here is a list of topics for the final. Generally you are responsible for anything discussed in class (except topics that appear italicized), and anything appearing on the homeworks.

More information

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017 CMSC 45 CMSC 45: Lecture Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct, Reading: Section. in KT. Dynamic Programming: In this lecture we begin our coverage of an important algorithm design

More information

13.4 Deletion in red-black trees

13.4 Deletion in red-black trees The operation of Deletion in a red-black tree is similar to the operation of Insertion on the tree. That is, apply the deletion algorithm for binary search trees to delete a node z; apply node color changes

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Chapter 12 Advanced Data Structures

Chapter 12 Advanced Data Structures Chapter 12 Advanced Data Structures 2 Red-Black Trees add the attribute of (red or black) to links/nodes red-black trees used in C++ Standard Template Library (STL) Java to implement maps (or, as in Python)

More information

ECE608 - Chapter 15 answers

ECE608 - Chapter 15 answers ¼ À ÈÌ Ê ½ ÈÊÇ Ä ÅË ½µ ½ º¾¹¾ ¾µ ½ º¾¹ µ ½ º¾¹ µ ½ º ¹½ µ ½ º ¹¾ µ ½ º ¹ µ ½ º ¹¾ µ ½ º ¹ µ ½ º ¹ ½¼µ ½ º ¹ ½½µ ½ ¹ ½ ECE608 - Chapter 15 answers (1) CLR 15.2-2 MATRIX CHAIN MULTIPLY(A, s, i, j) 1. if

More information

CS 231: Algorithmic Problem Solving

CS 231: Algorithmic Problem Solving CS 231: Algorithmic Problem Solving Naomi Nishimura Module 5 Date of this version: June 14, 2018 WARNING: Drafts of slides are made available prior to lecture for your convenience. After lecture, slides

More information

The divide-and-conquer paradigm involves three steps at each level of the recursion: Divide the problem into a number of subproblems.

The divide-and-conquer paradigm involves three steps at each level of the recursion: Divide the problem into a number of subproblems. 2.3 Designing algorithms There are many ways to design algorithms. Insertion sort uses an incremental approach: having sorted the subarray A[1 j - 1], we insert the single element A[j] into its proper

More information

CMPS 2200 Fall 2017 Red-black trees Carola Wenk

CMPS 2200 Fall 2017 Red-black trees Carola Wenk CMPS 2200 Fall 2017 Red-black trees Carola Wenk Slides courtesy of Charles Leiserson with changes by Carola Wenk 9/13/17 CMPS 2200 Intro. to Algorithms 1 Dynamic Set A dynamic set, or dictionary, is a

More information

Balanced search trees

Balanced search trees Balanced search trees Ordinary binary search trees have expected height Θ(log n) if items are inserted and deleted in random order, but for other orders the height can be Θ(n). This is undesirable, since

More information

Red-Black Trees. 1 Properties of red-black trees

Red-Black Trees. 1 Properties of red-black trees Red-Black Trees Chapter 12 showed that a binary search tree of height h can support any of the basic dynamic-set operations such as SEARCH, PREDECESSOR, SUCCESSOR, MINI- MUM, MAXIMUM, INSERT, anddelete

More information

Data Structures and Algorithms CMPSC 465

Data Structures and Algorithms CMPSC 465 Data Structures and Algorithms CMPSC 465 LECTURE 24 Balanced Search Trees Red-Black Trees Adam Smith 4/18/12 A. Smith; based on slides by C. Leiserson and E. Demaine L1.1 Balanced search trees Balanced

More information

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g)

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g) Introduction to Algorithms March 11, 2009 Massachusetts Institute of Technology 6.006 Spring 2009 Professors Sivan Toledo and Alan Edelman Quiz 1 Solutions Problem 1. Quiz 1 Solutions Asymptotic orders

More information

Algorithms, Spring 2014, CSE, OSU Lecture 5: Red-black trees

Algorithms, Spring 2014, CSE, OSU Lecture 5: Red-black trees 6331 - Algorithms, Spring 2014, CSE, OSU Lecture 5: Red-black trees Instructor: Anastasios Sidiropoulos January 17, 2014 Red-black trees For every node x: x.color : red or black x.k : key x.p : pointer

More information

COMP 251 Winter 2017 Online quizzes with answers

COMP 251 Winter 2017 Online quizzes with answers COMP 251 Winter 2017 Online quizzes with answers Open Addressing (2) Which of the following assertions are true about open address tables? A. You cannot store more records than the total number of slots

More information

CMPS 2200 Fall 2015 Red-black trees Carola Wenk

CMPS 2200 Fall 2015 Red-black trees Carola Wenk CMPS 2200 Fall 2015 Red-black trees Carola Wenk Slides courtesy of Charles Leiserson with changes by Carola Wenk 9/9/15 CMPS 2200 Intro. to Algorithms 1 ADT Dictionary / Dynamic Set Abstract data type

More information

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17 01.433/33 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/2/1.1 Introduction In this lecture we ll talk about a useful abstraction, priority queues, which are

More information

Dynamic Programming (Part #2)

Dynamic Programming (Part #2) Dynamic Programming (Part #) Introduction to Algorithms MIT Press (Chapter 5) Matrix-Chain Multiplication Problem: given a sequence A, A,, A n, compute the product: A A A n Matrix compatibility: C = A

More information

Dynamic programming 4/9/18

Dynamic programming 4/9/18 Dynamic programming 4/9/18 Administrivia HW 3 due Wednesday night Exam out Thursday, due next week Multi-day takehome, open book, closed web, written problems Induction, AVL trees, recurrences, D&C, multithreaded

More information

12 Dynamic Programming (2) Matrix-chain Multiplication Segmented Least Squares

12 Dynamic Programming (2) Matrix-chain Multiplication Segmented Least Squares 12 Dynamic Programming (2) Matrix-chain Multiplication Segmented Least Squares Optimal substructure Dynamic programming is typically applied to optimization problems. An optimal solution to the original

More information

Elements of Dynamic Programming. COSC 3101A - Design and Analysis of Algorithms 8. Discovering Optimal Substructure. Optimal Substructure - Examples

Elements of Dynamic Programming. COSC 3101A - Design and Analysis of Algorithms 8. Discovering Optimal Substructure. Optimal Substructure - Examples Elements of Dynamic Programming COSC 3A - Design and Analysis of Algorithms 8 Elements of DP Memoization Longest Common Subsequence Greedy Algorithms Many of these slides are taken from Monica Nicolescu,

More information

Search Trees. COMPSCI 355 Fall 2016

Search Trees. COMPSCI 355 Fall 2016 Search Trees COMPSCI 355 Fall 2016 2-4 Trees Search Trees AVL trees Red-Black trees Splay trees Multiway Search Trees (2, 4) Trees External Search Trees (optimized for reading and writing large blocks)

More information

II (Sorting and) Order Statistics

II (Sorting and) Order Statistics II (Sorting and) Order Statistics Heapsort Quicksort Sorting in Linear Time Medians and Order Statistics 8 Sorting in Linear Time The sorting algorithms introduced thus far are comparison sorts Any comparison

More information

Red-Black Trees (2) Antonio Carzaniga. April 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

Red-Black Trees (2) Antonio Carzaniga. April 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga Red-Black Trees (2) Antonio Carzaniga Faculty of Informatics Università della Svizzera italiana April 23, 2013 Recap on Red-Black Trees 2006 Antonio Carzaniga Recap on Red-Black Trees 12 5 18 2 9 15 19

More information

Data Structures and Algorithms. Dynamic Programming

Data Structures and Algorithms. Dynamic Programming Data Structures and Algorithms Dynamic Programming Introduction Dynamic programming is simply the process of turning recursive calls in to table lookups. If a recursive function does redundant computations,

More information

CSE 417 Dynamic Programming (pt 4) Sub-problems on Trees

CSE 417 Dynamic Programming (pt 4) Sub-problems on Trees CSE 417 Dynamic Programming (pt 4) Sub-problems on Trees Reminders > HW4 is due today > HW5 will be posted shortly Dynamic Programming Review > Apply the steps... 1. Describe solution in terms of solution

More information

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

CS 4349 Lecture September 13th, 2017

CS 4349 Lecture September 13th, 2017 CS 4349 Lecture September 13th, 2017 Main topics for #lecture include #dynamic_programming, #Fibonacci_numbers, and #rod_cutting. Prelude Homework 2 due today in class. Homework 3 released, due next Wednesday

More information

1 Non greedy algorithms (which we should have covered

1 Non greedy algorithms (which we should have covered 1 Non greedy algorithms (which we should have covered earlier) 1.1 Floyd Warshall algorithm This algorithm solves the all-pairs shortest paths problem, which is a problem where we want to find the shortest

More information

Design and Analysis of Algorithms 演算法設計與分析. Lecture 7 April 6, 2016 洪國寶

Design and Analysis of Algorithms 演算法設計與分析. Lecture 7 April 6, 2016 洪國寶 Design and Analysis of Algorithms 演算法設計與分析 Lecture 7 April 6, 2016 洪國寶 1 Course information (5/5) Grading (Tentative) Homework 25% (You may collaborate when solving the homework, however when writing up

More information

IN101: Algorithmic techniques Vladimir-Alexandru Paun ENSTA ParisTech

IN101: Algorithmic techniques Vladimir-Alexandru Paun ENSTA ParisTech IN101: Algorithmic techniques Vladimir-Alexandru Paun ENSTA ParisTech License CC BY-NC-SA 2.0 http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Outline Previously on IN101 Python s anatomy Functions,

More information

) $ f ( n) " %( g( n)

) $ f ( n)  %( g( n) CSE 0 Name Test Spring 008 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to compute the sum of the n elements of an integer array is: # A.

More information

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D.

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D. CSE 0 Name Test Fall 00 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to convert an array, with priorities stored at subscripts through n,

More information

Lecture 13: AVL Trees and Binary Heaps

Lecture 13: AVL Trees and Binary Heaps Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1. ( ) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally

More information

CS 3343 Fall 2007 Red-black trees Carola Wenk

CS 3343 Fall 2007 Red-black trees Carola Wenk CS 3343 Fall 2007 Red-black trees Carola Wenk Slides courtesy of Charles Leiserson with small changes by Carola Wenk CS 334 Analysis of Algorithms 1 Search Trees A binary search tree is a binary tree.

More information

Outline. Definition. 2 Height-Balance. 3 Searches. 4 Rotations. 5 Insertion. 6 Deletions. 7 Reference. 1 Every node is either red or black.

Outline. Definition. 2 Height-Balance. 3 Searches. 4 Rotations. 5 Insertion. 6 Deletions. 7 Reference. 1 Every node is either red or black. Outline 1 Definition Computer Science 331 Red-Black rees Mike Jacobson Department of Computer Science University of Calgary Lectures #20-22 2 Height-Balance 3 Searches 4 Rotations 5 s: Main Case 6 Partial

More information