Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials.

Slides:



Advertisements
Similar presentations
CSC 421: Algorithm Design & Analysis
Advertisements

Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 2 Some of the sides are exported from different sources.
2/9/06CS 3343 Analysis of Algorithms1 Convex Hull  Given a set of pins on a pinboard  And a rubber band around them  How does the rubber band look when.
Chapter 5 Decrease and Conquer. Homework 7 hw7 (due 3/17) hw7 (due 3/17) –page 127 question 5 –page 132 questions 5 and 6 –page 137 questions 5 and 6.
Theory of Algorithms: Decrease and Conquer James Gain and Edwin Blake {jgain | Department of Computer Science University of Cape Town.
Chapter 5 Decrease-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 4 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chapter 5: Decrease and Conquer
Chapter 4 Decrease-and-Conquer. Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend.
Chap 5: Decrease & conquer. Objectives To introduce the decrease-and-conquer mind set To show a variety of decrease-and-conquer solutions: Depth-First.
Design & Analysis of Algorithms CS315
Divide-and-Conquer The most-well known algorithm design strategy:
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 5 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
1 Divide-and-Conquer The most-well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances 2. Solve smaller instances.
Decrease-and-Conquer
CS4413 Divide-and-Conquer
Chapter 6: Transform and Conquer
Design and Analysis of Algorithms - Chapter 51 Decrease and Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller.
Theory of Algorithms: Divide and Conquer
Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials.
Chapter 4 Divide-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Introduction to Algorithms
Chapter 4 Divide-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
TCSS 343, version 1.1 Algorithms, Design and Analysis Transform and Conquer Algorithms Presorting HeapSort.
Design and Analysis of Algorithms - Chapter 5
Design and Analysis of Algorithms - Chapter 41 Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two.
Design and Analysis of Algorithms - Chapter 41 Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two.
MA/CSSE 473 Day 12 Insertion Sort quick review DFS, BFS Topological Sort.
Convex Hull. What is the Convex Hull? Imagine a set of points on a board with a nail hammered into each point. Now stretch a rubber band over all the.
1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance.
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 5 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
MA/CSSE 473 Day 15 BFS Topological Sort Combinatorial Object Generation Intro.
A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 4 ©2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
UNIT-II DECREASE-AND-CONQUER ANALYSIS AND DESIGN OF ALGORITHMS CHAPTER 5:
Chapter 5 Decrease-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Lecture 13 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 7.
Now, Chapter 5: Decrease and Conquer Reduce problem instance to smaller instance of the same problem and extend solution Solve smaller instance Extend.
MA/CSSE 473 Day 14 Strassen's Algorithm: Matrix Multiplication Decrease and Conquer DFS.
MA/CSSE 473 Day 11 Knuth interview Amortization (growable Array) Brute Force Examples.
MA/CSSE 473 Day 12 Interpolation Search Insertion Sort quick review
Decrease-and-Conquer
CSC 421: Algorithm Design & Analysis
CSC 421: Algorithm Design & Analysis
Chapter 4 Divide-and-Conquer
Chapter 5 Decrease-and-Conquer
Chapter 6 Transform-and-Conquer
CSC 421: Algorithm Design & Analysis
Convex Hull.
Decrease-and-Conquer
Chapter 5 Decrease-and-Conquer
Chapter 5.
Decrease-and-Conquer
Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance.
Decrease-and-Conquer
Decrease-and-Conquer
Chapter 6: Transform and Conquer
Chapter 5 Decrease-and-Conquer
Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance.
Transform and Conquer Transform and Conquer Transform and Conquer.
Divide-and-Conquer The most-well known algorithm design strategy:
CSC 421: Algorithm Design & Analysis
Transform and Conquer Transform and Conquer Transform and Conquer.
CSC 380: Design and Analysis of Algorithms
Introduction to Algorithms
CSC 380: Design and Analysis of Algorithms
CSC 380: Design and Analysis of Algorithms
CSC 380: Design and Analysis of Algorithms
Analysis and design of algorithm
CSC 421: Algorithm Design & Analysis
Presentation transcript:

Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials

The First Problem 2  Convex Hull The problem is to find the convex hull of the points or the polygon. That is, a polygonal area that is of smallest length and so that any pair of points within the area have the line segment between them contained entirely inside the area.

Convex Hull 3  Given a set of pins on a pinboard  And a rubber band around them  How does the rubber band look when it snaps tight?  We represent the convex hull as the sequence of points on the convex hull polygon, in counter-clockwise order

Brute force Solution 4 Based on the following observation: A line segment connecting two points Pi and Pj of a set on n points is a part of the convex hull’s boundary if and only if all the other points of the set lie on the same side of the straight line through these two points. We need to try every pair of points  O(n 3 )

Quickhull Algorithm Convex hull: smallest convex set that includes given points. Assume points are sorted by x-coordinate values Identify extreme points P 1 and P 2 (leftmost and rightmost) Compute upper hull recursively: find point P max that is farthest away from line P 1 P 2 compute the upper hull of the points to the left of line P 1 P max compute the upper hull of the points to the left of line P max P 2 Compute lower hull in a similar manner P1P1 P2P2 P max

QuickHull Algorithm 6 How to find the P max point How to find the P max point P max maximizes the area of the triangle P max P 1 P 2 if tie, select the P max that maximizes the angle P max P 1 P 2 The points inside triangle P max P 1 P 2 can be excluded from further consideration Worst case : O(n 2 )

Convex Hull 7 Could you Solve the Convex Hull Problem in O(nlogn) ?

Convex Hull: Divide & Conquer 8  Preprocessing: sort the points by x-coordinate  Divide the set of points into two sets A and B:  A contains the left  n/2  points,  B contains the right  n/2  points  Recursively compute the convex hull of A  Recursively compute the convex hull of B  Merge the two convex hulls A B

Convex Hull: Runtime 9  Preprocessing: sort the points by x-coordinate  Divide the set of points into two sets A and B:  A contains the left  n/2  points,  B contains the right  n/2  points  Recursively compute the convex hull of A  Recursively compute the convex hull of B  Merge the two convex hulls O(n log n) just once O(1) T(n/2) O(n)

Convex Hull: Runtime 10  Runtime Recurrence: T(n) = 2 T(n/2) + n  Solves to T(n) =  (n log n)

Merging in O(n) time 11  Find upper and lower tangents in O(n) time  Compute the convex hull of A  B:  Walk clockwise around the convex hull of A, starting with left endpoint of lower tangent  When hitting the left endpoint of the upper tangent, cross over to the convex hull of B  Walk counterclockwise around the convex hull of B  When hitting right endpoint of the lower tangent we’re done  This takes O(n) time A B

QuickHull 12 How to find the upper and lower tangents in O(n) time ?

Finding the lower tangent in O(n) time 13 can be checked in constant time How? Check only A+1 and A-1 for instance a = rightmost point of A b = leftmost point of B while T=ab not lower tangent to both convex hulls of A and B do{ while T not lower tangent to convex hull of A do{ a=a-1 } while T not lower tangent to convex hull of B do{ b=b+1 } } A B 0 a= =b T is lower tangent if all the points are above the line

Convex Hull – Divide & Conquer 14 Split set into two, compute convex hull of both, combine.

Convex Hull – Divide & Conquer 15 Split set into two, compute convex hull of both, combine.

16 Split set into two, compute convex hull of both, combine.

17 Split set into two, compute convex hull of both, combine.

18 Split set into two, compute convex hull of both, combine.

19 Split set into two, compute convex hull of both, combine.

20 Split set into two, compute convex hull of both, combine.

21 Split set into two, compute convex hull of both, combine.

22 Split set into two, compute convex hull of both, combine.

23 Split set into two, compute convex hull of both, combine.

24 Split set into two, compute convex hull of both, combine.

25 Merging two convex hulls.

26 Merging two convex hulls: (i) Find the lower tangent.

27 Merging two convex hulls: (i) Find the lower tangent.

28 Merging two convex hulls: (i) Find the lower tangent.

29 Merging two convex hulls: (i) Find the lower tangent.

30 Merging two convex hulls: (i) Find the lower tangent.

31 Merging two convex hulls: (i) Find the lower tangent.

32 Merging two convex hulls: (i) Find the lower tangent.

33 Merging two convex hulls: (i) Find the lower tangent.

34 Merging two convex hulls: (i) Find the lower tangent.

35 Merging two convex hulls: (ii) Find the upper tangent.

36 Merging two convex hulls: (ii) Find the upper tangent.

37 Merging two convex hulls: (ii) Find the upper tangent.

38 Merging two convex hulls: (ii) Find the upper tangent.

39 Merging two convex hulls: (ii) Find the upper tangent.

40 Merging two convex hulls: (ii) Find the upper tangent.

41 Merging two convex hulls: (ii) Find the upper tangent.

42 Merging two convex hulls: (iii) Eliminate non-hull edges.

Chapter 5 Decrease-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance to obtain solution to original instance Also referred to as inductive or incremental approach

3 Types of Decrease and Conquer Decrease by a constant (usually by 1): Decrease by a constant (usually by 1): insertion sort graph traversal algorithms (DFS and BFS) topological sorting algorithms for generating permutations, subsets Decrease by a constant factor (usually by half) binary search and bisection method exponentiation by squaring multiplication à la russe Variable-size decrease Euclid’s algorithm selection by partition Nim-like games This usually results in a recursive algorithm.

The Problem 46 Consider the problem of exponentiation: Compute a n ?

Solutions a n = a*a*a*a*...*a a n = a n/2 * a n/2 (more accurately, a n = a  n/2  * a  n/2│ ) a n = a n-1 * a a n = (a n/2 ) 2 Divide and conquer: Brute Force Decrease by constant factor Decrease by one

What is the difference? Compute a n Brute Force: Divide and conquer: Decrease by one: Decrease by constant factor: n-1 multiplications T(n) = 2*T(n/2) + 1 = n-1 T(n) = T(n-1) + 1 = n-1 T(n) = T(n/a) + a-1 = (a-1) n = when a = 2

The problems Our eyes can pick out the connected components of an undirected graph by just looking at a picture of the graph, but it is much harder to do it with a glance at the adjacency lists. Detecting cycle in a graph Topological Sorting Sudoku Puzzles To test if a graph is bipartite What is a bipartite graph?

A bipartite graph (or bigraph) is a graph whose vertices can be divided into two disjoint sets U and V such that every edge connects a vertex in U to one in V; that is, U and V are independent sets. Used in many applications such as network load balancing

Graph Traversal Many problems require processing all graph vertices (and edges) in systematic fashion Graph traversal algorithms: Depth-first search (DFS) Breadth-first search (BFS)

Decrease by One Depth-First Search: (Brave Traversal) Visits graph’s vertices by always moving away from last visited vertex to an unvisited one, backtracks if no adjacent unvisited vertex is available. Recursive or it uses a stack Using Stack a vertex is pushed onto the stack when it’s reached for the first time a vertex is popped off the stack when it becomes a dead end, i.e., when there is no adjacent unvisited vertex Try to do it yourself and show me your trail in the following example?

Algorithm for DFS

Example: DFS traversal of undirected graph ab ef cd gh DFS traversal stack: DFS tree: ab ef cd gh a ab abf abfe abf ab abg abgc abgcd abgcdh abgcd … Red edges are tree edges and other edges are back edges

Notes on DFS DFS can be implemented with graphs represented as: adjacency matrices: Θ(|V| 2 ). Why? adjacency lists: Θ(|V|+|E|). Why? Yields two distinct ordering of vertices: order in which vertices are first encountered (pushed onto stack) order in which vertices become dead-ends (popped off stack) Applications: checking connectivity, finding connected components checking acyclicity (if no back edges)

The Problem Finding paths from a vertex to all other vertices with the smallest number of edges

Breadth First Search Visits graph vertices by moving across to all the neighbors of the last visited vertex Instead of a stack, BFS uses a queue Similar to level-by-level tree traversal “Redraws” graph in tree-like fashion.

Example of BFS traversal of undirected graph BFS traversal queue: ab ef cd gh BFS tree: ab ef cd gh a bef efg fg g ch hd d Red edges are tree edges and white edges are cross edges

Write an Algorithm for BFS Using a queue?

Notes on BFS BFS has same efficiency as DFS and can be implemented with graphs represented as: adjacency matrices: Θ(|V| 2 ). Why? adjacency lists: Θ(|V|+|E|). Why? Yields single ordering of vertices (order added/deleted from queue is the same) Applications: same as DFS, but can also find paths from a vertex to all other vertices with the smallest number of edges

Digraph - Example A part-time student needs to take a set of five courses {C1, C2, C3, C4, C5}, only one course per term, in any order as long as the following course prerequisites are met: C1 and C2 have no prerequisites C3 requires C1 and C2 C4 requires C3 C5 requires C3 and C4. The situation can be modeled by a diagraph: Vertices represent courses. Directed edges indicate prerequisite requirements. Vertices of a dag can be linearly ordered so that for every edge its starting vertex is listed before its ending vertex (topological sorting). Being a dag is also a necessary condition for topological sorting to be possible.

Topological Sorting Example Order the following items in a food chain fish human shrimp sheep wheatplankton tiger

Solving Topological Sorting Problem Solution: Verify whether a given digraph is a dag and, if it is, produce an ordering of vertices. Two algorithms for solving the problem. They may give different (alternative) solutions. DFS-based algorithm Perform DFS traversal and note the order in which vertices become dead ends (that is, are popped of the traversal stack). Reversing this order yields the desired solution, provided that no back edge has been encountered during the traversal.

Example Complexity: as DFS

Solving Topological Sorting Problem Source removal algorithm Identify a source, which is a vertex with no incoming edges and delete it along with all edges outgoing from it. There must be at least one source to have the problem solved. Repeat this process in a remaining diagraph. The order in which the vertices are deleted yields the desired solution.

Example

Source removal algorithm Efficiency Efficiency: same as efficiency of the DFS-based algorithm

Decrease-by-Constant-Factor Algorithms In this variation of decrease-and-conquer, instance size is reduced by the same factor (typically, 2) The Problems : Binary search and the method of bisection Exponentiation by squaring Multiplication à la russe (Russian peasant method) Fake-coin puzzle Josephus problem

Russian Peasant Multiplication The problem: Compute the product of two positive integers Can be solved by a decrease-by-half algorithm based on the following formulas. For even values of n: For odd values of n: n * m = * 2m n * m = * 2m + m if n > 1 and m if n = 1 n * m = * 2m + m if n > 1 and m if n = 1 n2n2n2n2 n – 1 2

Example of Russian Peasant Multiplication Compute 20 * 26 n m

Fake-Coin Puzzle (simpler version) There are n identically looking coins one of which is fake. There is a balance scale but there are no weights; the scale can tell whether two sets of coins weigh the same and, if not, which of the two sets is heavier (but not by how much, i.e. 3-way comparison). Design an efficient algorithm for detecting the fake coin. Assume that the fake coin is known to be lighter than the genuine ones. - Divide them into two piles, put them into the scale, neglect the heavier one. Repeat Decrease by factor 2 algorithm Decrease by factor 3 algorithm (Q3 on page 187 of Levitin) (your assignment) T(n) = log n T(n) What about odd n?

Variable-Size-Decrease Algorithms In the variable-size-decrease variation of decrease-and-conquer, instance size reduction varies from one iteration to another The Problems : Euclid’s algorithm for greatest common divisor Partition-based algorithm for selection problem Interpolation search Some algorithms on binary search trees Nim and Nim-like games

Euclid’s Algorithm Euclid’s algorithm is based on repeated application of equality gcd(m, n) = gcd(n, m mod n) Ex.: gcd(80,44) = gcd(44,36) = gcd(36, 12) = gcd(12,0) = 12 One can prove that the size, measured by the second number, decreases at least by half after two consecutive iterations. Hence, T(n)  O(log n)

Selection Problem Find the k-th smallest element in a list of n numbers k = 1 or k = n median: k =  n/2  Example: 4, 1, 10, 9, 7, 12, 8, 2, 15  n =9 median = 9/2 = 5 The median is used in statistics as a measure of an average value of a sample. In fact, it is a better (more robust) indicator than the mean, which is used for the same purpose.

Algorithms for the Selection Problem The sorting-based algorithm: Sort and return the k-th element Efficiency (if sorted by mergesort): Θ(nlog n) Can you find a faster algorithm? A faster algorithm is based on using the quicksort-like partition of the list. Let s be a split position obtained by a partition: Assuming that the list is indexed from 1 to n: If s = k, the problem is solved; if s > k, look for the k-th smallest elem. in the left part; if s < k, look for the (k-s)-th smallest elem. in the right part. Note: The algorithm can simply continue until s = k. s all are ≤ A[s]all are ≥ A[s]

Example 4, 1, 10, 9, 7, 12, 8, 2, 15 n= 9 median =  n/2  = 5 So, find the 5 th smallest item ? Select the pivot 4 4, 1, 10, 9, 7, 12, 8, 2, 15 2, 1, 4, 9, 7, 12, 8, 10, 15 since s=3 and k= 5 proceed with the right part, Select 9 as a pivot 9, 7, 12, 8, 10, 15 8, 7, 9, 12, 10, 15 Since s =6 and k=5 proceed with the left part, Select 8 as a pivot 8, 7 7, 8 Now s=k=5 and the 5th smallest item is 8

Part of your assignment Report the complexity of the previous algorithm?

Binary Search Tree Algorithms Several algorithms on BST requires recursive processing of just one of its subtrees, e.g., Searching Insertion of a new key Finding the smallest (or the largest) key k <k>k

Searching in Binary Search Tree Algorithm BTS(x, v) //Searches for node with key equal to v in BST rooted at node x if x = NIL return -1 else if v = K(x) return x else if v < K(x) return BTS(left(x), v) else return BTS(right(x), v) Efficiency worst case: C(n) = n

Chapter 6 Transform-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

Transform and Conquer This group of techniques solves a problem by a transformation b To a simpler/more convenient instance of the same problem (instance simplification) b To a different representation of the same instance (representation change) b To a different problem for which an algorithm is already available (problem reduction)

Instance simplification - Presorting Solve a problem’s instance by transforming it into another simpler/easier instance of the same problem Presorting Many problems involving lists are easier when list is sorted. b searching b computing the median (selection problem) b checking if all elements are distinct (element uniqueness) Also: b Topological sorting helps solving some problems for dags. b Presorting is used in many geometric algorithms.

How fast can we sort ? Efficiency of algorithms involving sorting depends on efficiency of sorting. Note: About nlog 2 n comparisons are also sufficient to sort array of size n (by mergesort).

Searching with presorting Problem: Search for a given K in A[0..n-1] Presorting-based algorithm: Stage 1 Sort the array by an efficient sorting algorithm Stage 2 Apply binary search Efficiency: Θ(nlog n) + O(log n) = Θ(nlog n) Good or bad? Why do we have our dictionaries, telephone directories, etc. sorted?

Element Uniqueness with presorting b Presorting-based algorithm Stage 1: sort by efficient sorting algorithm (e.g. mergesort) Stage 2: scan array to check pairs of adjacent elements Efficiency: Θ(nlog n) + O(n) = Θ(nlog n) b Brute force algorithm Compare all pairs of elements Efficiency: O(n 2 )

Instance simplification – Gaussian Elimination Given: A system of n linear equations in n unknowns with an arbitrary coefficient matrix. Transform to: An equivalent system of n linear equations in n unknowns with an upper triangular coefficient matrix. Solve the latter by substitutions starting with the last equation and moving up to the first one. a 11 x 1 + a 12 x 2 + … + a 1n x n = b 1 a 11 x 1 + a 12 x 2 + … + a 1n x n = b 1 a 21 x 1 + a 22 x 2 + … + a 2n x n = b 2 a 22 x 2 + … + a 2n x n = b 2 a n1 x 1 + a n2 x 2 + … + a nn x n = b n a nn x n = b n

Gaussian Elimination (cont.) The transformation is accomplished by a sequence of elementary operations on the system’s coefficient matrix (which don’t change the system’s solution): for i ←1 to n-1 do replace each of the subsequent rows (i.e., rows i+1, …, n) by a difference between that row and an appropriate multiple of the i-th row to make the new coefficient in the i-th column of that row 0

Example of Gaussian Elimination Solve 2x 1 - 4x 2 + x 3 = 6 3x 1 - x 2 + x 3 = 11 x 1 + x 2 - x 3 = -3 Gaussian elimination row2 – (3/2)*row / row3 – (1/2)*row /2 -6 row3–(3/5)*row / /5 -36/5 Backward substitution x 3 = (-36/5) / (-6/5) = 6 x 2 = (2+(1/2)*6) / 5 = 1 x 1 = (6 – 6 + 4*1)/2 = 2

Pseudocode and Efficiency of Gaussian Elimination Stage 1: Reduction to the upper-triangular matrix for i ← 1 to n-1 do for j ← i+1 to n do for k ← i to n+1 do A[j, k] ← A[j, k] - A[i, k] * A[j, i] / A[i, i] //improve! Stage 2: Backward substitution for j ← n downto 1 do t ← 0 for k ← j +1 to n do t ← t + A[j, k] * x[k] x[j] ← (A[j, n+1] - t) / A[j, j] Efficiency: Θ(n 3 ) + Θ(n 2 ) = Θ(n 3 ) Read the Pseudocode code for the algorithm and find its efficiency?