Professional Documents
Culture Documents
Syllx Akash DAA
Syllx Akash DAA
Noy Pele: : 0s on? S50? -3n seqn for alln2n,, Thus we have show that 527-31 = O(n?) Q.1. (d) Differentiate Dynamic Programming and Divide and conquer approach Ans. Divide and conquer Approach | Dynamic Programming 1, The sub problems in dynamic programming are dependent and thus overlap. 2. As sub problems are shared, it is solved just once and the solution is stored in table to use for solving higher level sub problems. 1, The sub problems in divide and conquer approach are more are) less independent. 2. The subproblems are solved recursively until the instances are small enough to solve easily Thus it does more work than required by repeatedly cola same sub problems. 3. Itmay or may not provide an optimal ‘solution. 4, It uses topdown approach. 5. Binary search algorithm follows divide and conquer approach. 3. It guarantees an optimal solution. . It uses bottom-up approach. 5. Floyd-warshall algorithm uses dynamic programming. ) Q.1. (e) Prove following: (@) nl = O(n™) (ii) 1* +2" + 34.....470* = 0 (n**1) \ Ans. — (i) ' jf) = ol : \ = n(n-1)(n-2).. By fin)s n™ (n) = n™)| wherec=1andn,=1 i Gi fin) = 14 2k43ky s nktnbantents snk aLP. University-(B,Tech)-Akash Books 2015-3 fla) s n*! Q.2. (a) Solve the following recurrence relations: (8x2) () T() = 2T(vn) +1 (using substitution method) Ans. We guess that the solution is T(n) = O(nlgn) our method is to prove that T{n)< | (nlgn) for an appropriate choice of the constant c > 0. We start by assuming that this bound holds for Jp , that is T(Wn) sC(¥n) IgV) Tin)s 2C Jn Ign) +1 <2CVn ign¥841 <20(Jadtems1] S Cn len) +1 Ss Cnlogn where the last step holds as long as ¢ 21. (i) Tn) = AT ((n/2}) +m (using iteration method) Ans. Tn) = 4T([n/2))+n we iterate it as follows: eX afi) ‘etta)) 3) (ele)-3)3) ea 3 i} easton “9(z *) +e, ya tAte “ e x The series Terminaters when | ? = l=n=2lori=log.n | = : is S Xn) <4°™"TC1)+...+47 Ane Se4-2015 s w Say - is sinco, (142 + 22....2"+] (it) Tin) = {, master theorem) Ans. Tin) = as ns d d Tn) . > Tn) = Q.2. (6) Write Floyed Warshall Algorithm. Ans. Consider the shortest path problem n which the objective is to find the # Fifth Semester, Algorithm Analysis and Design 9 1 2 (S)aa{seloe( Gere , a > ss y (4 ny|—| +4 iG i nia) +4eesn & n(n-1)4 ylons4 (n-1) re2a=l & yn 1ah = logsn 1,2" =1) =2h-1 gla" 4 => 7,'t? -1 (n-1) n.(n-1) +n't? n(n-1)+n pes? n(n-1) + Xen?) n(n-1) +n? n(n-1) +n? a) 5T (n-3)+O(n?) whenm>0 risiewh (Using substract and conqutt 5T(n-3) +0 (n?) 5,b=3 ve ae 1 O(n4,a") O(n? a) O(n? 5/3 (n' ) e porte ss* distance as well as tho corresponding path for any gi ir of nodes in a di network. This type of problem can be solved using tags algoisihm, z ' —m<<———— iLP. University-(B.Tech)-Akash Books 2015-5 This algorithm takes the n its distance matrix (D°] and the initial precedence matrix (P°) as input. Then it performs n iterations (n is the no. of nodes in the distance network) and generates the final distance matrix (D¥] and the final precedence matrix (PN). One can find the shortest distance between any two nodes from the first distance matrix (DN) and can trace the corresponding path from the final precedence matrix (PN]. Steps of Floyd’s Algorithm: The steps of floyd’s algorithm are presented as follows: Step 1: Set the iteration number k = 0 Step 2: From the initial distance matrix [D°] and the inital distance Precedence (P?] from the distance network. Step 3: Increment the iteration number by 1 (K =k + 1) Step 4: Obtain the values of the distance matrix (D*] for all its cells where i is not equal to, using the following formula. Di = min(Dj1,Di + Dj) Step 5: Obtain the values of the precedence matrix [p*] for all its cells Where i is not equal to j using the following formula ph = pi; dif Dj ismot equal to Di" * \pi Notherwise. Step 6. Ifk =n go to step 7, otherwise k= k +1 and go to step 4. Step 7. For each source destination nodes combination, as required in relality, find the shortest distance from the final distance matrix [D") and trace the corresponding shortest path, from the final precedence matrix [p%). Floyd Warshall’s Algorithm: Floyd Warshall (w) 1.n rows [w] 2. DO —w 3. fork + 1tondo 4. fori - 1tondo 5. forj<1tondo 6. DP — (Dir, Di? + Dg) 7. return D(n). OR Q.2. (6) Explain Strassen matrix multiplication with example. Ans, Strassens Matrix Multiplication : By using divide-and-conquer technique, the overall complexity for multiplying two square matrices is reduced. This happens by decreasing the total number of multiplications performed at the expense of a slight increase in the number of additions. For providing optimality in multiplication of matrics an algorithm was published by V, Strassen in 1969. which gives an overview how one can find the product C of two 2x 2 dimension matrices A and B with just seven mutliplications as opposed to eight required by the brute-force algorithm.46-2016 Fifth Semester, Algorithm Analysis and Design The overall procedure can be explained as below: on[& ]:a-[t S]n.[h ] C= A°B [= S] - fe} 8) 1 Cul” Lae an} [bo by X,+2,-2, 42, 4y+%, a +x, 2,+%,-%4 +2, where X= (ag 444,)* Bay +b,,) % = (94044) * boo % = Ag * (Bo, ~ 541) %q = Gy * (by ~ boo) 5% (og +0q))* by, Fa = (19+ Gg) * (Bog + bo) Fy = (gy +044) * (big +By,) Thus, in order to multiply two 2 2 dimension matrices Strassen’ formula used seven multiplications and eighteen additions/subtractions, whereas brute force algorithm requires eight multiplications and four additions. The utility of Strassen’s formula is shown by its asymptotic superiority when order n of matrix reaches infinity. Let us consider two matrices Aand 6,nxn dimension, where n is a power of two. It can be observed that we can obtain four dimension submatrices from A, B and their product C. It can easily be verified by treating submatrices as number to get the correct product. Gu 1 Cu Ave | Ans Ce} Cu} * [Aw } An For example: C,y can be computed asAyy* By, +A,,° By, or an x, +25—2, + xy, where x,,x,2,and % canto tou using otraseen’s formula, with the Sumbers replaced by the corresponding submatrices. We can have Strassen’s algorithm for matrix multiplication, if the seven multiplication of “%, matrices are computed recursively by the same method. OR Q3. (a) Explain Quicksort algorithm and explain worst case time complexity 0f the algorithm. (5x2) Ans. Quick sort Algorithm QUICKSHORT (A, P, R) Lifper 2. then q + PARTITION (A, P, R) 3. QUICKSORT (A, P,g-1) 4. QUICKSORT (A, ¢ + 1,7)22 Unversity tecn—dumast: Bouts 2016-7 Riguralieroemnnyicpatitiiediapanan anny othene=-aili Siingicstdlamet, weeemor tee Bloweny eo rar for tor qu moc agomiihm w-ehow ir sores Cam urwartum: © Ty 2 0 -_ tue sir oz 2 -lsis)-1 teat: L Dees ted es gure auowt fis am von u tet for inttiglicetion, maintenance and em aes Performances sf Qui sort Tie umm sie of quick sort depends on whether che paritemng:s Jaimeed or wntaiere? T Se pecioning is belenned, the algorithm ims wepnpceady ae Sot as megs wt ant 2 the percitimnmg is unbelenced it rms wenpmtiraily 16 vor 2s ceca ‘Worst Camer Warst sauna secures wher. Se arxey as dividied in two uabalunred sub aay) vher ie wera a em.8-2015 Fifth Semester, Algorithm Analysis and Design Ls — (1) —> Thus Tin) = Tin-1) + T10) + q(n) = Tin- 1) +q(n) = O(n?) Q.3. (6) Sort the following numbers using Quicksort algorithm: 12 34 25 40 19 10 30 8 Ans. li Pj r (a) 34 [25 | 40]19]10]30[8 ns r (oi [12 [34] 25 [40] 19 [10 Jao ]s P i r () ifqaTsa [25] 40] 19 [10] 30].8 : continues for all as for every j value is less than r Ali +1) @ Afr) r PJ W. (@) ig [ga] 25] 40 ]19 [10] 30 [12 Pi j r (6) [ie [aa [25 [40] 19 [10 [30 ] 12 Pi r (©) [e]s4 [25] 40 [19 [10 [30 [12] i i ee Jj r i F r P @) [a[s4]25 [4019 [10 [30 [12 P © [esa [25140 [19 [10 [30 [12] Pi J . ® [g]34] 26] 40] 19 ]10 [30 [12] pi Ae dead @ [e]io]25 [4019 [34] 30 [72]LP. University-(B Tech)-Akash Books 2015-9 Pj (hy [ay i0 [12 [40 [19 [34 | 30] 25 continues till: j = 2 and next exchange results in 8] 10] 12[ 25] 19 [34 [30 | 40] and finally the array becomes 8] 10 [12] 19 | 25] 30 [34 | 40 QA. (a) Find the optimal parenthesization of a matrix chain product whose sequence of dimensions are <2,3,4,5,6>. (5x2) Ans. Matrix dimesnsion PO = 2 A, 2x3 Pl=3 A, 3x4 P224 A, 4x5 P3=5 A 5x6 P4=6 Way of paranthesization s{1,4] = 3 (Al A2 A3) (A4) s[1,3] = 2 Optimal paranthesization |(((A1 A2)A3)A4)} Q.A. (b) Determine LCS of X = < B,D,C,A,B,A> and Y = Ans4 (b) . Refer Q.No.5(b) of End Term Exam 2016 (Page No.: 23-2016)SECOND TERM EXAMINATION [NOV. 2015) FIFTH SEMESTER [B.TECH] ALGORITHM ANALYSIS AND DESIGN [ETCS-302] Time : 1.5 hrs. MLM. : 39 Note: Attempt three question in total Q. No.1 is compulsory. Attempt any two more question, from the remaining. Q.1. (a) Define Matroid . (5x2) Ans. Refer Q.No,1(h) End Term Exam 2016 (Page No.: 15-2016) Q.1. (b) What are string matching problems ? Ans. Refer Q.No.4 Important Questions (Page No.: 7) Q.1. (c) Explain prefix function used in Knuth Morris Pratt algorithm using suitable example. Ans. The perfix function x for a pattern encapsulates knowledge about how the pattern matches against shifts to itself. Give the pattern P[l...m], the prefix function for the pattern P is the function x :(1, 2, ...., )—»{0, 1, ....,m— 1) such that, nq] = max (K:K[:[o]sTey*] « ie [eee] i wa the pattern P matches with text 7’ so that q = 5. The valid shift euaonee The Aeacoabat, the pattern will not match text T when the shift ne S + 1, but its valid when S’ = S + 2, When the pattern Pq is compared with Pp, we find’ array x can be represented as x[5] = 3. cae The significance of prefix function is that it avoids testing useless shifts int naive pattern matching algorithm or avoids precomputation of 6 for a string ma! a ao”LP. University-(B.Tech)-Akash Books 2018-11 Q.1. (d) Write down the worst case complexity of naive, Rabin-Karp, KMP and string matching using finite automata algorithms, Ans. Naive O(mn) where m is the length of pattern and n is the length of string when in worst case length of pattern m and length of text n becomes equal algorithm runs in quadratic time Rabin karp. Same as Naive = (mn) (quadratic in worst case) KMP: Running time for prefix function calculation = 0(m) and for KMP matcher = O(n) Hence total time: © (m +n) Finite Automata Running time = 0(n) n = length of Text. Q.1. (e) Differentiate local and global optima. Ans. Differentiate between global and local optima: When an algorithm finds a solution to a linear optimization model itis the definitive best solution and we say it is the global optimum. A globally optimal solution hasan objective value that is as good or better than all other feasible solutions. A locally optimum solution is the one for which no better feasible solution can be found in the immediate neighbourhood of the given solution. Additional local optimal points may exist some distance away from the current solution. Q.2. (a) Find an optimal Huffman code for the following set of frequencies: A45. bil5 0:5 4:25 e:10 (5) Ans. Optimal Huffman code. A:45 b: 15 C:5 d:25.e: 10 (a) Huffman codes are widely used and popular technique for compressing data; savings upto 90% are typical, depending on the characters of the data being compressed. Huffman’s greedy algorithm uses table of the frequencies of occurence of the characters to build an optimal way of representing each character as a binary string (a)e:5 e:10 6:15 d:25 a:45 (6) ‘ 6:15 d:25 a:45 cs e:10 (c) d:2512-2015 Filth Semester, Algerith= Analysis and Desir {d) ) sence cal coling fr wsneitpven character 8 a-l b=001 ¢ = 0000 optimal Huffman code d=01 e = 0001 Q2. (6) Differentiate mentioned in part (a) of the question. need 3 bia Total bits required - (3xh5oBx15 +:3x5 + 3x25 + 3x10? = 135445415475 +30 = 300 bitsLP Usowerncy—-3 Teck Aaa Boss 201s-13 Variable length code: x thin we gine frequent characters thert cores und infeeguent cearactars long coden This woeld requir o=t ] b= Wt 6-00 Varabile length cde es (ASal + Del5 + 405 + 2025 o bx 9 = 45445+20+50+40 = 50 bie Q2 (ec) Differentiate Prim’s and Ercskal’s algorithm ® Acs Kruseal's Algorith=: Litisan Algrcti= ce graph theory that Sade a minima epanning tree for a connected weighted Gaz 2 Ersukal u wtere we créer she soies Som ema lent to largest end pick accorcing!y. 2. Eruskal allows beth cew-cow codes and cl t-nid nodes to get commected, 4 Eruskal’s algerie bolés a mii rpg ee by adding one edge ata nme The ser: Loe us always the shortest only fic aces cist create 8 cycle. 5. Eruskal’s require os to sont the edge wengt c's Sot Prim’s Algorith=: L Isis the Algorsi&cs shat Gods 2 x —ieeoo ppemming tree for a comnected weighted uoudirected graph. 2 In Proms algoetthon we weies em ecciltrary mode then correct the ones nearest to it. 3. Prem’s always jets 2 sew ve-cex to cid verte. + Prim’s Beil a cee spamming tree by adding me vervex at a time The next vertex ta be added is always ‘he ome nearest to a vertex already on a graph. 5. Io Prim’s algorc om we welt the sherent edge when execeting the algorithm. Q3. (a) Write Rabia-Earp string matching algorithm Consider working module q = 11, how maxy sparious hits does the Babin- Karp matcher algorithm finds im the text T=314159265248 when looking for the pattern P=26. ©) Ans. Astrng search algarthe which copares a eurings bach values, rather than the strings themselves. For eSinexcy the hash velue of the next position in the text is easily computed from the bas walze of the carext pomsian How Rabin Rary works Let characters ix bath array T and P be Gigts is redix-S notation (S = (0,1_9) Let p be the value of the characters in P. Choose a prime namber q wach that fits within a computer word to speed com putancrs. compute (p mad q) ~The valae of p mod g is what we will be using to find all metches of the pattern P ‘est againat P only those sequences in T baving the same (mod q) value (Tat, sem) med q) can be incrementally computed by subtrarting the high-order dogit, sixtting, adding the low-order tat, all in modelo g antthmetse ie14-2015 Fifth Semester, Algorithm Analysis and Design Algorithm: RABIN-KARP-MATCHER (TP, d,q) 1.n¢ length (7) 2. m length (P} 3.hed™ modg 4.p+-0 5.150 6. fori 1tom Preprocessing. 7. dop — (dp +pli}) mod q 8. ty © (dt, + Tli]) modg 9. for 8 <0 ton -m Matching. - 10. doifp =¢, : 11. then ifp [1 to ml=T[s+1tos+m) 12. then print "Pattern occurs with shift” 13.ifsspurious hit (s [4 [s]9]2]6]5 [375] 59 mod 11 = 4 equal to 4-> spurious hit [J4]1[s]9[2]e[6[3]5) 92 mod 11 = 4 equal to 4-> an spurious hit 26 mod 11 = 4 equal to 4 - an exact match! (3]1]4]1[5[o]2]6[s[ays} 05 mod 14” *10,not equal to 4 a ell tsLP. University-(B.Tech)-Akash Books ‘2015-15 3]i]4]i[s[ol2[e[s[a]s 53 mod 11 = 9 not euqal to 4 3]1[4]1[5]9]2[6]5[3]5 35 mod 11 = 2 not equal to 4 As we can see, when a match is found, further testing is done to insure that a match has indeed been found. Total spurious hits = 4 Q.3. (b) Define the complexity classes: P.NP and NPC. . (4) Ans. Define P and NP class of problems: Informally the class P is the class of decision problems solvable by some algorithm within a number of steps bounded by some fixed polynomial in the length of the input. Turing was not concerned with the efficiency of his machines, but rather his concern was whether they can simulate arbitrary algorithms given sufficient time. However it turns out Turing machines can generally simulate more efficient computer models (for example machines equipped with many tapes or an unbounded random access memory) by at most squaring or cubing the computation time. Thus P is a robust class, and has equivalent definitions over & large class of computer models. Here we follow standard practice and define the class P in terms of Turing machines. For ally the elem ents of the class P are languages: Let © be a finite alphabet (that is, a finite nonempty set) with at least two elements, and let 2* be the set of finite strings over £. Then a language over £ is a subset\L of t*. Each Turing machine M has an associated input alphabet ©. For each string w in £* there is a computation associated with M with input w. We say that M accepts w if this computation terminates in the accepting state. Note that M fails to accept w either if this computation ends in the rejecting state, or if the computation fails to terminate, The language accepted by M, denoted L(M), has associated alphabet £ andiis defined by: TAM) = (w € E* | M accepts w) P=(L 1 L=L(¥)‘or some Turing machine M which runs in polynomial time} The notation NP stands for “nondeterministic polynomial time”, since originally NP was defined in terms of nondeterministic machines (that is, machines that have more than one possible move from a given configuration). However now it is customary to give an equivalent definition using the notion of a checking relation, which is simply a binary relation R ¢ Z* x £,* for some finite alphabets £ and £,. We associate with each such relation R a language Lp over UE, v (#) defined by Ly = (why IR(w,y)) where the symbol # is not in £. We say that R is polynomial-time iff Lp e P. Now we define the class NP of languages by the condition that a language L over £ is in NP iff there is k N and a polynomial-time checking relation R such that for all w € 5°, we Lo 3y(ly 1s lw, and R(w, y)) where Iw! and ly! denote the lengths of w and y, respectively. Aproblem is NP-complete if it is both NP-hard and an element of NP (or 'NP-easy’). NPcomplete problems are the hardest problems in NP. If anyone finds a polynomial-time algorithm for even one NP-complete problem, then that would imply a polynomial-time algorithm for every NP-complete problem. Literally thousands of problems have been shown tobe NP-complete, so a polynomial-time algorithm for one of them seems incredibly likely + _ Itis not immediately clegr that any decision problems are NP-hard or NP-complete. + NP-hardness is already a lot to demand of a problem; isting that the problem alsoa 16-2015 Fifth Semester, Algorithm Analysis and Design have a nondeterministic polynomial-time algorithm seems almost compl, unreasonable “te QA. Attempt (any two) . ta QA. (a) Explain Hamiltonian cycle problem (with suitable example), Ans. (a) Hamiltonian cycle problem: A Hamiltonian path is a path that y each vertex exactly once A graph that contains a Hamiltonian path is called a traces’ graph. A group is Hamiltonian-connected if for every pair of vertices there Hamiltonian path between the two vertices ! A Hamiltonian cycle. Hamiltonian circuit vertex tour or graph cycle isa cycle the visits each vertex exactly once (except for the vertex that is both the start and wile i visited twice) A graph that contains a Hamiltonian cele is called a Hamilton erp A Hamiltonian decomposition is an edge decomposition of a graph into Hamiltoniay circuits. Examples of Hamiltonian graphs. a) Hamettarion graphs (2) Hamiltonia cycle of fig (i) O-OE-E7OOO-® If the last edge of a Hamiltonian cycle is dropped, we get a Hamiltonian path. Hamiltonian path of fig (i) Non Hamiltonian graphs can also have Hamiltonian paths. Q.4.(6) Find the optimal schedule for the following task with given weit! (penalties) and deadlines: ee ee ee ee 42 2 1 Bae ak eee we Be CheeLP. University(B.Tech)-Akash Books 2018-17 Ans. Task Scheduling Problems: The problem of scheduling unit time tasks with deadlines and penalties for a signle processor has the following inputs: (a) aset s = (a,a,.....4,) of n unit time tasks. (6) a set of n intger deadlines, d,,d,,.d, such that each d, satisfies 1 | = Wat, +W, = 15+10+1=26 Q.4. (c) String Matching with finite automata. (with suitable example) Ans. String matching algorithm using finite automata: There is a string- matching automaton for every pattern P; this automaton must be constructed from the pattern in a pre-processing step before it can be used to search the text etring. Figure below illustrates this construction for the pattern P = ababaca. We shall assume that P is a given fixed pattern string; for brevity, we shall not indicate the dependence upon P in our notation. In order to specify the string-matching automaton corresponding to a given pattern P{1...m}, we first define an auxiliary function a, called the suffix function corresponding to P. The function « is a mapping from £ to (0, J,...m) such that o(x) is the length of the longest prefix of P that is a suffix of x: o(x)= max tk: P, Jat. The suffix function a is well defined since the empty string P, = cis a suffix of every string. As examples, for the pattern P = ab, we have o(e) = 0,0(ccaca) = 1, and ofeeab) = 2. For a pattern P of length m, we have o(x) = m if and only if P} x. It follows from the definition of the suffix function that ifx] y, then o(x) sof). We define the string-matching automaton that corresponds to a given patern P{1_m) as follows. * The state set Qis (0, L...ym). The start state g, is state 0, and state m isthe only accepting state. f 0 © The transition function o is defined by the following equation, for any state q and character a : &(q,a) = ofP,a). S anc camaFifth Semester, Algorithm Analysis and Design 18-2015 To clarify the operation of a string-matching automaton, we now give a simple, efficient program for simulating the behaviour: of such an automaton (represented by its transition function 6) in finding occurrences of a pattern P of length m in an input text T1_n} FINITE-AUTOMATION-MATCHER (T, 5, m) 1.n«length(7) 2qe0. 3. forielton 4. dog ed(q, 7) 5 ifg=em G. then print “Pattern occurs shift” i -m ‘As for any string-matching automaton for a pattern of length m, the state set Q is (0, 1,...m), the start state is 0, and the only accepting state is state m. The simple loop structure of FINITE-AUTOMATON-MATCHER implies that its matching time on & text string of length n is O(n). Q-4. (d) Proof of correctness of Bellman-Ford algorithm. Ans. Proof of Correctness of Bellman Ford Algorithm: Bellman Ford Algorith that computes shortest paths from a signle source vertex to all of the other vertices in# weighted digraph. The correctness of algorithm can be shown by induction. Lemma: Aster i repetition of for loop: # It distance (u) is not infinity, it is equal to the length of some path from to us . Ifthere is a path from s to u with at most i edges, then Distance (u) is at most tb length of the shortest path from s to u with at most j edges. i