1、A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,1,Brute Force,A straightforward approach, usually based directly on the problems statement and definitions of the concepts involvedExamples:Compu
2、ting an (a 0, n a nonnegative integer)Computing n!Multiplying two matricesSearching for a key of a given value in a list,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,2,Brute-Force Sorting Al
3、gorithm,Selection Sort Scan the array to find its smallest element and swap it with the first element. Then, starting with the second element, scan the elements to the right of it to find the smallest among them and swap it with the second elements. Generally, on pass i (0 i n-2), find the smallest
4、element in Ain-1 and swap it with Ai: A0 . . . Ai-1 | Ai, . . . , Amin, . . ., An-1 in their final positionsExample: 7 3 2 5,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,3,Analysis of Select
5、ion Sort,Time efficiency:Space efficiency:Stability:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,4,Brute-Force String Matching,pattern: a string of m characters to search for text: a (longe
6、r) string of n characters to search in problem: find a substring in the text that matches the patternBrute-force algorithm Step 1 Align pattern at beginning of text Step 2 Moving from left to right, compare each character of pattern to the corresponding character in text until all characters are fou
7、nd to match (successful search); or a mismatch is detected Step 3 While pattern is not found and the text is not yet exhausted, realign pattern one position to the right and repeat Step 2,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Up
8、per Saddle River, NJ. All Rights Reserved.,5,Examples of Brute-Force String Matching,Pattern: 001011 Text: 10010101101001100101111010 Pattern: happy Text: It is never too late to have a happy childhood.,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Edu
9、cation, Inc. Upper Saddle River, NJ. All Rights Reserved.,6,Pseudocode and Efficiency,Efficiency:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,7,Brute-Force Polynomial Evaluation,Problem: Fi
10、nd the value of polynomialp(x) = anxn + an-1xn-1 + + a1x1 + a0 at a point x = x0Brute-force algorithmEfficiency:,p 0.0 for i n downto 0 dopower 1for j 1 to i do /compute xi power power xp p + ai power,return p,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pear
11、son Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,8,Polynomial Evaluation: Improvement,We can do better by evaluating from right to left:Better brute-force algorithm Efficiency:,p a0 power 1 for i 1 to n dopower power xp p + ai power return p,A. Levitin “Introduction to the Design & A
12、nalysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,9,Closest-Pair Problem,Find the two closest points in a set of n points (in the two-dimensional Cartesian plane).Brute-force algorithmCompute the distance between every pair of distinct p
13、ointsand return the indexes of the points for which the distance is the smallest.,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,10,Closest-Pair Brute-Force Algorithm (cont.),Efficiency: How t
14、o make it faster?,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,11,Brute-Force Strengths and Weaknesses,Strengths wide applicability simplicity yields reasonable algorithms for some important
15、 problems (e.g., matrix multiplication, sorting, searching, string matching) Weaknesses rarely yields efficient algorithms some brute-force algorithms are unacceptably slow not as constructive as some other design techniques,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed.,
16、Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,12,Exhaustive Search,A brute force solution to a problem involving search for an element with a special property, usually among combinatorial objects such as permutations, combinations, or subsets of a set.Method: genera
17、te a list of all potential solutions to the problem in a systematic manner (see algorithms in Sec. 5.4) evaluate potential solutions one by one, disqualifying infeasible ones and, for an optimization problem, keeping track of the best one found so far when search ends, announce the solution(s) found
18、,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,13,Example 1: Traveling Salesman Problem,Given n cities with known distances between each pair, find the shortest tour that passes through all t
19、he cities exactly once before returning to the starting city Alternatively: Find shortest Hamiltonian circuit in a weighted connected graph Example:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserv
20、ed.,14,TSP by Exhaustive Search,Tour Cost abcda 2+3+7+5 = 17 abdca 2+4+7+8 = 21 acbda 8+3+4+5 = 20 acdba 8+7+4+2 = 21 adbca 5+4+3+8 = 20 adcba 5+7+3+2 = 17More tours?Less tours?Efficiency:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. U
21、pper Saddle River, NJ. All Rights Reserved.,15,Example 2: Knapsack Problem,Given n items: weights: w1 w2 wn values: v1 v2 vn a knapsack of capacity W Find most valuable subset of the items that fit into the knapsackExample: Knapsack capacity W=16 item weight value2 $205 $3010 $505 $10,A. Levitin “In
22、troduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,16,Knapsack Problem by Exhaustive Search,Subset Total weight Total value1 2 $202 5 $303 10 $504 5 $101,2 7 $501,3 12 $701,4 7 $302,3 15 $802,4 10 $403,4 15 $60
23、1,2,3 17 not feasible1,2,4 12 $601,3,4 17 not feasible2,3,4 20 not feasible 1,2,3,4 22 not feasible,Efficiency:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,17,Example 3: The Assignment Prob
24、lem,There are n people who need to be assigned to n jobs, one person per job. The cost of assigning person i to job j is Ci,j. Find an assignment that minimizes the total cost.Job 0 Job 1 Job 2 Job 3 Person 0 9 2 7 8 Person 1 6 4 3 7 Person 2 5 8 1 8 Person 3 7 6 9 4Algorithmic Plan: Generate all le
25、gitimate assignments, compute their costs, and select the cheapest one. How many assignments are there? Pose the problem as the one about a cost matrix:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Re
26、served.,18,9 2 7 8 6 4 3 75 8 1 87 6 9 4 Assignment (col.#s) Total Cost 1, 2, 3, 4 9+4+1+4=181, 2, 4, 3 9+4+8+9=301, 3, 2, 4 9+3+8+4=241, 3, 4, 2 9+3+8+6=261, 4, 2, 3 9+7+8+9=331, 4, 3, 2 9+7+1+6=23etc. (For this particular instance, the optimal assignment can be found by exploiting the specific fea
27、tures of the number given. It is: ),Assignment Problem by Exhaustive Search,C =,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,19,Final Comments on Exhaustive Search,Exhaustive-search algorith
28、ms run in a realistic amount of time only on very small instances In some cases, there are much better alternatives! Euler circuits shortest paths minimum spanning tree assignment problemIn many cases, exhaustive search or its variation is the only known way to get exact solution,A. Levitin “Introdu
29、ction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,20,Graph Traversal Algorithms,Many problems require processing all graph vertices (and edges) in systematic fashionGraph traversal algorithms:Depth-first search (DF
30、S)Breadth-first search (BFS),A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,21,Depth-First Search (DFS),Visits graphs vertices by always moving away from last visited vertex to unvisited one,
31、backtracks if no adjacent unvisited vertex is available. Uses a stack a vertex is pushed onto the stack when its 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 “Redraws” graph in tree-like fashion (with tree ed
32、ges and back edges for undirected graph),A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,22,Pseudocode of DFS,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 20
33、12 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,23,Example: DFS traversal of undirected graph,DFS traversal stack:,DFS tree:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserv
34、ed.,24,Notes on DFS,DFS can be implemented with graphs represented as: adjacency matrices: (V2) adjacency lists: (|V|+|E|)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)Application
35、s: checking connectivity, finding connected components checking acyclicity finding articulation points and biconnected components searching state-space of problems for solution (AI),A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Sa
36、ddle River, NJ. All Rights Reserved.,25,Breadth-first search (BFS),Visits graph vertices by moving across to all the neighbors of last visited vertexInstead of a stack, BFS uses a queueSimilar to level-by-level tree traversal “Redraws” graph in tree-like fashion (with tree edges and cross edges for
37、undirected graph),A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,26,Pseudocode of BFS,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, I
38、nc. Upper Saddle River, NJ. All Rights Reserved.,27,Example of BFS traversal of undirected graph,BFS traversal queue:,BFS tree:,A. Levitin “Introduction to the Design & Analysis of Algorithms,” 3rd ed., Ch. 3 2012 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.,28,Notes on BFS,B
39、FS has same efficiency as DFS and can be implemented with graphs represented as: adjacency matrices: (V2) adjacency lists: (|V|+|E|)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,