Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials."— Presentation transcript:

1 Introduction to Algorithms Rabie A. Ramadan rabie@rabieramadan.org http://www. rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials

2 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.

3 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. 0 2 1 3 4 6 5

4 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 )

5 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

6 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 )

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

8 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

9 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)

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

11 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 1 2 3 4 5 6 7

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

13 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=2 1 5 3 4 0 1 2 3 4=b 5 6 7 T is lower tangent if all the points are above the line

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

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

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

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

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

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

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

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

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

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

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

25 25 Merging two convex hulls.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

44 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

45 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.

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

47 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

48 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

49 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?

50 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

51 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)

52 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?

53 Algorithm for DFS

54 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. 12 54 6 3 7 8

55 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)

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

57 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.

58 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. 1 3 26 475 8

59 Write an Algorithm for BFS Using a queue?

60 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

61 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.

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

63 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.

64 Example Complexity: as DFS

65 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.

66 Example

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

68 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

69 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

70 Example of Russian Peasant Multiplication Compute 20 * 26 n m 20 26 10 52 5 104 104 2 208 + 1 416 416 520

71 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?

72 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

73 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)

74 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.

75 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]

76 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

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

78 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

79 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

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

81 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)

82 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.

83 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).

84 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?

85 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 )

86 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

87 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

88 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 2 -4 1 6 2 -4 1 6 3 -1 1 11 row2 – (3/2)*row1 0 5 -1/2 2 1 1 -1 -3 row3 – (1/2)*row1 0 3 -3/2 -6 row3–(3/5)*row2 2 -4 1 6 0 5 -1/2 2 0 0 -6/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

89 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?


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

Similar presentations


Ads by Google