73
JEPPIAAR ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING SEMESTER IV CS 2251 DESIGN AND ANALYSIS OF ALGORITHMS 3 1 0 4 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 II 9 Divide and Conquer: General Method – Binary Search – Finding Maximum and Minimum – Merge Sort – Greedy Algorithms: General Method – Container Loading – Knapsack Problem. UNIT III 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

CS2251-DAA

Embed Size (px)

Citation preview

Page 1: CS2251-DAA

JEPPIAAR ENGINEERING COLLEGEDEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SEMESTER IV CS 2251 DESIGN AND ANALYSIS OF ALGORITHMS 3 1 0 4

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

Divide and Conquer: General Method – Binary Search – Finding Maximum and Minimum – Merge Sort – Greedy Algorithms: General Method – Container Loading – Knapsack Problem.

UNIT III 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 and Bound: General Methods (FIFO & LC) – 0/1 Knapsack problem – Introduction to NP-Hard and NP-Completeness.

TUTORIAL = 15 Total = 60

TEXT BOOK:

1. Ellis Horowitz, Sartaj Sahni and Sanguthevar Rajasekaran, Computer Algorithms/ C++, Second Edition, Universities Press, 2007. (For Units II to V)

2. K.S. Easwarakumar, Object Oriented Data Structures using C++, Vikas Publishing House pvt. Ltd., 2000 (For Unit I)

REFERENCES:

Page 2: CS2251-DAA

1. T. H. Cormen, C. E. Leiserson, R.L.Rivest, 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-IPART – 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 aparticular task. In addition, all algorithms must satisfy the following criteria:1) input2) Output3) Definiteness4) Finiteness5) Effectiveness.3. Define Program.

Ans: A program is the expression of an algorithm in a programming language.Sometimes works such as procedure, function and subroutine are usedSynonymously program.4. Write the For LOOP general format.

Ans: The general form of a for Loop isFor variable : = value 1 to value 2 stepStep do<statement 1><statement n >5. What is recursive algorithm?

Ans: An algorithm is said to be recursive if the same algorithm is invoked in thebody. An algorithm that calls itself is Direct recursive. Algorithm A is said to beindeed recursive if it calls another algorithm, which in turn calls A.6. What is space complexity?

Ans: The space complexity of an algorithm is the amount of memory it needs torun to completion.7. What is time complexity?

Ans: The time complexity of an algorithm is the amount of computer time itneeds 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) a prior 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

Page 3: CS2251-DAA

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 beexecuted for the given parameters.11. Define worst-case step count.

Ans: The worst-case step count is the maximum number of steps that can beexecuted for the given parameters.12. Define average step count.

Ans: The average step count is the average number of steps executed aninstances 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 suchthat f(n)£ C * g(n) for all n, n ³n0.14. Define the asymptotic notation “Omega” ( Ω ).

Ans:The function f(n) =W (g(n)) iff there exist positive constant C and nosuch that f(n) C * g(n) for all n, n ³ n0.15. Define the asymptotic t\notation “theta” ( Ѳ)

Ans:The function f(n) =(g(n)) iff there exist positive constant C1, C2, and nosuch that C1 g(n)f(n) C2 g(n) for all n, n 0.16. Define Little “oh”.

Ans: The function f(n) = 0(g(n))iffLim f(n) = 0n - g(n)

17. Define Little Omega.Ans: The function f(n) = (g(n))Iff Lim f(n) = 0n - g(n)

18.What are exponential growth functions?

The functions 2n and n! are exponential growth functions, because these two functions grow so fast that their values become astronomically large even for rather smaller values of n.

19. What is worst-case efficiency?

The worst-case efficiency of an algorithm is its efficiency for the worst-case input of size n, which is an input or inputs of size n for which the algorithm runs the longest among all possible inputs of that size.

20. What is best-case efficiency?

The best-case efficiency of an algorithm is its efficiency 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.

Page 4: CS2251-DAA

PART – B

1.Give the properties of an algorithmAns:

Non Ambiguity Range of Input Multiplicity Speed Finiteness

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) Explain algorithm specification?Ans: Algorithm:

The collection of unambiguous instructions occurring in some specific sequence.Steps to write an Algorithm:

pseudo 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 (p1,p2…………………..pn)

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 operator assignment statement can be given

Eg: Variable expression It also includes other operators such as Boolean Operators, Logical operators,

Relational Operators etc. Multidimensional arrays Looping Conditional statement Input and Output.

Page 5: CS2251-DAA

Algorithm.

4. Explain all asymptotic notations?Ans:

Big Oh:The function f(n) = O(g(n)) iff there exist positive constants C and no such

that f(n)C * 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 f(n) C * g(n) for all n, n n0.

ThetaThe function f(n) =(g(n)) iff there exist positive constant C1, C2, and nosuch that C1 g(n)f(n) C2 g(n) for all n, n n0.

Little OhThe function f(n) = 0(g(n))Iff Lim f(n) = 0 n - g(n) Little omegaThe function f(n) = (g(n))Iff Lim g(n) = 0 n - f(n)

5. Explain Performance analysis?Ans: 1. Space Complexity:The space complexity of an algorithm is the amount of memory it needs to run tocompletion.algorithm using iterative function to fine sum of n numbersAlgorithm sum(a,n)S : = 0.0For i=1 to n doS : - S + a[i];Return S;algorithm using Recursive function to fine sum of n numbersAlgorithm Rsum (a,n)If(n_ 0) thenReturn 0.0;ElseReturn Rsum(a, n- 1) + a(n);2. Time Complexity:The time complexity of an algorithm is the amount of computer time itneeds to run to completion.3. Asymptotic Notation:4. Performance measurement:5. Practical Complexities:

UNIT -II

Page 6: CS2251-DAA

PART - A1. Write algorithm using iterative function to fine sum of n numbers.Ans: Algorithm sum(a,n)

S : = 0.0For i=1 to n doS : - S + a[i];Return S;

2. Write an algorithm using Recursive function to fine sum of n numbers,Ans: Algorithm Rsum (a,n)

If(n_ 0) thenReturn 0.0;ElseReturn Rsum(a, n- 1) + a(n);

3. Define the divide an conquer method. Given a function to compute on ‘n’ inputs the divide-and-comquer strategy suggests splitting the inputs in to’k’ distinct susbsets, 1k n, 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 stillrelatively large, then the divide-and conquer strategy can possibly be reapplied.4. Define control abstraction.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()

if small(p) then return S();elsedivide P into smaller instance 12k k 1Apply D and C to each of these subproblemsReturn combine (DAnd C( 1) DAnd C( 2),----, DAnd (( k));

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, q=[(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

(1) (logn) (Logn)best average worst

Page 7: CS2251-DAA

unsuccessful searches(logn) best, average, worst

9. Define external path length?Ans: The external path length E, is defines analogously as sum of the distance

of all external nodes from the root.10. Define internal path length.

Ans: The internal path length ‘I’ is the sum of the distances of all internal nodesfrom 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], a [2]…. a [n], the general idea is to imagine them split into 2 sets a [1], …a [(n/2)] and a [(n/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 discoverwhether the nodes of G can be colored in such a way that no two adjacent nodeshave the same color yet only m colors are used.14.Define chromatic number of the graph.

Ans: The m – colorability optimization problem asks for the smallest integer mfor which the graph G can be colored. This integer is referred to as the chromaticnumber of the graph.15. Define a planar graph.

Ans: A graph is said to be planar iff it can be drawn in such a way that no twoedges cross each other.16. What are NP- hard and Np-complete problems?

Ans: The problems whose solutions have computing times are bounded bypolynomials of small degree.17. What is a decision problem?

Ans: Any problem for which the answer is either zero or one is called decisionproblem.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 if n . 1 return n

Page 8: CS2251-DAA

else return F(n-1)+F(n-2)

PART – B1. 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 todemonstrate divide and conquer in simple setting.Iterative algorithmAlgorithm straightmaxmin(a,n,max,min)max:=min:=a[1];for I:= 2 to n doif(a[I]>max) then max:=a[I];if(a[I]<min) then min := a[I];Recursive algorithmAlgorithm maxmin(I,j,max,min)if(I==j) then max:=min:=a[I];else if (I=j-1) thenif(a[I]<a[j]) thenmax:=a[j];min:=a[I];elsemax:=a[I];min:=a[j];elsemid:=(I+j)/2;maxmin(I,mid,max,min);maxmin(mid+1,j,max1,min1);if ( max< max1) then max:= max1;if(min > min1) then min:= min1;

2. Explain the concept of mergesort?Ans:

In merge sort the elements are to sorted in non decreasing order. Given asequence of n elements that is a[1],a[2]….a[n] the general idea is to magine themsplit into 2 sets a[1],a[2],…..a[n/2] and a[n/2]+1,……,a[n]. each set isindividually sorted and the resulting sorted sequence are merge to produce a

Page 9: CS2251-DAA

single sorted sequence of n elements. The time complexity is O(n log n) for worstcase.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 ofbinary search by giving formulas that describe the best, average and worst cases.Algorithm binsearch(a,n,x)low:=1;high:=n;while(low<high) domid:=(low+high)/2;if(x<a[mid]) thenhigh:= mid-1;else if(x>a[mid]) thenlow:= mid+1;elsereturn mid;return 0;Successful searches(1) (logn) (Logn)best average worstunsuccessful searches(logn)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 freightage. 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

Page 10: CS2251-DAA

the problem more complicated. Some knowledge belongs to the common sense; for example, stabilityof 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,(ii) Commonsense knowledge,(iii) Regulatory knowledge,(iv) 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 – III

PART - A1. 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 c(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 a algorithm for straightforward maximum and minimum

Ans: algorithm straight MaxMin(a,n,max,min)//set max to the maximum and min to the minimum of a[1:n]max := min: = a[i];for i = 2 to n doif(a[i] >max) then max: = a[i];if(a[i] >min) then min: = a[i];

Page 11: CS2251-DAA

5. Give the recurrence relation of divide-and-conquer?Ans:The recurrence relation isT(n) = g(n)T(n1) + T(n2) + ----+ T(nk) + f(n)

6. Write the algorithm for Iterative binary search?Ans: Algorithm BinSearch(a,n,x)//Given an array a[1:n] of elements in nondecreasing order, n>0, determine

whether x is presentlow : = 1;high : = n;while (low < high) domid : = [(low+high)/2];if(x a[mid]) then high:= mid-1;else if (x a[mid]) then low:=mid + 1;else return mid;return 0;

7. What are internal nodes?Ans: The circular node is called the internal nodes.

8. Describe the recurrence relation ofr 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 relationn = 1, a constantT(n) = a2T (n/2) + n where n 1, c 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: * To 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 solution12. 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 (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 wixi and pixi.

Page 12: CS2251-DAA

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 (i.e.) 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 stages 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 choice.* Show that all but one of the sub problems induced by having made the greedychoice are empty.* Develop a recursive algorithm and convert into iterative algorithm18. What is activity selection problem?

Ans: The ‘n’ task will be given with starting time si and finishing time fi. Feasiblesolution is that the task should not overlap and optimal solution is that the task shouldbe completed in minimum number of machine set.

19. Write the specification of TVSPAns: Let T= (V, E, W) be a weighted directed binary tree where

V vertex setE edge setW weight function for the edge.W is more commonly denoted as w (i,j) which is the weight of the edge <i,j> _ E.20. Define forest.

Ans: Collection of sub trees that are obtained when root node is eliminated is known as forest

Page 13: CS2251-DAA

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 earned 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 J of 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,d4) = (2,1,2,1). Out ofThe feasible solution and its val ues the optimal one is (1,4) with value 127.Algorithm JS(d,j,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<i<k. In addition if <u,v> is an edge in E then u belongs to Vi and V belongs to Vi+1 for some I, 1<i<K. The srts V1 and Vk are such that |v1|=|vk| =1. The vertex s is the source and t the sink. Let c(I,j) be the cost of edge <I,j>. the cost of the path from s to t is the sum of the costs of the edges in the path. TheMultistage 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 to t 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 obtaincost(i,j) = minc(j,l)+cost(i+1,l)l €vi+1<j,l>€ EAlgorithm F graph(G,k,n,p)Time taken is O(|V| + |E|) where V is set of vertices and E is set of edges.3. Give the Bellman ford algorithm for Single source shortest path.Ans:To find the single source shortest Path we use Dynamic programming strategy. It must be cyclefree shortest path to obtain an algorithm to determine a shortest path from a source vertex to all remaining vertices in the graph. When negative edge lengths are permitted we require thet the graph have no cycles of negative length. Let dist[u] be the length of a shortest path from the source vertex v to vertex u under the constraint that the shortest path contains at most L edges. We make three observations and from it we bring the following

Distk[u] = min distk-1 [u], min distk-1 [i] + cost [i,u].Time taken is O(n3).

3. ExplainTravelling salesman problem.

The traditional lines of attack for the NP-hard problems are the following:

Page 14: CS2251-DAA

1. Devising algorithms for finding exact solutions (they will work reasonably fast only for relatively small problem sizes).2. Devising "suboptimal" or heuristic algorithms, i.e., algorithms that deliver either seemingly or probably good solutions, but which could not be proved to be optimal.3. Finding special cases for the problem ("sub problems") for which either better or exact heuristics are possible.

As a graph problem

Computing a solution

Using inversion instead, the salesman starts with the shuffled cards laid out in front of him. First, he calculates the path length. Then he randomly picks four contiguous cards and inverts their order (i.e. A B C D -> D C B A). After recalculating the path length, he keeps the new order if it is shorter as in the figure below with 6 towns (note: the hometown, point 1, is not counted).

For 60 towns, a loop is randomly opened more than once in every 602 attempts. If the salesman has a friend with an identical card deck, then they can double their chances of opening a loop. They both lay out the cards in the same order, then randomly select different sets of four cards to invert. Naturally, more friends working in parallel will continue to improve the odds. The figure below shows a randomly generated path connecting 60 points.Each iteration has 180 parallel inversion operations (i.e. 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 Knapsack problem!Given items T = T1, T2, T3, ..., Tn (items you might want to carrying your backpack) with associated weights w1, w2, … , wn and benefit values b1, b2, …, bn, how can we

Page 15: CS2251-DAA

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 totalbenefit from among all the subsets whose cumulative weight is! 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(T,W)1. for i = 0 to W do2. B[i] = 03. for k = 1 to |T| do4. for w = W downto wk do5. if B[w – wk] + bk > B[w] then6. B[w] = B[w – wk] + bk7. list[w] = list [w – wk] +k

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 earned iff it is completed within deadline.* Processing the job on the machine is for 1unit 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 thenode gets splitted?

Ans:To calculate delayd(u)=maxd(v)+w(u, v)v _ c(u)The condition in which the node gets splitted are:

d(u)+w(u ,v)> δ and also d(u) is set to zero.4. What is meant by tolerance level?

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 task is early in a schedule.6. Define feasible solution for TVSP.

Ans:Given a weighted tree T(V,E,W) and a tolerance limit δ any subset X of V is a feasible solution if d(T/X)<= δ7. Define optimal solution for TVSP.

Ans:An optimal solution is one in which the number of nodes in X is minimized.

Page 16: CS2251-DAA

8. Write the general algorithm for Greedy method control abstraction.Ans: Algorithm Greedy (a, n)solution=0;for i=1 to n dox= select(a);if feasible(solution ,x) thensolution=Union(solution ,x);return solution;

9. Define optimal solution for Job sequencing with deadlines.Ans: Feasible solution with maximum profit is optimal solution for Job

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.It does not guarantee to give an optimal solution always.Dynamic programming1.Many number of decisions are generated.2.It 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 their

values. 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 asequence 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 stageresulting from the first decision.

Page 17: CS2251-DAA

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 1<i<n. First we make a decision on x1 and then on x2 and so on. An optimal sequence of decisions maximizes the object function pi xi.17.Write about optimal merge pattern problem.

Ans: Two files x1 and x2 containing m & n records could be merged together to obtain one merged file. When more than 2 files are to be merged together. The merge can be accomplished by repeatedly merging the files in pairs. An optimal merge pattern tells which pair of files should be merged at each step. An optimal sequence is a least cost sequence.18.Explain any one method of finding the shortest path.

Ans: One way of finding a shortest path from vertex i to j in a directed graph G is to decide which vertex should be the second, which is the third, which is the fourth, and so on, until vertex j is reached. An optimal sequence of decisions is one that results in a path of least length.19.Define 0/1 knapsack problem.

Ans: The solution to the knapsack problem can be viewed as a result of sequence of decisions. We have to decide the value of xi. xi is restricted to have the value 0 or 1 and by using the function knap(l, j, y) we can represent the problem as maximum pi xisubject to wi xi < y where l - iteration, j - number of objects, y – capacity.20.What is the formula to calculate optimal solution in 0/1 knapsack problem?

Ans: The formula to calculate optimal solution is g0(m)=maxg1, g1(m-w1)+p1.21.Write about traveling salesperson problem.

Ans: Let g = (V, E) be a directed. The tour of G is a directed simple cycle that includes every vertex in V. The cost of a tour is the sum of the cost of the edges on the tour. The traveling salesperson problem to find a tour of minimum cost.22.Write some applications of traveling salesperson problem.Ans:

Routing a postal van to pick up mail from boxes located at n different sites. Using a robot arm to tighten the nuts on some piece of machinery on an

assembly line. Production environment in which several commodities are manufactured onthe same set of machines.

PART – B

1. Explain subset sum problem. The subset sum problem is a good introduction to the NP-complete class of problems. There are two reasons for this

It is a decision and not an optimization problem It has 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; one algorithm for the approximate version of the subset sum problem is given below.

Page 18: CS2251-DAA

A solution that has a ±1% precision is good enough for many physical problems. However, the number of place values in the problem is essentially equivalent to the number of simultaneous constraints that need to be solved. A numerical precision of 1% is approximately 0.000012%, or 7 binary places (any numerical error after that is less than 1⁄128 of the first digit). However, if there are 100 binary place values in the problem, solving just 7 of them amounts to solving only 7% of the constraints. Moreover, given that the volume of the solution space in this case would be 2100, and you have only covered a volume of 27, then there is still a solution space of 293 left uncovered. In this way, a solution with a 1% numerical precision has covered essentially none of the real problem. The only way that a solution to the subset sum problem can be used as a solution to other NP problems is to solve all of the problem (and all of the constraints) exactly.In cryptography, it is actually important to solve real subset sum problems exactly. The subset sum problem comes up when a codebreaker attempts, given a message and ciphertext, to deduce the secret key. A key that is not equal to but within ±1% of the real key is essentially useless for the codebreaker due to the avalanche effect, which causes very similar keys to produce very different results.

2. Short note on flow shop scheduling?Ans:The processing of jobs requires the performance of several distinct job. In flowshop we have n jobs each requiring n tasks i.e. T1i, T2i,…...Tmi, 1<i<n. The conditions of flow shop scheduling are

Let Tji denote jth task of the ith job. Task Tij is to be performed on Pj number of processors where 1<j<m i.e. number of processors will be equal to number of task

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 S.The finish time F(S) of schedule S is given by F(S)=max fi (S) 1<i<nThe mean flow time MFT (S) is defined to be MFT (S) = 1 fi(S) n 1<i<n

Optimal finish time scheduling for a given set of tasks is a non preemptive schedule S for which F (S) is minimum over all nonpreemptive schedules S.

Preemptive optimal finish time scheduling for a given set of tasks is a preemptive schedule S for which F (S) is minimum over all preemptive schedules S.

3. Explain backtracking with example?To solve any problem using backtracking, it requires that all the solutionssatisfy a complex set of constraints. They are:iii. 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

Page 19: CS2251-DAA

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.The tree organization of the solution space is referred to as state space tree.

Example:-The problem is to place eight queens on a 8 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.4. Explain Hamiltonian circuit problem. 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 cycle 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 (i.e., the vertices are connected with arrows and the edges traced "tail-to-head").A Hamiltonian decomposition is an edge decomposition of a graph into Hamiltonian circuits.Any Hamiltonian cycle can be converted to a Hamiltonian path by removing one of its edges, but a Hamiltonian path can be extended to Hamiltonian cycle only if its endpoints are adjacent.The line graph of a Hamiltonian graph is Eulerian. The line graph of an Eulerian graph is Hamiltonian.A tournament (with more than 2 vertices) is Hamiltonian if and only if it is strongly connected.A Hamiltonian cycle may be used as the basis of a zero-knowledge proof.Number of different Hamiltonian cycles for a complete graph = (n-1)! / 2.Number of different Hamiltonian cycles for a complete Digraph = (n-1)!.5. Explain generally about Backtracking. 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-left-straight-right' is considered a node in a tree.

AimsBacktracking is the approach to find a path in a tree. There are serveraldifferent aims to be achieved :

just a path all paths the shortest path

depending on the algorithm and the problem, 'just a path' is the first solution. The shortest path can only be determined when all paths are known, hence the order of the listing. Implementation considerationsThe implementation bases on recursion. Each step has to be reverseable,hence the state has to be saved somehow. There are two approaches to savethe state :

as full state on the stack as reversable action on the stack

While the former is simpler it uses more stack. The later may be preferred for bigger problems. Consider a game with 100x100 places. To mark the visited places as array

Page 20: CS2251-DAA

takes 10k booleans per step. The most unfortunate solution, where all places have to be visited has 10k steps with 10k booleans each as state, therefore using 100M booleans on the stack with the first approach. The later uses several orders of magnitude less stack when just saving the positionImplementationAs usual in a recursion, the recursive function has to contain all the knowledge.The standard implementaion is :

1. check if the goal is achievedREPEAT

2. check if the next step is possible at all3. check if the next step leads to a known position - prevent circles4. do this next step

UNIT – VPART - A

1.Give the time complexity and space complexity of traveling salesperson problem.

Ans: Time complexity is O (n2 2n). Space complexity is O (n 2n).

2.Define flow shop scheduling.Ans: The processing of jobs requires the performance of several distinct job. In flow shop we have n jobs each requiring n tasks i.e. T1i, T2i,…...Tmi, 1<i<n.

3.What are the conditions of flow shop scheduling?Ans: Let Tji denote jth task of the ith job. Task Tij is to be performed on Pj number of processors where 1<j<m i.e. number of processors will be equal to number of task 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.

4.Define nonpreemptive schedule.Ans: A nonpreemptive schedule is a schedule in which the processing of a task

on any processor is not terminated until the task is complete.5. 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 timeAns: The finish time fi (S) of job i is the time at which all tasks of job i have

been completed in schedule S.The finish time F(S) of schedule S is given by F(S)=max fi (S) 1<i<n

Page 21: CS2251-DAA

7.Define mean flow timeAns: The mean flow time MFT (S) is defined to be]

MFT (S) = 1 fi(S) n 1<i<n8.Define optimal finish time.

Ans: Optimal finish time scheduling for a given set of tasks is a non preemptive schedule S for which F (S) is minimum over all non preemptive schedules S.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 (S) is minimum over all preemptive schedules S.10. What are the requirements that are needed for performing Backtracking?

Ans: To solve any problem using backtracking, it requires that all the solutionssatisfy a complex set of constraints. They are:i. Explicit constraints.ii. Implicit constraints.11.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 constraint.

Ans: 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.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 problem15.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 organizations that are independent of the problem instance being

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

Page 22: CS2251-DAA

algorithm?Ans:

The efficiency of the backtracking algorithm depends on the followingfour factors. They are:i. The time needed to generate the next xkii. The number of xk satisfying the explicit constraints.iii. The time for the bounding functions Bkiv. -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. FIFOii. LIFOiii. LCiv. Heuristic search24.State 8 – Queens problem.

Ans: The problem is to place eight queens on a 8 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 - B1. 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-Boundmethod are:i. LC searchii. 15 – puzzle problemiii. LC control abstractioniv. Boundingv. FIFO branch and boundvi. LC branch and bound

2. What is knapsack problem? Expalin in deatail with alg.Ans:

Page 23: CS2251-DAA

Given n objects and a knwpsack or bag. Object I has a weight wi and the knapsack has the capacity m. If a fraction xi 0<xi<1 of object i is placed in to knapsack then a profit of pixi earned. The objective is to obtain a filling of the knapsack that maximizes the total profit earned. Since the knapsack capacity is m, we rewuire the total weight of all chosdn objects to be atmost m.

Formally the problem can be stated asMaximize ∑pixi 1<i<n subject to ∑ wixi <= m 1<i<n and 0<xi<1, 1<i<n. The profits and weights are positive numbers.Algorithm Greedyknapsack(m,n) Needs the objects are considered in order of the ratio pi/wi. Disregarding the time to initially sort the objects each of the three strategy outlined above requires O(n) times.Example: The problem n=3, m= 20 (p1,p2,p3) = (25,24,15) and (w1, w2,w3) = (18,15,10) . Out of the feasible solutions the optimal solution is (0, 1, ½ ) which gives thevalue 31.5.3. Define Biconnected components and DFS.Ans:

A Graph G is biconnected if and only if it contains no articulatin point. A vertex V ina graph is said to be an articulation point if and only if the deletion of vertex v together with all its edges incident to v disconnects the graph into to two or more non-empty components.. A maximal biconeected component is biconnected graph. The graph G can be transformed into a biconnected graph by using the adge additionscheme.For each articulation point a dolet B1, B2,.. BK be the biconnected components containing vertex a.le vi, vi != a be the vertec in IAdd to G the edges (vi, vi+1 )Doing DFS gives DFN numbers to the nodes. From it the L value is found. Calculations and methods are devised to find the articulation point and then the edge connection is made to make it biconnected.The time taken for TVS is O(n)time.4. Explain Spanning Tree . Given a connected, undirected graph, a spanning tree of that graph is a subgraph which is a tree and connects all the vertices together. A single graph can have many different spanning trees. We can also assign a weight to each edge, which is a number representing how unfavorable it is, and use this to assign a weight to a spanning tree by computing the sum of the weights of the edges in that spanning tree. 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.

Page 24: CS2251-DAA

The minimum spanning tree of a planar graph. Each edge is labeled with its weight, which here is roughly proportional to its length.Minimum-cost subgraphIf the weights are non-negative, then a minimum spanning tree is in fact the minimum-cost subgraph connecting all vertices, since subgraphs containing cycles necessarily have more total weight.Cycle propertyFor any cycle C in the graph, if the weight of an edge e of C is larger than the weights of other edges of C, then this edge cannot belong to an MST. Assuming the contrary, i.e. that e belongs to an MST T1, then deleting e will break T1 into two subtrees with the two ends of e in different subtrees. The remainder of C reconnects the subtrees, hence there is an edge f of C with ends in different subtrees, i.e., it reconnects the subtrees into a tree T2 with weight less than that of T1, because the weight of f is less than the weight of e.Cut propertyFor any cut C in the graph, if the weight of an edge e of C is smaller than the weights of other edges of C, then this edge belongs to all MSTs of the graph. Indeed, assume the contrary, i.e., e does not belong to an MST T1. Then adding e to T1 will produce a cycle, which must have another edge e2 from T1 in the cut C. Replacing e2 with e would produce a tree T1 of smaller weight.AlgorithmThe first algorithm for finding a minimum spanning tree was developed by Czech scientist Otakar Borůvka in 1926 (see Borůvka's algorithm). Its purpose was an efficient electrical coverage of Moravia. There are now two algorithms commonly used, Prim's algorithm and Kruskal's algorithm. All three are greedy algorithms that run in polynomial time, so the problem of finding such trees is in FP, and related decision problems such as determining whether a particular edge is in the MST or determining if the minimum total weight exceeds a certain value are in P. Another greedy algorithm not as commonly used is the reverse-delete algorithm, which is the reverse of Kruskal's algorithm.The problem can also be approached in a distributed manner. If each node is considered a computer and no node knows anything except its own connected links, one can still calculate the distributed minimum spanning tree.

Page 25: CS2251-DAA

5. Explain about DFS Graph traversal technique.Here, the starting point can be any vertex and the next vertex to be visited is decided by the traversal you choose. If you choose the DFS, the next vertex to be visited will be the adjacent vertex (to the starting point), which has the highest depth value(??????...look at the graph below) and then the next adjacent vertex with the next higher depth value and so on till all the adjacent nodes for that vertex are not visited. We repeat this same procedure for every visited vertex of the graph.Well, I got to explain this with the help of a graph - If V1 is the starting point of my traversal then, as you can see - V2, V3 and V8 are its adjacent vertices and so in the Adjacency List of V1. Now, I am suppose to visit these vertices, but as this is DFS, I should visit V8 first and then V2 and V3. So, to keep track of which vertex to be visited next, we make use of a STACK, which holds these vertex values in the DFS order. Let's see the algorithm...Algorithm:-Step-1: Set the starting point of traversal and push it inside the stackStep-2: Pop the stack and add the popped vertex to the list of visited verticesStep-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 alreadyStep-5: Go to step-2 if the stack is not empty

UNIVERSITY QUESTIONS

CS1201-Design and analysis of algorithms Fourth semester APRIL/MAY - 2008Part - A [each carry 2 marks] 1. Define Big oh notation2. Enumerate some important types of problem3. How will you measure input size of algorithms4. what is the average case complexity of linear search algorithm5. Write the procedure for selection sort6. Define depth first searching technique7. what is the fundamental philosophy of transform and conquer method8. what is AVL tree9. State if backtracking always produces optimal solution10. Explain briefly branch and bound technique for solving problems

Page 26: CS2251-DAA

Part - B 11.(a) (i) Define the asymptotic notations used for best case average case and worst case analysis of algorithms(ii) Write an algorithm for finding maximum element of an array , perform best , worst and average case complexity with appropriate order notations.

(or)(b) Write an algorithm to find mean and variance of an array perform best, worst and average case complexity, defining the notations used for each type of analysis.

12. (a) Derive the recurrence equation for Fibonacci series. Perform Complexity analysis for the same.

(or)(b) Explain in detail, the techniques for algorithm visualization.

13. (a) Explain in detail quick sorting method. Provide a complete analysis of quick sort. //see Anany Levitin book

(or)(b) Explain in detail merge sort. illustrate the algorithm with a numeric example. Provide complete analysis of the same. // see Anany Levitin book

14 (a) Apply Prim's Algorithm and Kruskal algorithm to the graph to obtain minimum spanning tree. Dothese algorithms generate same output – Justify // see Anany Levitin book (or)(b) Solve the following instance of the single-source shortest paths problem with vertex a as the source.// see anany levitin book for graph. Write the algorithm for the above problem

15. (a) Explain N-queens problem with an algorithm. Explain why backtracking is defined as a default procedure of last resort for solving problems. (or) (b) job 1 job 2 job 3 job 4

a 9 2 7 8b 6 4 3 7 c 5 8 1 8d 7 6 9 4Consider the above matrix for assignment problem involving persons and jobs. Explain in detail howbranch and bound technique is useful is solving assignment problems

Page 27: CS2251-DAA

TWO MARKS ANSWER:1. The function f(n)=O(g(n)) iff there exists positive constants C and no such that

f(n)<=c*g(n) for all n, n>= no.

2. Sorting, searching, numerical, string matching, geometric, combinatorial, graph problems.

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

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

5. Scan the array to find its smallest element and swap it with the first time with the 1st element. Then starting with the 2nd 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.

6. 1.select an unvisited node V, visit it and treat as the current node

2.find 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 it a new current node.

4.Repeat steps 2 & 3 until no more nodes can be visited.

5.Repeat steps 1 for the remaining nodes.

7. Transform and conquer is the 4th alg design and problem solving strategy. Transform and conquer is an alg strategy in which the problem is solved by applying transformations. There are three variations of this approach .1.instance simplification, 2.representation change, 3.problem reduction.

8. An 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 or 1 or -1.(height of empty tree is -1).

9. NO, backtracking always does not produce optimal solution.

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

Page 28: CS2251-DAA

Part –B

11. (a) (i) Big Oh:The function f(n) = O(g(n)) iff there exist positive constants C and no such that f(n)C * 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 f(n) C * g(n) for all n, n n0.Theta The function f(n) =(g(n)) iff there exist positive constant C1, C2, and no such that C1 g(n), f(n) C2 g(n) for all n, n n0.Little Oh

The function f(n) = 0(g(n)) Iff Lim f(n) = 0 n - g(n)Little omega The function f(n) = (g(n)) Iff Lim g(n) = 0 n - f(n)

11.(ii)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 algorithmAlgorithm straightmaxmin(a,n,max,min)max:=min:=a[1];for I:= 2 to n doif(a[I]>max) then max:=a[I];if(a[I]<min) then min := a[I];Recursive algorithmAlgorithm maxmin(I,j,max,min)if(I==j) then max:=min:=a[I];else if (I=j-1) thenif(a[I]<a[j]) thenmax:=a[j];min:=a[I];elsemax:=a[I];min:=a[j];else

Page 29: CS2251-DAA

mid:=(I+j)/2;maxmin(I,mid,max,min);maxmin(mid+1,j,max1,min1);if ( max< max1) then max:= max1;if(min > min1) then min:= min1;

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 recursive if it calls another algorithm, which in turn calls A.

- Recurrence equation of Fibonacci series- int fibnum(int p)

if(p==1 || p==0 ) return(p);else return (fibnum(p-1)+fibnum(p-2));

12. (b) - Algorithm Visualization is Visualization of the abstractions that describe software. - Draw the diagram 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 a[1],a[2]….a[n] the general idea is to magine them split into 2 sets a[1],a[2],…..a[n/2] and a[n/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(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).

14. (a) - A greedy algorithm obtains an optimal solution to a problem by making a sequence of choices. At each decision point, the algorithm chooses the locally optimal

Page 30: CS2251-DAA

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 a N 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 - Explain 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 are commonly used in Branch-and-Bound method.The searching techniques that are commonly used in Branch-and-Boundmethod are:i. LC searchii. 15 – puzzle problemiii. LC control abstractioniv. Boundingv. FIFO branch and boundvi. LC branch and bound

Page 31: CS2251-DAA

UNIVERSITY QUESTION PAPER

B.E/ B.Tech. DEGREE EXAMINATION, NOVEMBER 2005.04 SEMESTER

CS1201 – DESIGN AND ANALYSIS OF ALGORITHMS.

Time: 3 Hrs. Max.marks:100PART A (Answer ALL questions)

10* 2=20

1. What are algorithm design techniques?

2. How is an Algorithm’s time efficiency measured?

3. Mention any four classes of algorithm efficiency.

4. What is algorithm visualization?

5. Write any four examples for Brute force approach.

6. Give the time efficiency and drawback of merge sot algorithm.

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 5*16=80

11. (i) Explain the necessary steps for analyzing efficiency of recursive algorithm with example.

(OR)

(ii) What is empirical analysis of an algorithm? Discuss its strength and weakness?

12. (i) Describe the steps in analyzing and coding an algorithm.

(OR)

(ii) Discuss the fundamentals of analysis framework and notations Used in algorithm design.

13. (i) Explain Quick sort algorithm with suitable example.

(OR)

(ii) 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.

Page 32: CS2251-DAA

(OR)

(ii) Define spanning tree. Discuss the design steps in Prim’s Algorithm to construct minimum spanning

tree with an ex.

15.(i) Explain Subset sum problem and discuss the possible solution strategies using backtracking.

(OR)

(ii) 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-log-n many divide and conquer alg .including merge sort and quick sort

n! 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 queens 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 2nd 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.

Page 33: CS2251-DAA

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. The accuracy of approx alg Sa to a problem minimizing some function f,can be quantified by size of the relative error of the approximation.

r(Sa) = f(Sa)/ f(S*)

PART B ANSWERS

11. (i)

1. Space Complexity:The space complexity of an algorithm is the amount of memory it needs to run to completion.algorithm using Recursive function to fine sum of n numbersAlgorithm Rsum (a,n)If(n_ 0) thenReturn 0.0;ElseReturn Rsum(a, n- 1) + a(n);2. Time ComplexityThe time complexity of an algorithm is the amount of computer time it needs to run to completion.3. Asymptotic Notation4. Performance measurement5. 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 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 (p1,p2…………………..pn)

Keyword name of the Alg parameters

Heading Section includes//Problem description://Input://Output:

Page 34: CS2251-DAA

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 operator assignment statement can be given

Eg: Variable expression It also includes other operators such as Boolean Operators, Logical operators, Relational Operators etc. Multidimensional arrays Looping Conditional statement Input and Output. Algorithm

12. (ii) 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 and worst case -

13. (ii) Algorithm for DFS:-Step-1: Set the starting point of traversal and push it inside the stackStep-2: Pop the stack and add the popped vertex to the list of visited verticesStep-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 alreadyStep-5: Go to step-2 if the stack is not empty

Algorithm for BFS:-Step-1: Set the starting point of traversal and add it inside the queueStep-2: Find the adjacent vertices for the starting vertex( from the Adjacency 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 (i) - Definition of AVL Tree and Balancing Factor - Algorithm for Single Rotation

- Algorithm for double Rotation - Show these Rotations with an example

14 (ii) . - 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 spanning tree

- prim’s Algorithm for MST

Page 35: CS2251-DAA

- 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:iii. 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-Boundmethod are:i. LC searchii. 15 – puzzle problemiii. LC control abstractioniv. Boundingv. FIFO branch and boundvi. LC branch and bound

UNIVERSITY QUESTION PAPER

B.E/ B.Tech. DEGREE EXAMINATION, NOVEMBER 2008.

04 SEMESTER

CS1201 – DESIGN AND ANALYSIS OF ALGORITHMS.

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 i.e. , 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 Fibonacci number of sequence?

Page 36: CS2251-DAA

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) In worst 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 Secret(A[0…n-1])

// INPUT: An array A[0..n-1] of n real numbers

Minval A[0]; Maxvala[0];

For i 1 to n-1 do

If A[i]< minval

Minval A[i];

If A[i]> maxval

maxval A[i];

return maxval-minval;

(i) What does this algorithm Compute?

(ii) What is the Basic operation?

(iii) How many times is the basic operation computed?

(iv) What is the efficiency class of this algorithm?

(v) 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.

Page 37: CS2251-DAA

(or)

(b) Consider the following recursive algoritm for computing the sum of the 1st n cubes :S(n)=13+23+….+n3; ALGORITHM S(n) // I/P : A +ve integer n; // o/p: The sum of the first n cubes. If n==1 return 1 Else return S(n-1) + n*n*n(i)Set up and solve a recurrence relation for the number of the algorithm basic operation is executed.(ii) How does the algorithm compared with the straight forward non-recursive algorithm for computing this function?

13. (a) (i) Describe the Quick sort algorithm. (ii) 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 First Search algorithms.How do they fit into the Decrease and Conquer strategy?

14 . (a) (i) Describe 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

(i) 1,2,3,4,5,6 (ii) 6,5,4,3,2,1 (iii) 3,6,5,1,2,4

15 . (a) Using Backtracking enumerate how can you solve the following problems:(i) 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 $1002 7 $633 8 $564 4 $12

W=16 (ii) Give an ex for the best case input for the branch and bound algorithm for the assignment problem. (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.

Page 38: CS2251-DAA

TWO MARK ANSWERS:1. 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.

2. Input: The stringOutput: Result is palindrome or notGets(string)Strcpy(stringup, string)Strrev(stringup)Diff=strcmp(string,stringup)

3. i. Understand the purpose of experiment of given algorithmii. Decide the efficiency metric M . also decide the measurement unitiii. Decide on characteristics of the inputiv. Create a program for implementing the algorithmv. Generate a sample of inputvi . Run the algorithm for some set of input samplevii. Analyze the resultant data

4. This series can be obtained by following formula

f(n)=f(n-1)+f(n-2) where n>1

5. Linear search , merge sort.

6. Divide: Partition array into two sub lists S1 and S2 with n/2 elements eachConquer: Then find the maximum number of sub lists S1 and sub list S2Combine: Compare S1 result and S2 result return maximum number

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

8. Input: The adjacency matrix A of a diagram with a vertices Output: The transitive closure of the graph R(0) Afor k 1 to n do for i1 to n do for j 1 to n do R(k)[i,j]R(k-1)[i,j]Return R(n)

9. When we got minimum values from each column and no value selected is under same column then we will terminate the search.

10. 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 wixi and pixi.

Page 39: CS2251-DAA

PART B ANSWERS

11.(a)(i) Big Oh:The function f(n) = O(g(n)) iff there exist positive constants C and no such that f(n)C * 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 f(n) C * g(n) for all n, n n0. Theta The function f(n) =(g(n)) iff there exist positive constant C1, C2, and no such that C1 g(n), f(n) C2 g(n) for all n, n n0.Little OhThe function f(n) = 0(g(n)) Iff Lim f(n) = 0 n - g(n)Little omega The function f(n) = (g(n)) Iff Lim g(n) = 0 n - f(n)(ii) – 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 sequential search

11.(b) Refer page no. 5 of Anany Levitin

12 (a) (i) Computing the minimum and maximum element in an array (ii) Comparison (iii) (n-1) times (iv) Explain about Best case, average case and worst case

(v)Try to improve this algorithm for better performance12 (b) (i) Refer page no. 61 of Anany Levitin

(ii) Refer page no. 69 of Anany Levitin

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) Algorithm for DFS:-Step-1: Set the starting point of traversal and push it inside the stackStep-2: Pop the stack and add the popped vertex to the list of visited verticesStep-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 alreadyStep-5: Go to step-2 if the stack is not empty

Algorithm for BFS:-Step-1: Set the starting point of traversal and add it inside the queueStep-2: Find the adjacent vertices for the starting vertex( from the Adjacency Matrix)

Page 40: CS2251-DAA

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 (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 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-left-straight-right' is considered a node in a tree.

(i) - 8-Queens Problems - The problem is to place 8 queens on a 8 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 cycle 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) (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-Boundmethod are:i. LC searchii. 15 – puzzle problemiii. LC control abstractioniv. Boundingv. FIFO branch and boundvi. LC branch and bound

Page 41: CS2251-DAA

(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 0<xi<1 of object i is placed in to knapsack then a profit of pixi earned. The objective is to obtain a filling of the knapsack that maximizes the total profit earned. Since the knapsack capacity is m, we require the total weight of all chosen objects to be almost m.

CS1201 — DESIGN AND ANALYSIS OF ALGORITHMS (Regulation 2004) Time : Three hours Maximum : 100 marksAnswer ALL questions. PART A (10 x 2 = 20 marks)

1. What is time complexity?2. Define Big Omega notation.3. What is the substitution method?4. What are the main aspects of greedy method?5. Give an application for Knapsack problem.6. Define optimal solution.7. Define subset problem.8. Give the application of backtracking technique.9. Define graph coloring.10. Distinguish between P class problems with NP class problems.

PART B — (5 x 16 = 80 marks)

11. (a) Explain the following terms : (i) Searching. (4) (ii) Asymptotic notations. (4) (iii) Analysis framework.(4) (iv) Algorithm efficiency. (4)

Or (b) Explain in detail about mathematical analysis of non-recursive algorithm with suitable examples. (16)

12. (a) Describe in detail about merge sort algorithm and justify the benefits of merge sort with suitable example. (16) Or (b) (i) Explain in detail about Kruskal's algorithm. (8) (ii) Find the minimum spanning tree using Krushal's algorithm with example. (8)

13. (a) Explain in detail about Warshall's algorithm with suitable example. (16) Or

(b) Explain an algorithm to find optimal binary search tree with example. (16)

Page 42: CS2251-DAA

14. (a) (i) Explain the algorithm for Knapsack problem according to backtracking problem. (5) (ii) Explain in detail about Hamiltonian circuit problem. (11) Or (b) (i) Explain in detail about subset-sum problem with suitable example.(10) (ii) Given a set S = 1,3,4,5 and X = 8. Find subset sum using backtracking problem. (6)

15. (a) Discuss NP completeness in Knapsack problem with justification. (16) Or (b) (i) Discuss the features of traveling salesman problem. (6) (ii) Given a graph G = (V, E,W) shown in the figure where vertices refer to cities, edges refer to connection between cities, weight associated with each edge represents the cost. Find out the minimum cost for the salesman. (10)

TWO MARKS ANSWERS:1. The time complexity of an algorithm is the amount of computer time it needs

to run to completion

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

3. One of the methods for solving any such recurrence relation is called the substitution method

4. A greedy algorithm obtains an optimal solution to a problem by making a sequence of choices. At each decision point, the algorithm chooses the locally optimal solution. In other words, when we reconsidering which choice to make, we make the choice that looks best in the current situation, without considering results from subproblems.Problems solved optimally by greedy algorithms share some features with those problems solved optimally by dynamic programming algorithms:

5. It can be used in business, combinatory, complexity theory , cryptography and applied maths.

6. A feasible solution either maximizes or minimizes the given objective function is called as optimal solution

7. The subset sum problem is a good introduction to the NP-complete class of problems. There are two reasons for this .It is a decision and not an optimization problem .It has a very simple formal definition and problem statement.

8. To solve n-queens problem, Hamiltonian, subset sum problem.

9. In graph theory, graph coloring is a special case of graph labeling; it is an assignment of labels traditionally called "colors" to elements of a graph subject to

Page 43: CS2251-DAA

certain constraints. In its simplest form, it is a way of coloring the vertices of a graph such that no two adjacent vertices share the same color; this is called a vertex coloring. Similarly, an edge coloring assigns a color to each edge so that no two adjacent edges share the same color, and a face coloring of a planar graph assigns a color to each face or region so that no two faces that share a boundary have the same color.

10. There is often only a small difference between a problem in P and an NP-complete problem. For example, the 3-satisfiability problem, a restriction of the boolean satisfiability problem, remains NP-complete, whereas the slightly more restricted 2-satisfiability problem is in P (specifically, NL-complete), and the slightly more general max. 2-sat. Problem is again NP-complete. Determining whether a graph can be colored with 2 colors is in P, but with 3 colors is NP-complete, even when restricted to planar graphs. Determining if a graph is a cycle or is bipartite is very easy (in L), but finding a maximum bipartite or a maximum cycle subgraph is NP-complete. A solution of the knapsack problem within any fixed percentage of the optimal solution can be computed in polynomial time, but finding the optimal solution is NP-complete.

PART B ANSWERS

11 (a) (i) Refer page no. 20 of Anany Levitin

(ii) Refer page no. 52 of Anany Levitin

(iii) Refer page no. 42 of Anany Levitin

(iv) Refer page no. 47 of Anany Levitin

(b) Refer page no. 61 of Anany Levitin

12. (a) 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 a[1],a[2],…..a[n/2] and a[n/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(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).

- Refer page no. 124 of Anany Levitin

(b) (i) Refer page no. 311 of Anany Levitin

(ii) - 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 spanning tree - prim’s Algorithm for MST

Page 44: CS2251-DAA

- Explain the graph in stepwise procedure by drawing graph and tabulation13.(a) Refer page no. 280 of Anany Levitin

(b) Refer page no. 289 of Anany Levitin

14. (a) (i) 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 0<xi<1 of object i is placed in to knapsack then a profit of pixi earned. The objective is to obtain a filling of the knapsack that maximizes the total profit earned. Since the knapsack capacity is m, we require the total weight of all chosen objects to be almost m. 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-left-straight-right' is considered a node in a tree.

(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 cycle 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

(b) (i) The subset sum problem is a good introduction to the NP-complete class of problems. There are two reasons for this It is a decision and not an optimization problem It has 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;

(ii)Refer page no. 372 of Anany Levitin

15.(a) Refer page no. 345 of Anany Levitin

(b) (i) Refer page no. 382 of Anany Levitin

(ii) Refer page no. 383 of Anany Levitin

Page 45: CS2251-DAA

UNIVERSITY QUESTION PAPER

B.E/ B.Tech. DEGREE EXAMINATION, NOVEMBER 2007.

04 SEMESTER

CS1201 – DESIGN AND ANALYSIS OF ALGORITHMS.

Time: 3 Hrs. Max.marks:100

PART A (Answer ALL questions) 10* 2=201. What is meant by stepwise refinement?2. How is the efficiency of an Algorithm defined?3. Give the Smoothness rule.4. What is Algorithm Visualisation?5. State the time complexity of bubble sort Algorithm.6. List out any two Drawbacks of binary search algorithm.7. What is Mathematical modelling?8. What is Prestructuring ? Give eg.9. What is Heuristics?10. What is the metric used to measure the accuracy of approximation of algorithms?

PART B 5*16=80

11. (a) (i) What are the important problem types focussed by the researchers? Explain any 2 with eg. (ii)What is Empirical Analysis of an algorithm? Discuss its strength and weakness (or)(b) (i) Discuss the Fundamentals of Analyse framework.

(ii) Explain the various Asymptotic Notations used in Algorithm design.12. (a)Discuss the general plan for analysing the efficiency of Non-recursive Algorithm.

Write an algorithm to find the number of binary digits in the binary representation of a positive decimal integer and analyse its efficiency. (or)(b) What is the principle alternative to Mathematical analysis of an algorithm? Explain the steps in analysing the efficiency of this analysis with eg.

13. (a) Find the number of comparison made by the sentinel version of sequential search algorithm for (i) In worst case and (ii) In Average case. (or)

(b) Give a suitable eg and explain the Depth First Search algorithm. 14. (a) (i) Define Heap.Explain the properties of Heap. (ii) With a simple eg Explain heap sort algorithm. (or) (b) 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)

Page 46: CS2251-DAA

(b) Discuss the solution for Knapsack problem using Branch and Bound Technique.

Two marks answers1. 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. IfT(n) ε Ѳ(f(n)) for values of n that are powers of where b>=2, then T(n)εѲ(f(n))

4. Algorithm Visualisation is Visualisation of the abstractions that describe software.

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 scanFor i= 1 we required n-1 comparison For i=2 we required n-2 comparisonFor i=n-1 we required n comparisonTherefore f(n) = (n-1)+(n-2)+...............+2+1 =(n-1)n/2=( n2-n)/2 =O(n2) (order of n2)Computing time = O(n2)

6. It is the answer we should have fully expected: Since the algorithm simply reduces the size of the Remaining array by about half an each iteration, the number of such iteration needed to reduce the initial size n to the final size 1 has to be about log2 nThe logarithmic function grows so slowly that its values remain small even for every large values of n.

7. A mathematical model is an abstract model that uses mathematical language to describe the behaviour

of a system.

8 Prestructuring is the 2nd 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.

Page 47: CS2251-DAA

10. The accuracy of approx alg Sa to a problem minimizing some function f,can be quantified by size of

the relative error of the approximation.

r(Sa) = f(Sa)/ f(S*)

PART B ANSWERS11 (a) (i) 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 metric M to be measured and the measurement unit

3. Decide on characteristics of the input sample

4. Prepare a program implementing 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 function f(n) = O(g(n)) iff there exist positive constants C and no such that f(n)C * 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 f(n) C * g(n) for all n, n n0.Theta

Page 48: CS2251-DAA

The function f(n) =(g(n)) iff there exist positive constant C1, C2, and no such that C1 g(n), f(n) C2 g(n) for all n, n n0.Little Oh

The function f(n) = 0(g(n)) Iff Lim f(n) = 0 n - g(n)Little omega The function f(n) = (g(n)) Iff Lim g(n) = 0 n - f(n)

12.(a) (i)General Plan for Analyzing efficiency of Non recursive Algorithm:-Decide on a parameter indicating an input’s size-Identify the algorithm’s basic operation

- Check 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. (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 sequential search

13.(b) Algorithm for DFS:-Step-1: Set the starting point of traversal and push it inside the stackStep-2: Pop the stack and add the popped vertex to the list of visited verticesStep-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 alreadyStep-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 two 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

(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 spanning tree

- prim’s Algorithm for MST - Explain the graph in stepwise procedure by drawing graph and tabulation

Page 49: CS2251-DAA

15.(a) The subset sum problem is a good introduction to the NP-complete class of problems. There are two reasons for this It is a decision and not an optimization problem It has 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-Boundmethod are:i. LC searchii. 15 – puzzle problemiii. LC control abstractioniv. Boundingv. FIFO branch and boundvi. 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 0<xi<1 of object i is placed in to knapsack then a profit of pixi earned. The objective is to obtain a filling of the knapsack that maximizes the total profit earned. Since the knapsack capacity is m, we require the total weight of all chosen objects to be almost m.

QUESTION PAPER CODE: E3063B.E./B.Tech. DEGREE EXAMINIATION,APRIL/MAY 2010

FOURTH SEMESTERCOMPUTER SCIENCE AND ENGINEERING

CS2251 – DESIGN AND ANALYSIS OF ALGORITHMS(Regulation 2008)

PART A1.Differentiate Time Complexity from space complexity.2.What is a recurrence equation3.What is called Substitution Method?4.What is an optimal solution?5.Define Multistage graphs6.Define Optimal Binary Search Tree7. Differentiate Explicit and Implicit Constraints8.What is the difference between a Live node and a Dead Node9. What is a Biconnected Graph10.What is FIFO branch and Bound algorithm

Page 50: CS2251-DAA

PART B11.a)Explain how time complexity is calculated .Give an example

(OR) b)Elaborate on Asymptotic Notations with examples12.a)With a suitable algorithm,explain the problem of finding the maximum and minimum items in a set of n elements (OR) b)Explain Merge Sort Problem using divide and conquer technique. Give an example13.a) Write down and explain the algorithm to solve all pairs shortest paths problem

(OR) b)Explain how dynamic programming is applied to solve travelling salesperson problem14.a)Describe the backtracking solution to solve 8-Queens problem

(OR) b)With an example, explain Graph coloring algorithm15.a) Explain in detail the Graph Traversals

(OR) b) With an example, explain how the branch and bound technique is used to solve 0/1 Knapsack problem