0% found this document useful (0 votes)
24 views50 pages

CS2251 Daa

251 may june 2013-
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views50 pages

CS2251 Daa

251 may june 2013-
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 50
SEMESTER IV CS 2251 DESIGN AND ANALYSIS OF ALGORITHMS 3104 UNIT I 9 Algorithm Analysis — Time Space ‘Tradeoff — Asymptotic Notations — Conditional asymptotic notation — Removing condition from the conditional asymptotic notation - Properties of big-Oh notation ~ Recurrence equations ~ Solving recurrence equations Analysis of linear search, UNIT IT * Divide and Conquer: General Method — Binary Search — Finding Maximum and Minimum — Merge Sort ~ Greedy Algorithms: General Method ~ Container Loading Knapsack Problem. UNIT OT 9 Dynamic Programming: General Method — Multistage Graphs — All-Pair shortest paths — Optimal binary search trees — 0/1 Knapsack — Travelling salesperson problem . UNIT IV 9 Backtracking: General Method ~8 Queens problem — sum of subsets ~ graph coloring — Hamiltonian problem — knapsack problem, UNIT V 9 Graph Traversals — Connected Components — Spanning Trees — Biconnected components — Branch afd Bound: General Methods (FIFO & LC) — 0/1 Knapsack problem — Introduction to NP-Hard and NP-Completeness. TUTORIAL Total = 60 BOOK: 1. Ellis Horowitz, Sartaj Sahni and Sanguthevar Rajasekaran, Computer Algorithms! C++, Second Edition, Universities Press, 2007. (For Units II to V) 2. KS, Baswarakumar, Object Oriented Data Structures using C++, Vikas Publishing House pvt. Ltd., 2000 (For Unit 1) REFERENCES 1. T. H. Cormen, ©. E. Leiserson, RLRivest, and C, Stein, "Introduction to Algorithms", Second Edition, Prentice Hall of India Pvt. Ltd, 2003. 2. Alfred V. Aho, John E, Hopcroft and Jeffrey D. Ullman, "The Design and Analysis of Computer Algorithms", Pearson Education, 1999. UNIT-T PART-A 1, What is performance measurement? Ans: Performance measurement is concerned with obtaining the space and the time requirements of a particular algorithm, 2. What is an algorithm? Ans: An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In addition, all algorithms must satisfy the following criteria 1) input 2) Output 3) Definiteness 4) Finiteness 5) Effectiveness 3. Define Program, Ans: A program is the expression of an algorithm in a programming language. Sometimes works such as procedure, fiction and subroutine are used Synonymously program. 4. Write the For LOOP general format. Ans: ‘The general form of a for Loop is For variable : = value 1 to value 2 step Step do t = statement 1> 3 5. What is recursive algorithm? ‘Ans: Anvalgorithm is said to be recursive if the same algorithm is invoked in the body. An algorithm that calls itself is Direct recursive. Algorithm A is said to be indeed recursive if it calls another algorithm, which in tum calls A. 6. What is space complexity? ‘Ans: The space complexity of an algorithm is the amount of memory it needs to run to completion. 7. What is time complexity? Ans: ‘The time complexity of an algorithm is the amount of computer time it needs to run to completion. 8. Give the two major phases of performance evaluation Ans: Performance evaluation can be loosely divided into two major phases: (i) aprior estimates (performance analysis) (ii) a Posterior testing(performance measurement) 9. Define input size. Ans: The input size of any instance of a problem is defined to be the number of words(or the number of elements) needed to describe that instance. 10. Define best-case step count. ‘Ans: The best-case step count is the minimum number of steps that can be executed for the given parameters. 11. Define worst-case step count. Ans: The worst-case step count is the maximum number of steps that can be executed for the given parameters. 12. Define average step count. Ans: The average step count is the average number of steps executed an instances with the given parameters. 13. Define the asymptotic notation “Big oh” (0) Ans: The function f(n) ~ O(g(n)) iff there exist positive constants C and no such that {(n}£ C * g(n) for all n, n 5n0. 14. Define the asymptotic notation “Omega” (Q ). Ans: The function f(n) =W (g(n)) iff there exist positive constant C and no such that f(n) C * g(n) for all n,n nO. 14. Define the asymptotic f\notation “theta” ( ©) Ans:The function f(n) —LL] ((n)jff there exist positive constant C1, C2, and no such that Cl g(n)L] fn) 22 g(nfor all n, n 110, 16. Define Little “oh”. Ans: The funetion f(n) = 0(g(n)) iff Lim fn) = 0 n-LL ea) 17. Define Little Omega. Ans: The funetion fin) = TT.) (e(n)) Iff Lim f(n)=0 n-CDe@) 18. What are exponential grow#h functions? ‘The functions 2n and nt are exponential growth functions, because these two functions grow so fast that their values become astronomieally large even for rather smaller values of n. 19. What is worst-case efficieney? ‘The worst-case efficiency of an algorithm is its efficiency for the worst-case input of’sizen, which is an input or inputs of size n for whieh the algorithm runs the longest among all possible inputs of that size. 20. What is best ase efficiency? The best-case efficiency of an algorithm is its efficieney for the best-case input of size n, which is an input or inputs for which the algorithm runs the fastest among all possible inputs of that size 21. What is average case efficiency? ‘The average case efficiency of an algorithm is its efficiency for an average case input of size n. It provides information about an algorithm behavior on a “typical” or “random” input. PART -B 1.Give the properties of an algorit Ans: > Non Ambiguity Range of Input Multiplicity Speed Finiteness vyvyy 2. Discuss various issues in Writing an algorithm Ans Divise Algorithm, Validate Algorithm Analyse Algorithm Test a program > > > 3. Define Algorithm & what are the steps to write an Algorithm (or) Explai algorithm specification? Ans: Algorithm: ‘The collection of unambiguous instructions occurring in some specific sequence. Steps to write an Algorithm: “4 pscudo code conventions > Alg is the procedure consisting of heading and body.Heading consists of the keyword Algorithm,name of the Alg and parameter List. Syntax: Algorithm name (piip2 pn) Keyword name of the Alg parameters > Heading Section includes {iProblem description: Input: Output: Body of the Algorithm Compound statements should be enclosed within { and } brackets Single line comments are written using // as beginning of comment Identifier should begin by Letter not by a digit Using assignment opeffTOr assignment statement can be given Eg: Variabe— expression It also includes other operators such as Boolean Operators, Logical operators, Relational Operators etc Multidimensional arrays Looping Conditional statement Input and Output vvvvv v vvvY > Algorithm. 4. Explain all asymptotic notations? © Big Oh: ‘The function fn) = O(g(n)) iff there exist positive constants © and no such that fn) C * g(a) for all n, n Ch0. © Omega: ‘The function f(n) =W (g(n)) iff there exist positive constant C and no such that fn) C* g(n) for all n,n (LJ) n0. © Theta ‘The function fn) ~LL] (g(a)) iff there exist positive constant C1, C2, and no such that C1 g(n)CL] f(aLLJ C2 g(n) for all n,n Cho. « Little Oh The function f(n) = Og(n)) If Lim fn) =0 n-C1) g@) * Little omega ‘The function fn) = C1 (g()) If Lim g(n) = 0 n- CO) f(a) 5. Explain Performance analysis? Ans: 1, Space Complexity: ‘The space complexity of an algorithm. completion, algorithm using iterative funetion to fine sum of n numbers Algorithm sum(a.n) the amount of memory it needs to run to t S:=00 For i=1 ton do S:-S + alif; Retum S; 3 algorithm using Recursive function to fine sum of m numbers Algorithm Rsum (a.n) t If(_ 0) then Return 0.0; Else Return Rsum(a, n- 1) + a(n); $ 2. Time Complexity: The time complexity of an algorithm is the amount of computer time it needs to run to completion. 3. Asymptotic Notation: 4. Performance measurement: 5. Practical Complexities: UNIT IL PART -A 1. Write algorithm using iterative function to fine sum of n numbers. Ans: Algorithm sum(a.n) t $:=0.0 For i=1 to n do S$:-S +alif; Return S; } 2. Write an algorithm using Recursive function to fine sum of n numbers, Ans: Algorithm Rsum (a,n) t If{a_0) then Retum 0.0; Else Retum Rsum(a, n- 1) + a(n): 3. Define the divide an conquer method. Given a function to compute on ‘n” inputs the divide-and-comguer strategy suggests splitting the inputs in tok’ distinct susbsets, 1k Ch, yielding k’ subproblems. The subproblems must be solved, and then a method must be found to combine subsolutions into a solution of the whole. If the subproblems are still, relatively large, then the divide-and conquer strategy can possibly be reapplied. 4. Define control abstractio Ans: A control abstraction we mean a procedure whose flow of control is clear but whose primary operations are by other procedures whose precise meanings are left undefined, 5. Write the Control abstraction for Divide-and conquer. Ans: Algorithm DAnd(C)) t if small(p) then return S(); else t divide P into smaller instance QCD PCT k C0. Apply D and C to each of these subproblems Return'eombine (DAnd C(Q] 1) DAnd C(12) } } 6. What is the substitution method? Ans: One of the methods for solving any such recurrence relation is called the substitution method. 7. What is the binary search? ‘Ans: If “q’ is always chosen such that ‘aq’ is the middle element(that is, g-[(n+1)2), then the resulting search algorithm is known as binary search, 8. Give computing time for Bianry search? Ans: In conclusion we are now able completely describe the computing time of binary search by giving formulas that describe the best, average and worst cases. Successful searches Od) Alogn) ALogn) DAnd (Ok): best average worst unsuccessful searches Cidogn) best, average, worst 9. Define external path length? ‘Ans: The external path length F, is defines analogously as sum of the distance of all extemal nodes from the root. 10, Define internal path length. Ans: The internal path length ‘T from the root. 11, What is the maximum and minimum problem? Ans: The problem is to find the maximum and minimum items in a set of “n? elements. Though this problem may look so simple as to be contrived, it allows us to demonstrate divide-and-comquer in simple setting. 12. What is merge sort and give it’s time complexity? ‘Ans: In merge sort, the elements are to be sorted in non-decreasing order. Given a sequence of n elements i.e. a [1], 8 [2]... a [n}, the general idea is to imagine them split into 2 sets a [1], ...a [(02)] and a [(w/2) +1], ... a [n].Each set is individually sorted, and the resulting sorted sequence are merge to produce a single Sorted sequence of ‘n’elements, ‘The time complexity is O (nlogn) for worst case 13. State m—colorability decision problem, Ans: Let G be a graph and m be a given positive integer. We want to discover whether the nodes of G can be colored in such a way that no two adjacent nodes have the same color yet only m colors are used, 14.Define chromatic number of the grap! Ans: The m — colorability optimization problem asks for the smallest integer m for which the graph G can be colored, This integer is referred to as the chromatic number of the graph. 15, Define a planar graph. Ans: A graph is said t0 be planar iff it can be drawn in such a way that no two edges cross each other 16, What are NP- hard and Np-complete problems? ‘Ans: The problems whose solutions have computing times are bounded by polynomials of small degree. 17. What is a decision problem? Ans: Any problem for which the answer is either zero or one is called decision problem, 18, What is maxclique problem? ‘Ans: A maxclique problem is the optimization problrm that has to determine the size of a largest clique in Grapg G where clique is the maximal subgraph of a graph. 19. what is approximate solution? ‘Ans: A feasible solution with value close to the value of an optimal solution is called approximate solution. 20.Write a recursive algorithm for computing the nth fibonacci number? ALGORITHM F(n) / Computes the nth Fibonacci number recursively by using the definition ‘/ Input A non-negative integer n ‘/ Output The nth Fibonacci number ifn. the sum of the distances of all internal nodes Tetum n else retum F(n-1)+F(n-2) PART-B 1. Write the algorithm for finding the maximum and minimum and explain it? Ans: The problem is to find the maximum and minimum items in a set of n elements. Though this problem may look so simple as to be converted it allows us to demonstrate divide and conquer in simple setting, Iterative algorithm Algorithm straightmaxmin(a, t max:-min:=a[1]; forL=2tondo t iffaft}>max) then max:=a[T]; if{a[T] min1) then min: min1; 3 2. Explain the concept of mergesort? Ans: In merge sort the elements are to sorted in non decreasing order. Given a sequence of n elements that is a[1].a{2]....a[n] the general idea is to magine them split into 2 sets af ],a[2J,.....afn/2] and a[n/2]+1.......,afn}. each set is individually sorted and the resulting sorted sequence are merge to produce a single sorted sequence of n elements. The time complexity is O(n log n) for worst case, Insertion sort works exceedingly fast on arrays of less than 16 elements, though for large n its computing time is O(n2). The time complexity and space complexity of traveling salesperson problem is, > Time complexity is O (n2 2n). > Space complexity is O (n 2n). 3. Explain binary search method? Ans: If ‘q’ is always chosen such that ‘aq’ is the middle element(that is, q=[(n+1)2). then the resulting search algorithm is known as binary search. In conclusion we are now able completely describe the computing time of binary search by giving formulas that describe the best, average and worst cases. Algorithm binsearch(a.n.s) while(low-high) do t mid:=(low+high)/2: if{a[mid]) then low:= mid+1; else return mid; 3 return 0; 3 Successful searches, Ca) Dogan) DLogn) hest average worst unsuccessful Searches Cilogn) best, average, worst 4. Explain container loading. Container loading problems have been studied by a variety of different methods. Yet they are attracting more researchers’ attention now, mainly due to remarkable progress in distribution systems and automatizationin fieightage. A container loading problem requests us a procedure of locating objects that should be loaded into a container in which objects mean cartons, boxes, parcels, cases, bags and other types that can be handled as freights in general. Many studies on container loading are based on the formulations as optimization problems; the simplest formulation is a bin packing problem, which is known to be NP-hard [4]. However, another essential feature is knowledge in the loading. Experiences tell us that frequently knowledge for loading is more important than optimization, There’re various types of knowledge in actual container loading that makes the problem more complicated. Some knowledge belongs to the common sense; for example, stability of loaded objects is the most important aspect to be considered in practice. Others include strict regulations such as hazardous objects should be placed separately. Moreover there is expert knowledge that is not expressed explicitly. Thus the problem should be a mixture of such a knowledge system and an optimization system, How to mix these different characteristics is the most important point of the container loading problem, We begin with showing a list of different knowledge types in this problem. (i) Framework knowledge, ‘Commonsense knowledge, iii) Regulatory knowledge, ’) Expert knowledge. 5. Explain greedy algorithm. A greedy algorithm obtains an optimal solution to a problem bymaking a sequence of choices. At each decision point, the algorithm chooses the locally optimal solution. In other words, when we are considering which choice to make, we make the choice that looks best in the current situation, without considering results from sub problems. Problems solved optimally by greedy algorithms share some features with those problems solved optimally by dynamic programming algorithms: optimal substructure, recursive solutions.! UNIT - II PART -A 1. What is the Quick sort? Ans: n quicksort, the division into subarrays is made so that the sorted subarrays do not need to be merged later. 2. Write the Anlysis for the Quick sort. Ans: In analyzing QUICKSORT, we can only make the number of element comparisions o(n). It is easy to see that the frequency count of other operations is of the same order as C(n). 3. Is insertion sort better than the merge sort? Ans: Insertion sort works exceedingly fast on arrays of less then 16 elements, though for large “n’ its computing time is O(n2). 4. Write algorithm for straightforward maximum and minimum Ans: algorithm straight MaxMin(a.n,mas.min) //set max to the maximum and min to the minimum of a[ Ln] t max == min: fori=2tondo t if{afi] >max) then max: = afi]; if{ali] >min) then min: afi]; 5 3 5. Give the recurrence relation of divide-and-conquer? Ans:The recurrence relation is Tom) = gin) “Tonl) + T(n2) + + Tonk) + fn) 6. Write the algorithm for Iterative binary search? Ans: Algorithm BinSearch(a.n,s) /iGiven an array a{1:n] of elements in nondecreasing order, n>0, determine whether x is present t low :=1 high : =n; while (low < high) do t mid : = [(ow+high)’2]; iff CO] amid) then high else if (x Lla{mid]) then low else return mid; 3 retum 0; 5 7. What are internal nodes? Ans: ‘The circular node is called the intemal nodes. 8, Describe the recurrence relation off merge sort? Ans: If the time for the merging operation is proportional to n, then the computing time of merge sort is described by the recurrence relation n= 1,a> constant T(n)=a 27 (n/2) +n where n EJ ye> constant ‘9.What is meant by feasible solution? Ans:Given n inputs and we are required to form a subset such that it satisfies some given constraints then such a subset is called feasible solution. 10. Write any two characteristics of Greedy Algorithm? Ans: * ‘fo solve a problem in an optimal way construct the solution from given set of candidates * As the algorithm proceeds, two other sets get accumulated among this one set contains the candidates that have been already considered and chosen while the other set contains the candidates that have been considered but rejected. 11. Define optimal solution? Ans: A feasible solution either maximizes or minimizes the given objective function is called as optimal solution 12. What is Knapsack problem? ‘Ans:A bag or sack is given capacity n and n objects are given. Each object has weight wi and profit pi Fraction of object is considered as xi (Le) 0<=xi<=1 If fraction is 1 then entire object is put into sack. When we place this fraction into the sack we get wini and pixi. 13. Define weighted tree. ‘Ans:A directed binary tree for which each edge is labeled with a real number (weight) is called as weighted tree. 14, What is the use of TVSP? ‘Ans: In places where the loss exceeds the tolerance level boosters have to the placed. Given a network and loss tolerance level the tree vertex splitting problems is to determine an optimal placement of boosters, 15, What is the Greedy choice property? ‘Ans: * The first component is greedy choice property (ie.) a globally optimal solution can arrive at by making a locally optimal choice. * The choice made by greedy algorithm depends on choices made so far but it cannot depend on any future choices or on solution to the sub problem. * It progresses in top down fashion. 16. What is greedy method? Ans: Greedy method is the most important design technique, which makes a choice that looks best at that moment. A given “n’ inputs are required us to obtain a subset that satisfies some constraints that is the feasible solution. A greedy method suggests that one can device an algorithm that works in considering one input at a time. 17. What are the steps required to develop a greedy algorithm? Ans: * Determine the optimal substructure of the problem, * Develop a recursive solution. * Prove that at any stage of recursion one of the optimal choices is greedy choice. Thus it is always safe to make greedy choive. * Show that all but one of the sub problemas induced by having made the greedy choice are empty. * Develop a recursive algorithm and convert into iterative algorithm 18. What is activity selection problem? Ans: The ‘n” task will be given with starting time si and finishing time fi, Feasible solution is that the task should not overlap and optimal solution is that the task should be completed in minimunt number of machine set. 19, Write the specification of TVSP Ans; “Let T= (V, E, W) be a weighted directed binary tree where V> vertex set E> edge set W> weight function for the edge. W is more commonly denoted as w (ij) which is the weight of the edge < 20. Define forest. Ans: Collection of sub trees that are obtained when root node is eliminated is known as forest PART -B 1. Explain Jobsequencing with deadlines problem with example. Ans: We are given a set of n jobs. Associated with job I is an integer deadline di and profit pi > 0. For any job i the profit pi is eamed iff the job is completed by its deadline. To complete a job one has to process the job on a machine one unit of time. Only one machine is available for the processing jobs. A fesible solution for this problem is subsets Jof jobs such that each job in this subset can be completed by its deadline, The value of the feasible solution J is the sum of the profits of the jobs in J. An optimal solution is. a feasible solution with maximum value. Example : Let n=4, (p1-p2.p3.p4) = (100. 10,15.27) and (d1.d2,d3.44) = (2.1.2.1). Out of The feasible solution and its val ues the optimal one is (1,4) with value 127, Algorithm JS(dj.n) Algorithm Requires us to consider the job in nondecreasing order of pi’s. Computing time of this algorithm takes O(n2) time. 2. Define Multistage Graphs with forward approach. A Multistage graph G= (V,E) is a directed graph in which the vertices are partitioned into k>2 disjoint sets Vi, 1. the cost of the path from s to tis the sum of the costs of the edges in the path. The Multistage graph problem is the minimum cost path from s to t, Each set Vi defines a stage in the graph. Because of the constraints on E every path from s tot starts in stage 1 goes o stage 2 then to stage 3 then to stage 4 and so on and eventually terminates in stage K. In the forward approach we obtain cost(ij) = min fe(ul)+cost(i+1,D} Lévi+l D CBA), After recal culating the path length, he Keeps the new order if itis shorter asin the figure below with 6 towns (uote: the hometown, point 1, isnot counted). aN ~\ / a Le Ae le, 7 ™VIRXG Sty : 2B area For 60 towns, a loop is randomly opened more than once in every 50” attempts. If the salesman has a friend with an identical card deck, thea they can double their chances of opening a loop. They both lay oat the cards in the same order, then randomly select different sets of four cards to invert. Naturally, more friends werking ia parallel will continue to improve the odds. The figure below shows a rondomly generated path connecting 60 points Each iteration has 180 parallel inversion operations (i.c. friends), 60 of which are combined to make a new path. After about 1500 iterations, all loops have been opened, reducing the tour to 1/5 of the original length. See figure below. 5, Explain 0-1 Knapsack problem. 0-1 Rnapsack problem! Given items T = Tl, T2, T3, ..., Ta Giems you might want to camying your backpack) with associated weights wl, w2, ..., wn and benefit values b1, b2, ..., bu, how can we maximize the total benefit considering that we are subject to an absolute weight limit W?A brute-force solution to this problem is to enumerate all possible subsets of T and select the one with the highest total benefit from among all the subsets whose cumulative weight ist W. Algorithm 0-1 Knapsack! Input: Set T of n items, such that item i has positive benefit bi and positive integer weight wi and maximum total weight W. (assumes there is a global array B of length W-1 and that each element of B has an associated list that is initially empty). !Output: For w = 0, . W, maximum benefit B[w] of a subset of T with total weight w.! 0-1Knapsack(I,W) for i=0 to W do . Bi] = 0 fork =1 10 |T| do for w = W downto wk do if Bw — wk] + bk > Bp] then . Bw] = Blw — wk] + bk . listfw] = list [w — wk] +k eye ee UNIT - IV PART -A 1. What does Job sequencing with deadlines mean? Ans: * Given a set of ‘n’ jobs each job “i” has a deadline di such that di>=0 and a profit pi such that pi>=0, * For job ‘i’ profit pi is eared iff it is completed within deadline. * Processing the job on the machine is for Lunit of time. Only one machine is available. 2. Define post order traversal, Ans: The order in which the TVSP visits the nodes of the tree is called the post order traversal. 3. Write the formula to calculate delay and also write the condition in which the node gets splitted? Ans:To calculate delay d(u)-maxfd(v)+w(u, ¥)} ve c(u) ‘The condition in which the node gets splitted are: d(u)tw(u ,v)> 8 and also d(u) Ans: The network can tolerate the losses only up to a certain limit tolerance limit. 5. When is a task said to be late in a schedule? Ans:A task is said to be late in any schedule if it finishes after its deadline else a is early in a schedule. 6. Define feasible solution for TVSP. Ans:Given a weighted tree T(V.E. a feasible solution if d(T/X)<= 3 7. Define optimal solution for TVSP. Ans:An optimal solution is one in which the number of nodes in X W) and a tolerance limit 5 any subset X of V is 8. Write the general algorithm for Greedy method control abstraction. Ans: Algorithm Greedy (a, n) t solution=0; for i=1 10 n do t select(a): if feasible(solution .x) then solution-Union(solution ,x): } retum solution; $ 9. Define optimal solution for Job sequencing with deadlines. Ans: Feasible solution with maximum profit is op sequencing with deadlines. 10.Write the difference between the Greedy method and Dynamic programming. Ans: Greedy method 1.Only one sequence of decision is generated. 2.1t does not guarantee to give an optimal solution always Dynamic programming 1.Many number of decisions are generated. 2.11 definitely gives an optimal solution always. 11.Define dynamic programming. ‘Ans: Dynamic programming is an algorithm design method that can be used when a solution to the problem is viewed as the result of sequence of decisions. 12.What are the features of dynamic programming? Ans: * Optimal solutions to sub problems are retained so as to avoid recomputing theit value ‘* Decision sequences containing subsequences that are sub optimal are not considered. * It definitely gives the optimal solution always. 13.What are the drawbacks of dynamic programming? Ans Time and space requirements are high, since storage is needed for all level. © Optimality should be checked at all levels. 14.Write the general procedure of dynamic programming. Ans: ‘The development of dynamic programming algorithm can be broken into a sequence of 4 steps. 1. Characterize the structure of an optimal solution. 2. Recursively define the value of the optimal solution 3. Compute the value of an optimal solution in the bottom-up fashion. 4. Construct an optimal solution from the computed information. 15.Define principle of optimality. Ans: It states that an optimal sequence of decisions has the property that whenever the initial stage or decisions must constitute an optimal sequence with regard to stage mal_solution for Job resulting from the first decision. 16.Give an example of dynamic programming and explain. Ans: An example of dynamic programming is knapsack problem, The solution to the knapsack problem can be viewed as a result of sequence of decisions. We have to decide the value of xi for I Let Tji denote jth task of the ith job. Task Tj is to be performed on Pj number of processors where 1 Any task Tji must be assigned to the processor Pj > No processor can have more than one task assigned to it at any time. For any job I processing the task for j>1 cannot be started until T(j-i).i has been completed. A nonpreemptive schedule is a schedule in which the processing of a task on any processor is not terminated until the task is complete. A preemptive schedule is a schedule in which the processing of a task on any processor can be terminated before the task is completed. The finish time fi (S) of job i is the time at Which all tasks of job i have been completed in schedule 8.The finish time F(S) of schedule $ is given by F(S)=maxf{ fi (S)} I1 cannot be started until T(j-i),i has been completed. 4.Define nonpreemptive schedule. Ans: A nonpreemptive schedule is a schedule in which the processing of a task n any processor is not terminated until the task is complete. Define preemptive schedule. Ans: A preemptive schedule is a schedule in which the processing of a task on any processor can be terminated before the task is completed, 6.Define finish time Ans: The finish time fi (S) of job iis the time at which all tasks of job i have been completed in schedule 8. The finish time F(S) of schedule S is given by F(S)=max{ fi ($)} I< 7.Define mean flow time Ans: The mean flow time MFT (S) is defined to be] MFT (S)= 1 fi(S) nl 8.Define optimal finish time. Ans: Optimal finish time scheduling for a given set of tasks is a non preemptive schedule § for which F (S) is minimum over all non preemptive schedules 8. 9.Define preemptive optimal finish time. Ans: Preemptive optimal finish time scheduling for a given set of tasks is a preemptive schedule S for which F (8) is minimum over all preemptive schedules 8. 10, What are the requirements that are needed for performing Backtracking Ans: To solve any problem using backtracking, it requires that all the solutions satisfy a complex set of constraints. They are: i, Explicit constraints Implicit constraints Define explicit constraint. Ans: They are rules that restrict each xi to take on values only from a give set. ‘They depend on the particular instance I of the problem being solved. All tuples that, satisfy the explicit constraints define a possible solution space. 12. Define implicit constrain Ans: They are rules that determine which of the tuples in the solution space of 1 satisfy the criteria funetion. It deseribes the way in which the si must relate to each other. 13.Define state space tree, Ans: The tree organization of the solution space is referred to as state space tree. 14.Define state space of the problem. Ans: All the paths from the root of the organization tree to all the nodes is called as state space of the problem 15.Define answer states. Ans: Answer states are those solution states s for which the path from the root to s defines a tuple that is a member of the set of solutions of the problem. 16. What are static trees? ‘Ans: The tree organizatio solved are called as static tree. 17.What are dynamic trees? Ans: ‘The tree organizations those are independent of the problem instance being solved are called as static tree. 18.Define a live node. Ans: A node which has been generated and all of whose children have not yet been generated is called as a live node. 19. Define a E — node. Ans: E — node (or) node being expanded. Any live node whose children are currently being generated is called as a E — node. s that are independent of the problem instance being, 20.Define a dead node. Ans: Dead node is defined as a generated node, which is to be expanded further’ all of whose children have been generated. 21.,What are the factors that influence the efficiency of the backtracking algorithm? Ans: ‘The efficiency of the backtracking algorithm depends on the following four factors. They are: i, The time needed to generate the next xk ‘The number of xk satisfying the explicit constraints, i. The time for the bounding functions Bk iv. -The number of xk satisfying the Bk. 22.Define Branch-and-Bound method. Ans: The term Branch-and-Bound refers to all the state space methods in which all children of the E-node are generated before any other live node can become the Enode. 23. What are the searching techniques that are commonly used in Branch-and- Bound method. Ans: ‘The searching techniques that are commonly used in Branch-and-Bound method are: i, FIFO LIFO i. LC iv. Heuristic search 24,State 8 — Queens problem. Ans: The problem is to place eight queens on a & x 8 chessboard so that no two queen “attack” that is, so that no two of them are on the same row, column or on the diagonal. 25.State Sum of Subsets problem, Ans: Given n distinct positive numbers usually called as weights , the problem calls for finding all the combinations of these numbers whose sums are m. PART -B. 1. Explain branch and bound? Ans: ‘The term Branch-and-Bound refers to all the state space methods in which all children of the E-node are generated before any other live node can become the Enode. the searching techniques that are commonly used in Branch-and-Bound method. ‘The searching techniques that are commonly used in Branch-and-Bound method are i, LC search ii, 15 — puzzle problem iii. LC control abstraction iv. Bounding vy. FIFO branch and bound vi, LC branch and bound 2. What is knapsack problem? Expalin in deatail with alg. Ans: Given n objects and knwpsack or bag. Object I has a weight wi and the napsack has the capacity m. If a fraction xi O= no. ve constants C and no such that Sorting, searching, m problems. nerical, string matching, geometric, combinatorial, graph ‘The Efficiency of an algorithm is based on the parameter on which the input size depends upon. In most of the problems selection of such parameter is straight forward. For ex it will be the size of the list for a problem of sorting, searching, and similar problems. ‘The average case time complexity of linear search is Cavg(n)=P(n+1)'2 n(1-P), Cavg(n) is prob of successful search, Scan the array to find its smallest element and swap it with the first time with the 1 clement. Then starting with the 2"! element scan the entire list to find the smallest element and swap it with the second element. Continuing in this fashion to sort the entire list. L select an unvisited node V, visit it and treat as the current node 2find an unvisited neighbor of the current node, visit it, and make it the new current node. if there are more than one unvisited neighbors the n resolve the tie by following the alpha order. 3.if the current node has no unvisited neighbors, back track to its parent and make i a new current node, A.Repeat steps 2 & 3 5.Repeat steps 1 for the remait til no more nodes can be visited. ing nodes. Transform anél-conquer is the 4 alg design and problem solving strategy. ‘Transform aiid conquer is an alg strategy in which the problem is solved by applying transformations. There are three variations of this approach .1.instanee simplification, 2.representation change, 3.problem reduction, AW AVL tree is a binary tree in which the balance factor of every node which is defined as the difference between the heights of the node’s and right sub tree is either 0 o I or -1 {height of empty tree is -1). NO, backtracking always does not produce optimal solution. Branch and Bound is an alg design tech that enhances the idea of generating a state space tree with the idea of estimating the best value obtainable from a current node of the decision tree . if such an element is not superior to the best solution seen upto that point in the processing of node is eliminated from further considerations. 11. @) (i) Big Oh: The function {(n) = O(g(n)) iff there exist positive constants C and no such that (LIC *g(n) for all n,n, 00, Omega: ‘The function f{n) =W (g(n)) iff there exist positive constant C and no such that fn) © * g(n) for all n, n Cin. Theta The function fn) ~_L] (g(n)) iff there exist positive constant C1, C2, and no sueh that C1 g(n), fn) C2 gin) for all n, n CL) n0, Little Oh ‘The function fn) = O(g(m)) IF Lim fn) 0 n- Ogin) Little omega The function f(n) = (g(n)) If Lim g(n)=0 n= Lita) 11.) The problem is to find the maximum and minimum jtemis inva set of n elements Though this problem may look so simple as to. be converted it allows us to demonstrate divide and conquer in simple setting, Iterative algorithm Algorithm straightmaxmin(a.n,max. { max:-min:=a[1]; for :=2t0ndo t iffa[}>max) then max:=a[T]: if(a[]] min) then min:= min 1; 3 } 11. (b) + _ Algorithm for finding mean and variance: - Explanation for that algorithm - Analyse the Worst case, best case and average case 12. (a) - An algorithm is said to be recursive if the same algorithm.is invoked in the body. An algorithm that calls itself is Direct recursive. Algorithm A is said to be indeed reoursive if it calls another algorithm, which in turn calls A. = Recurrence equation of Fibonacci series = int fibnum¢int p) { if(p—1 | pO) retum(p); else return (fibnum(p-1)+fibnumi(p-2)): 3 12, (b)- Algorithm Visualization is Visualization of the abstractions that describe software. ~ Draw the diagrain related to this (Refer Anany Levitin for diagram ) - Conclude with the benefits of visualization 13.(a) — Briefly discuss about divide and conquer approach ~ Write algorithm for partitioning the array and quick sort - Explain how that algorithm works = Discuss about the best case, average case and worst case 13. (b) In merge sort the elements are to sorted in non decreasing order. Given a sequence of n elements that is af1].a[2]....a[n] the general idea is to magine them split into 2 sets af ],a{2])......aft/2] and afn’2}+1 in). each set is individually sorted and the resulting sorted sequence are merge to produce a single sorted sequence of n elements. The time complexity is O(n log n) for worst ease. Insertion sort works exceedingly fast on arrays of less than 16 elements, though for large n its computing time is O(n2). The time complexity and space complexity of traveling salesperson problem is, > Time complexity is O (n2 2n). > Space complexity is © (n 2n), 14, (a) - A greedy algorithm obtains an optimal solution to a problem by making sequence of choices. At each decision point, the algorithm chooses the locally optimal solution. In other words, when we are considering which choice to make, we make the choice that looks best in the current situation, without considering results from sub problems. Problems solved optimally by greedy algorithms share some features with those problems solved optimally by dynamic programming algorithms: optimal substructure, recursive solutions - Definition for minimum spanning tree = Algorithm for prim’s and Krushkal’s ~ Difference between Prim’s and Krushkal’s ~ Explain the graph in stepwise procedure by drawing graph and tabulation 14. (b) ~ Definition for single source shortest path algorithm = Write the algorithm for finding the single source shortest path = Explain the algorithm with graph and Tabulation 15. (a) - N-Queens Problems - The problem is to place N queens on aN x N chessboard so that no two queen “attack” that is, so that no two of them are on the same row, column or on the diagonal. ~ Algorithm for solving N-Queen problem ‘xplain some possible cases 15. (b) The term Branch-and-Bound refers to all the State space methods in which all children of the E-node are generated before any other live node can become the Enode. the searching techniques that aré commonly used in Branch-and-Bound method. ‘The searching techniques that are commonly-used in Branch-and-Bound method are: i. LC search ii. 15 — puzzle problem i. LC control abstraction iv. Bounding v. FIFO branch and bound vi LC branch and bound UNIVERSITY QUESTION PAPER B.E/ B.Tech. DEGREE EXAMINATION, NOVEMBER 2005. 04 SEMESTER SIGN AND ANALYSIS OF ALGORITHI 81201 - DI ‘Time: 3 Hrs Max.marks:100 PART A (Answer ALL questions) 10* 2-20 What are algorithm design techniques? How is an Algorithm’s time efficiency measured?” 1 2. 3. Mention any four classes of algorithm efficiency. 4, What is algorithm visualization? 5. Write any four examples for Brute force approach, Give the time efficiency and drawback of merge sot algorithm. 6. 7. What is mathematical modeling’ 8. What is pre-structuring? Give examples. 9. State the principles of backtracking? 10. How is accuracy of approximation algorithm measured? PART B 5716-80 11. (i) Explain the necessary steps for analyzing efficieney of recursive algorithm with example. (OR) i) What is empirical analysis of an algorithm? Discuss its strength and weakness? 12. (j) Describe the steps in analyzing and coding an algorithm. (OR) Gi) Discuss the fundamentals of analysis framework and notations Used in algorithm design. 13. @) Explain Quick sort algorithm with suitable example. (OR) (i) Give a suitable example and explain the Breadth first search And Depth first search algorithms. 14, (i) Define AVL tree, Explain the construction sequence of AVL tree with a simple example. (OR) (ii) Define spanning tree. Discuss the design steps in Prim’s construct minimum spanning, tree with an ex. Algorithm to 15.(i) Explain Subset sum problem and discuss the possible solution strategies using backtracking, (OR) Gil) Discuss the solution for Traveling salesman problem using Branch and bound techniques. TWO MARKS ANSWER 1, The techniques that are used to devise and formulate a feasible solution to a problem are known as algorithm designs techniques. 2. The time(t) taken by an algorithm(a) is the sum of the compile time and the execution time, The compile time does not depend on the instance characteristic. ‘The runtime denoted by (Ta) takes into consideration of the input size of the problem, 3. CLASS NAME COMMENT L constant short of best case efficiencies. N linear alg that scans list of size n belonging to this class Nlogn —n-logen many divide and conquer alg..including merge sort and quick sort nt Factorial typical for alg, That generate all permutations of an n-element set 4, Algorithm Visualization is Visualization of the abstractions that describe software. 5. * The 8 Gueens problem The Graph closing problem ©The Hamiltonian Circuit problem ©The Knapsack problem * The Subset Sum problem 6. The Time efficiency of merge sort algorithm is Tn-O(nlog2n).One main drawback of merge sort is that it requires large auxiliary area. 7. A mathematical model is an abstract model that uses mathematical language to describe the behavior of a system, 8. Pre-structuring is the 2™' type of tech. That exploits space for time tradeoffs that uses extra space to facilitate a faster and/or more flexible access to that data. 9. Backtracking algorithms determine problem solutions by the component at a time and to use modified criterion function called bounding functions to test whether the vector being formed has any chance of success. 10. t he accuracy of approx alg S, to a problem minimizing some function fean be quantified by size of the relative error of the approximation. 18s) f{S,)/f(S*) PART B_ANSWER! IL) 1. Space Complexity The space complexity of an algorithm is the amount of memory it needs to runito completion, algorithm using Recursive function to fine sum of n numbers Algorithm Rsum (a.n) t If(a_ 0) then Return 0.0; Else Retum Rsum(a, n- 1) + a(n): 3 2. Time Complexity The time complexity of an algorithm isthe amount of computer time it needs to run to completion 3. Asymptotic Notation 4, Performance measurement 5. Practical Complexities (ii) Refer page no. 84 of Anany Levitin 12 (i) Algorithm: The collection of unambiguous instructions occurring in some specific sequence, Steps to write an Algorithm: pseudo code conventions > Algis the procedure consisting of heading and body.Heading consists of the keyword Algorithm,name of the Alg and parameter List. Syntax: Algorithm name (p1,p2. pn) {feats t Keyword name of the Alg _ parameters Heading Section includes {/Problem description: Input: Output > Body of the Algorithm > Compound statements should be enclosed within { and } brackets > Single line comments are written using // as beginning of comment > Identifier should begin by Letter not by a digit > Using assignment operttor _ assignment statement can be given Eg: Varitbte expression > Italso includes other operators such as Boolean Operators, Logical operators, Relational Operators ete. Multidimensional arrays Looping Conditional statement Input and Output. Algorithm vvVVY 12. Gi) Refer page no. 42 of Anany Levitin 13.(i) — _ Briefly discuss about divide and conquer approach = Write algorithm for partitioning the array and quick sort - Explain how that algorithm works - Discuss about the best case, average case andl worst case 13. (ii) Algorithm for DFS:- Set the starting point of traversal and push it inside the stack Pop the stack and add the popped vertex to the list of visited vertices Find the adjacent vertices for the most recently visited vertex( from the Adjacency Matrix) Step-4: Push these adjacent vertices inside the stack (in the increasing order of their depth) if they are not visited and not there in the stack already Step-5: Go to step-2 if the stack is not empty Algorithm for BR: Step-1: Set the starting point of traversal and add it inside the queue Step-2: Find the adjacent vertices for the starting vertex( from the Adjacency Matrix) Stop-3: add these adjacent vertices inside the queue if they are not visited Step-4: Go to step-2 if the queue is not empty 14) - Definition of AVL Tree and Balancing Factor - Algorithm for Single Rotation - Algorithm for double Rotation - Show these Rotations with an example 14 Gi) .- A minimum spanning tree (MST) ot minimum wei; then a spanning tree with weight less than or equal to the w spanning tree. More generally, any undirected graph (not necessarily connected) has a minimum spanning forest. which is a union of minimum spanning trees for its -onnected component num spanning tree - prim’s Algorithm for MST ~ Explain the graph in stepwise procedure by drawing graph and tabulation 15. (i) - Given n distinct positive numbers usually called as weights , the problem calls for finding all the combinations of these numbers whose sums are m, To solve any problem using backtracking, it requires that all the solutions satisfy a complex set of constraints, They are: i. Explicit constraints. iv. Implicit constraints. ‘They are rules that restrict each xi to take on values only from a give set. They depend on the particular instance I of the problem being solved. All tuples that satisfy the explicit constraints define a possible solution space. They are rules that. determine which of the tuples in the solution space of I satisfy the criteria function. It describes the way in which the xi must relate to each other. 15. (ii) The term Branch-and-Bound refers to all the state space methods in which all children of the E-node are generated before any other live node can become the Enode. the searching techniques that are commonly used in Branch-and-Bound method. ‘The searching techniques that are commonly used in Branch-and-Bound method are: i, LC search 15 — puzzle problem ii. LC control abstraction: y. Bounding v. FIFO branch and bound vi. LC branch and bound UNIVERSITY QUESTION PAPER B.E/ B.Tech. DEGREE EXAMINATION, NOVI 04 SEMESTER CS1201 — DESIGN AND ANALYSIS OF ALGORITHMS. ABER 2008. Time: 3 Hrs, Max. marks:100 PART A (Answer ALL questions) 10* 2=20 1. Define an algorithm 2. Design an algorithm for checking whether the given word is Palindrome or not ie. , Whether the word is the same even when reversed Eg MADAM is a palindrome. 3. List out the steps for empirical analysis of algorithm efficiency 4, What is the significance of Fibonacei number of sequence? 5. Give an example problem that cannot be solved by a Brute-Force attack. 6. Write a PSEUDOCODE for a divide and conquer algorithm for finding the position of the largest element in an array of n numbers. 7. Define a heap. 8. Give the Pseudo code of the Warshall’s Algorithm. 9. When do you terminate the search path in a state-space tree of a branch and bound algorithm? 10, Define a Knapsack Problem, PART B 5*16-80 11. (a) (i) Elaborate the various asymptotic metrics used to evaluate the efficiency of the algorithm. (ii) Use the most appropriate notation to indicate the time efficiency class of a sequential search (1) Inworst case (2) In the best case © (3) In the average case (or) (b) Specify the Euclid algorithm, the consecutive integer checking algorithm and the middle school algorithm for computing the GCD of two integer numbers. Which of them is simpler? Which is more efficient? Why? 12. (a) Consider the following Algorithm: ALGORITHM Seeret(A(0...it-1]) {/ INPUT: An array A[0.in-1] of n real numbers Minval€ A[0]) Maxval€a[0]: Mo nl do If Afi]= minval Minval © Afi}; Ie Afi}> maxval maxval © Afi]: retum maxval-minval; @ What does this algorithm Compute? (ii) What is the Basic operation? ii) How many times is the basic operation computed? (iv) What is the efficiency class of this algorithm? w Suggest an improvement or a better algorithm altogether and indicate the efficiency class . If you cant do in , prove that in fact it Cant be done. (or) ve algoritm for computing the sum of the 1* n cubes (b) Consider the following ree S(n)=12 +234... tn’: ALGORITHM S(n) W/V : A +ve integer n; 1/ olp: The sum of the first n cubes. Ifn==1 return 1 Else return S(n-1) + n®n%n (Set up and solve a recurrence relation for the number of the algorithm basic operation is executed. (Gi) How does the algorithm compared with the straight forward non-recursive algorithm for computing this function? 13. (a) (i) Describe the Quick sort algorithm. Gii) Apply QUICK sort to sort the list E.X,A.M.P.L.E in alphabetical order. Draw the tree of the recursive calls made. (or) (b) Compare and contrast the Depth First Search and Breadth Fi algorithms. How do they fit into the Decrease and Conquer stiategy? t Search 14. (a) (i) Deseribe the Prim’s Algorithm for finding the minimum cost spanning tree. (ii) Apply the Prim’s Algorithm to the following graph: (b) For each of the following lists , construct an AVL tree by inserting their elements successfully , starting with an empty tree @12.3.4,5.6 (i) 6.5,4.3,2.1 (ii 15. (a) Using Backtracking enumerate how can you solve the following problems: 8-Queens Problem (ii) Hamiltonian circuit problem (or) (b) (i)_ solve the following instances of the knapsack problem by branch and bound technique ITEM, WEIGHT VALUES 1 10 S100 2 7 863 3 g $56 4 4 si2 W=l6 (ii) Give an ex for the best case input for the branch and bound algorithm for the assignment probler (iii) In The best case , how many nodes will be in the state space tree of the branch and bound algorithm for the assignment problem TWO MARK ANSWERS: 1 10, An algorithm is a sequence of unambiguous instructions for solving a problem, i.e, for obtaining a required output for any legitimate input in finite amount of time. Input: The string Output: Result is palindrome or not Gets(string) Strepy(stringup, string) Strrev(stringup) Diff-stremp(string stringup) i, Understand the purpose of experiment of given algorithm ii. Decide the efficiency metric M . also decide the measurement unit i. Decide on characteristics of the input iv. Create a program for implementing the algorithm v. Generate a sample of input ‘vi. Run the algorithm for some set of input sample vii, Analyze the resultant data This series can be obtained by following formula f{n)=f(n-1)Hf(n-2) where n>1 Linear search , merge sort Divide: Partition array into two sub lists $1and $2 with n/2 elements each ‘Conquer: Then find the maximum number of sub lists $1 and sub list $2 Combine: Compare $1 result and $2 result retur maximum number Heap is a complete binary:tree or a almost complete binary tree in which every parent node be either greater (or) lesser than its child nodes, Input: The adjacency matrix A of a diagram with a vertices Output: The transitive closure of the graph ROCA fork€ 1161do for i110 n do for j€ ton do ROQIERE- DIL] Retuim Rn) When we got m same column then we will terminate the search. mum values from each column and no value selected is under A bag or sack is given capacity n and n objects are given. Each object has weight wi and profit pi Fraction of object is considered as xi (i.e) 0°=xi<=1 .If fraction is 1 then entire object is put into sack. When we place this fraction into the sack we get wini and pixi, PART B ANSWERS 11.(a) (i) Big Oh: The function f{n) = O(g(n)) iff there exist positive constants © and no such that f@)COIC * g(a) for all n,n, n0. Omega: ‘The function f(n) =W (g(n)) iff there exist positive constant C and no such that fin) C * g(n) for all n, n C)n0. + Theta ‘The function f(n) —L] (g(a) iff there exist positive con: C1 g(n), fn) C2 gin) for all n, n CL) n0, Little Oh ‘The function fin) = O(g(n)) If Lim fin) 0 n= Ogi) Little omega The function fin) =(g(m)) If Lim g(n)=0 =D) a) — Definition for sequential search- It compares given element with all the elements in an array - Algorithm for sequential search - Briefly explain about efficiency class for sequetitial search t C1, C2, and no suth that 11.(b) Refer page no. 5 of Anany Levitin 12 (a) (i) Comput Git) Comparison num and maximum element in an array (iv) Explain about Best case, average case and worst case -y to improve this algorithm for better performance 12 (b) (i) Refer page no, 61 of Anany Levitin (ii) Refer page no. 69 of Anany Levitin 13. (@) Briefly discuss about divide and conquer approach ~ Write algorithm for partitioning the array and quick sort - Explain how that algorithm works = _ Discuss about the best case, average case and worst ease 13. (b) Algorithm for DES:- Step-I: Set the starting point of traversal and push it inside the stack Step-2: Pop the stack and add the popped vertex to the list of visited vertices Step-3: Find the adjacent vertices for the most recently visited vertex( from the Adjacency Matrix) Step-4: Push these adjacent vertices inside the stack (in the increasing order of their depth) if they are not visited and not there in the stack already Step-5: Go to step-2 if the stack is not empty igorithm for BS: Step-I: Set the starting point of traversal and add it inside the queue Step-2: Find the adjacent vertices for the starting vertex( from the Adjaceney Matrix) Step-3: add these adjacent vertices inside the queue if they are not visited Step-4: Go to step-2 if the queue is not empty 14 (a). - A minimum spanning tree (MS‘T) or minimum weight spanning tree is then a spanning tree with weight less than or equal to the weight of every other spanning tree. More generally, any undirected graph (not necessarily connected) has a minimum spanning forest, which is a union of minimum spanning trees for its ~ Definition for minimum spanning tree prim’s Algorithm for MST - Explain the graph in stepwise procedure by drawing graph and tabulation 14 (b) - Definition of AVL Tree and Balancing Factor - Algorithm for Single Rotation - Algorithm for double Rotation - Show these Rotations with an example 15. (a) Backtracking is used to solve problems with tree structures. Even problems seemingly remote to trees such as a walking a maze are actually trees when the decision "back-lefi-straight-right’ is considered a node in a tree. (i) - 8-Queens Problems - The problem is to place & queens on a8 x 8 chessboard so that no two queen “attack” that is, so that no two of them are on the same row, column or on the diagonal. ~ Algorithm for solving 8-Queen problem - Explain some possible cases (ii) A Hamiltonian path or traceable path is a path that visits each vertex exactly once. A graph that contains a Hamiltonian path is called a traceable graph. A. graph is Hamilton-connected if for every pair of vertices there is a Hamiltonian path between the two vertices. A Hamiltonian cycle, Hamiltonian circuit, vertex tour or graph cycle is a cvcle that visits each vertex exactly once (except the vertex which is both the start and end, and so is visited twice). A graph that contains a Hamiltonian cycle is called a Hamiltonian graph. Similar notions may be defined for directed graphs, where each edge (arc) of a path or cycle can only be traced in a single direction 15. (b) (The term Branch-and-Bound refers to all the state space methods in which all children of the B-node are generated before any other live node can become the Enode, the searching techniques that are commonly used in Branch-and-Bound method. ‘The searching techniques that are commonly used in Branch-and-Bound method are: i, LC search ii, 15 — puzzle problem iii, LC control abstraction iv. Bounding vy. FIFO branch and bound vi. LC branch and bound (ii) Given n objects and a knapsack or bag. Object I has a weight wi and the knapsack has the capacity m. If a fraction xi O) Define Spanning tree. Discuss the design steps in Kruskal’s algorithm to construct minimum spanning tree with an eg, 15.(a) _ Explain subset sum problem and discuss the possible solution strategies using Backtracking. (or) (b) Discuss the solution for Knapsack problem using Branch and Bound Technique. ‘Two marks answ: 1. In the early days of computing the dominant vehicle for specifying algorithm was a flowchart, a method of expressing an algorithm by a collection of connected geometric shapes containing descriptions of the algorithm’s steps 2. There are two kinds of efficiency: time efficiency and space efficiency. Time efficiency indicates how fast an algorithm in question runs; space efficiency deals with the extra space the algorithm requires. 3. Let T(n) be an eventually nondecreasing function and f(n)be a smooth, function. If Tin) ¢ O(f{n)) for values of n that are powers of where b>=2, then Tin)e@(fin)) 4, Algorithm Visualisation is Visualisation of the abstractions that describe sofiware. 5. Let f{n) be the number of comparisons required to sort the given n number using bubble sort. Then f(n) = sum of comparisons required in each sean For i= 1 we required n-1 comparison For i=2 we required n-2 comparison For i=n-1 we required n comparison Therefore f(n) = (n-1)Hn-2)s, : (oe n/2=(ar"-ny/2, =O(0') (order of n°) ‘Computing time = O(n") 6. It is the answer we should have fully expected: Since the algorithm simply reduces the size of the Remiaining array by about half an each iteration, the number of such iteration néeded to reduce the initial size n to the final size 1 has to be about logon ‘The logarithmic function grows so slowly that its values remain small even for every large values of n 241 7. A mathematical model is an abstract model that uses mathematical language to describe the behaviour of a system. 8 Prestructuring is the 2™' type of tech. That exploits space for time tradeoffs that uses extra space to fascilitate a faster and/or more flexible access to that data. 9. A heuristics is a common — sense rule drawn from experience rather than from a mathematically proved assertion. 10. The accuracy of approx alg S, to a problem minimizing some function f.can be quantified by size of the relative error of the approximation. 1(S,) = f(S,)/(S*) Important problem types are Sorting Searching, String Processing Graph problem Combinatorial Problems Geometric Problems Numerical Problems(Refer page no 19 of Anany Levitin) (ii) A general plan for empirical analysis of algorithm efficiency: 1. Understand the experiment’s purpose 2. Decide on the efficiency metrie M to be measured and the measurement unit Decide on characteristics of the input sample 3 4. Prepare a program iniplementing the algorithm for the experimentation 5. Generate a sample of inputs 6. Run. the algorithm on the sample’s inputs and record the data observed 7. Analyze the data obtained(Refer page no 85 from Anany Levitin) 11. (b) (i) Analysis Framework: Measuring an input’s size “Unit for measuring running time + Order of growth -Worst-case, Best-case and Average case Efficiencies (ii) Big Oh: The fumetion f(n) = O(g(n)) iff there exist positive constants © and no such that f(a) LIC * g(n) for all n,n, n0. Omega: The function f{n) =W (g(n)) iff there exist positive constant C and no such that fin) © * g(n) for all n, n Cn0, Theta ‘The function f(n) ~CL] (g(n)) iff there exist positive constant C1, C2, and no such that C1 g(n), f(n) C2 g(n) for all n, nT] n0, Little Oh The function f(n) = O(g(n)) If Lim f{n)=0 n- gin) Little omega The function f(n) =(g(n)) ff Lim g(n)= 0 n- Din) 12.(a) ()General Plan for Analyzing efficiency of Non recursive Algorithm: -Decide on a parameter indicating an input’s size Identify the algorithm’s basic operation ~ Cheek whether the number of times the basic operation is executed depends only on the size of an input. ~ Set up a sum expressing the number of times the algorithm’s basic operation is executed. = Using standard formulas and rules of sum Manipulation (ii) Refer Page no 66 from Anany Levitin (b) Refer Page no 69 from Anany Levitin 13. @) — — Defi elements in an array ~ Algorithm for sequential search - Briefly explain about efficiency class for'sequential search 13.(b) Algorithm for DFS:- jon for sequential search- It compares. given element with all the Step-1: Set the starting point of traversal and push it inside the stack Step-2: Pop the stack and add the popped vertex to the list of visited vertices Step-3: Find the adjacent vertices for the most recently visited vertex( from the Adjaceney Matrix) Step-4: Push these adjacent vertices inside the stack (in the increasing order of their depth) if they are not visited and not there in the stack already Step-5: Go to step-2 if the stack is not empty 14, (a) (i) Heap -A. heap can be defined as a binary tree with keys assigned to its nodes provided the following ivo conditions are met 1. the binary tree is essentially complete 2. The Key at each node is greater than or equal to the Keys at its children ass (ii) Refer Page no 219 from Anany Levitin (b) A minimum spanning tree (MST) or minimum weight spanning tree is then a spanning tree with weight less than or equal to the weight of every other spanning tree. More generally, any undirected graph (not necessarily connected) has a minimum spanning forest, which is a union of minimum spanning trees for its connected components ~ Definition for minimum spa - prim’s Algorithm for MST - Explain the graph in stepwise procedure by drawing graph and tabulation ing tree 15.(a) The subset sum problem is a good introduction to the NP-complete class of problems, There are two reasons for this + Itisad nd not an optimization problem + Ithas a very simple formal definition and problem statement Although the subset sum problem is a decision problem, the cases when an approximate solution is sufficient have also been studied, in the field of approximations algorithms; 15, (b) (i)The term Branch-and-Bound refers to all the state space methods in which all children of the E-node are generated before any other live node can become the Enode. the searching techniques that are commonly used in Branch-and-Bound method. ‘The searching techniques that are commonly used in Branch-and-Bound method are: i. LC search ii. 15 — puzzle problem iii, LC control abstraction iv. Bounding v. FIFO branch and bound vi LC branch and bound (ii) Given n objects and a knapsack or bag. Object I has a weight wi and the knapsack has the capacity m, If a fraction xi O

You might also like