0% found this document useful (0 votes)
43 views

Computer Algorithm

computer algorithm

Uploaded by

Johan Iskandar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
43 views

Computer Algorithm

computer algorithm

Uploaded by

Johan Iskandar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 59
yall A eRe - Fee alo a om a sl com em “a Bike AS ae : icPenezemnsntee erate ne ARAL | Ae RAR (ComputerAlgorithmA guy # HM * (Close Books and Notes) 23%) 1, Give the definitions of P and NP. (0) Give the definition of NP-complete {Gh Heh problem bus the steric! honor of being the Gist prob ever shown tobe NP-complete? Describe this problem broly. frreseiae {@) Howto prove a given problem to be NP-complete (bythe methodology of reductions)? {G Why i it“hare” to solve NP-complete problems? Hit: From the definition I~ -- ~~ 3%) - 2. fa Rthiet robbing a sae finds tilled with types of items of varying sce and - (ee ut bas onfy a small knapseck of eapecity M to use fo carry dhe goods. The sas Teapaac problem is to find the combination of items which the thief should aaa for fs kaapseck in order to maximize the total value ofall the items he cae soppose the the sizes of ftems and M are integers. Can you derive an i ‘iforiden forthe knapsack problrn with time complexity ON)? If you can, ‘write down your algorithm, Gy Suppone that the sizes of itsms and M ace eal aumbers. Can you derive an (ther for tke Knepsack problem with polynomial time complexity? Exphin your answer, Bide rae ARH aH ARG RUE A, e Wk On Sika = * 8m am aH 1GSERRIRMELE RRS » FRU HERA (Computer AlgoritimB Spy gy #8 * is 4. (10%) Two binary search trees t and tare equivalent if they contain exactly the same lerents That Is, for allx € t,x & and forally © ts y € t. Devise an efficient (Eta) igrithm to determine if BST t; and tare equivalent. What i the running time of your - : sigorithm, assuming [t= [tel =n? 2. (13%) A word ladder isa sequence of words such that each word i en English word, and pees <2tch pair of consecutive words difers by replacing exactly one letter with another, Here |sa simple example: ‘TREE, FREE, FRET, FRAT, FEAT, HEAT, HEAP Assume that you are upped witha function GET-WORDS{w) that returns, in Of3) time, @ list of all Engish words that difer from w by exactly one letter {perhaps using @ wo preprocessed lcokup table]. Describe an efficent algorithm that finds a word ladder, beginning at wand ending at ws, of minimum lenath, 2. (20) Conder the folowing binary heap (on aroprepresentaton of hespodered complete nay ee i of telat betes eta tate ~ le twtr [ele] vets Tepat-f- (2) Delete the maximum key. Give the resulting binary heap. Cicle those values that changed. (b) insert the key X into the orginal binary heap. Give the resulting binary heap. Gcle those values that changed 4. (15%) The following state machine s designed to accept precicly those strings (over the two letters A and 6) that contain BBABEB, Assume state Os the stat state and state 6 Is the accept state. $8 eal a ale Fan Blo a * lam em & BLERARAT So RE eh TROL 106 BEER 1 PRG EH APRA ES bE Mae ek (Computer Algorithm)A 1. (20%) Consider the algorithm listed below and answer each ofthe following questions define N 16, + unsigned int 24st 001; void xy2int 2) [J+ perform sono operations on the List. */ Int, jy next: for (4= 1; Sem; S40 next = List(i)s for =i 15 3 aistly + 1 Let} + 1) = next: BI eee } ew (4) Deserive the operation ofthe above algoitam by way of numerical example. () Analyze the time complexity ofthe algorithm and represent the result in O(n) notation, 2. (20%) Considering the binary search problem, answer each of the following questions: (@) Weite a recursive binary search algoritwm. fiuasrerez () Write an iterative binary search algorithm, — 13. (10%) Compare the general features of recursive and iterative algorithms in terms of time ‘and space needed in executing these algorithms. Of cours, other factors, if you know, can also be given. wer sx 2 Sate nl ol 4 lcm ae Bl MA a A EERR i FRA a TA OR 10 FRE | meee AE Che ae AUG St} KAMAL (Compater AlgorithmB Bettman 4% ive eon othe © notaon. Use he dios oF, sow duel tat f(a) =H? — Bae? Of) (10 pein) ‘Copa ad eerste remy ead nd he as gang ss (10 pnts) ‘Adedimersont box wt meni (3.4) ms wih ote ox wid menos Quy ster false pemtton an (0-2 auc ta gy rt < Peta ‘were a and B are known constants, Assume that 7(1) is known and js power of (6 eee ab Tn) = { 3. (0%) Answer each ofthe following questions: peresecsees| (2) What is the sbetract computation model of computer systems in studying computer algorithms? (@) What ae the meanings of deterministic and nondeteministie algorithms? peneeeceeesl 7 BEF @ ace Fen alo a i aml com em ah HEeRHRAS SRE ah AGA * 10 ERR 2 IMEI R eA Amal: a: rea RA ESTAR IER(Computer Algorithm)B yaa (Close Books and Notes) 23%), 1. G@) Bully describe the principle of dynamic programming. (b) What Is the ‘optimal way to compute , A, Ay A,, where the dimensions of the matrices are Az x1, Ay: 1x40, A M0%5, 4,2 $30? (Using dynamic programming approach, Plage show the table.) 3%) 2. (@) Give the definitions of Pand NP. () Give the definition of NP-complete. (© What is Cook's theaern? Describe its prof briefly. {G) Howto prove a given problem tobe NP-complete? (© Why is A “hard” to solve NP-complete problems? Hint Prom the defin 3 WEEEEEE EL EEE Qa Pwd a aha eal aSr, Fre Ror) aM] com) ee koe 102 EAH 1 SMALE Aaa oF an AAAI ARAB + at ARs IEIR(Computer Algoitm)s B a att 1. (15%) Given two functions (nt) end g(r), please give the meaning of following expressions precisely: ) FA) = CGC), ©) FE = AGED), ) F(A) = 8) 12 (40% Please onder the following fonstions by growth ate in increasing order: ,W,tllogW.N?, Nlog(logN), 2" 5, (10%) Please give the advantages and disadvantages of insertion sort, quick sot, rmenge sort, and heap sort respectively. 4. (15%) Please answer flowing questions: {) What are the major eferences betwen the dynamic programming method and divide-and-conquer method? Please give your answers in detail. (b) Considering the following Fibonacci sequence: F(Q) = FQ) = Land F(x) = F(a 1) + Fn 2) givenn 22 Prease find out (8) using dynamic programming method snd F(9) using divide-and-conqucr method respectively. Fee 6 ]e a 2 8] cam) ae am 3 # ar ae ‘tvteus emareeee OM ROU a ea AAA SME: EMAIL CompueAlennios ARE RIA: 1. (45%) Given each pai af wo fenton given below, deeming iff) = OCaCWD, Fla) = ACGEOD), Fr) = (G(r), oF eter: 6) F60) = logy 4n , 90) = log Sm © FO) = 1A" , glo) = ot (OF) =n™ , g(r) = nllogny* 2, (40%) Plate answer the following TRUB or FALSE questions: 7 @ m= O(n) 7 ® 106) 7 7 =00% @ 1 = o(nlog?n) 10 logn = 0(04) ‘3 (45%) Given the aeaph shown in Fig 1, please: (6) Find the einimum spanning ee using the Kruska’s algorithm, (©) Find the minimum sparing re sing the Prim’ algorin, sd Pee ete (6) Doser ihe nina apace wee unique, is Big. pee 4, (4.0%) Place answer the following questions: {@) Whats the eaionship besween NP, NP-Hlard, and NP-Complete? a (©) Which ace the fllowing problems belong to the class NP? Ya) All pai horest path - YQ) Clique problem £@) Secoloing ofa graph Baik RA Ful fear ars Fee ele a em] cam) sta BARAK titre a2 Soames [RPA ee AERA A} that Rsk (Compater Algorithm). Port A 2. GO pol) Exam he lowing ems (@) beapsoat (0) Binary search we (© divdeardconqur (dyna rogemmig, (sree aay nd (© eniverahshng 2. (40 pas) Give an O(n git th srs ming in theraege Oto 1 uly your sve. 2 (Opals) Consider an eray A ith (n> 2) ambe. Dseie a Ofnogn)ine goin to fad ,y €A sich fa fens] Seo foray CA. ely your answe HLkBSaRAS ease: z Ep a Fen ome mae & Bice am ah keane emiemnee TRPAMK wom | poate: stag a(Compseigaima Part B 1. (15%), (@) What is the definition of the Binomial tree? (b)For a Binomial tree By, there are exactly C*, nodes at depth i for 1-0, 1, ...,k. Please prove it. 2. (15%) (@)Please write and explain the depth-first-search algorithm. (b)According to your algorithm, if we start from A, what is the visting order? @ OTORS) OOO 3. 0% Please write and explain the Floyd-Warshall algorithm. [bint:all-pairs shortest-paths problem 4. (10%) Please write and explain the Kruskal's algorithm. (hint: the minimum spanning trees] ult eae a tre ale x wml cam am as LEMAR A * 11 AER mae RRR ee SRA: ACA AP EMA Computer AgoitmA f 1. Acave folowing estos (0) Owes preci deft frthe 0 notation. (pons) (0) Lie advanges ind csadvanages fests, qk sor, merge sor and heap srt. (10 plas) (©) Bit expin be dae rogranming sitegy and ke dvdean-congiee meted Wit i th aoc “tree between en? pom) pettecety @ Dew the 8tem hash tele resulting fom hash function i) the keys 18,41 22,44 59,323 and 73, using the hash ‘mod 13 and esoming cllstns a handled by near probing, (points) 2 Let A bean aay of ndstnsimegers. Give an algorithm to find a longest increasing subsequence of ruber For example, if A contains the sequence (18,41,22,4,59,32,31,73), thea a longest Increasing subsequence it (18,61, 44,59,73). Analyze your algorithm se show the re using oréecnotton (AS points) 4 Fale aE a sl SS ee eee le, RAEMARA® -—lgpagismyanneg PROM woe SRA A APRA BS tp R Hse (Computer Algorithm)B 110% Anever ong gestae (0 Wiis nina pobre kr? lt Et on eagle [eee Sati your mera (6 Wists btwn NP and NEC? Pes toe cal fr eco ;——— ‘them as well Peet 2. Te econ eo avec a cone, nt, ph I-— ihe matinon dts eo any othe veoh ph Ti a) te Sort pth mt en 0) ™ aie 8) ne re anf grt ote een of en vee. ame ae ssraniog tine |—— 2.0% Wot besa oft lovin Lier Pan? Opie Po: wens Coin 0 — ano sme lo I 4. (20%) Consider a directed graph G where each edge (iy) € Ela both a weight w(x) (ot necessarily positive) as wel as color color() & {ted blue}. The weight of a path p= vy»... a equal tothe sum ofthe weight af the edges, _plusS foreach pair of sdjscent edges that are not the same colt. Tht is, when traversing a path, it cast an additional 5 units to switch from one edge to another ofa different color Give an efficient algorithm to find a lowest-ost path between two vertices sand f, and analyze its ranning time, (Zou may assume that there exists suet a path) For fl ret, you algorithm should have a running time of OVE). RL ER AR KY aA a] FREE ae ae ile a a ei cm a oeF eR AMR LaTES — CRP APRA Sat SURI (Computer Algorithm)A We Paria 1. Answer the folowing questions. (4) Compare and contrac Prim’ algorithm and Kruska’s algorithm, (10 points) (@) Explzin the reladonship among P, NP, and NPC. Give one example foreach of them. (10 points) 2, Consider a set of keys K = (lyk. os} hy < fr), For each key ki, we have @ probability 7 tata search willbe fork. Some searches may be for values notin K, and so we slso have n-+ 1 "dummy keys" dod a. teptesenting values notin K. The dummy key d, represents al values between & and kyr. For each dummy key di, we have a probability qi that ‘search will eoesgond tod, Determine the cost and structure of an optimal binary search tee or set K withthe following probabilities: (IS points) tfo_1 2 3 4 5 Be DOF 0.05 0.0 -00F 9% | 006 006 0, 06 005 005 00S 0.05 _ 3: An Ber tour ofa strongly connected, lreied graph @—= (VE) i a eyele that waverses cach edges of G exactly once, although it may visit a Yerex more than once, Describe an O(E time Algorithm to fine an Bulec tour of G if one exists. (15 points) 43 MA SPHARAE aka at de eel OF AEE, Fen mle a oF aa e slcsm an ogee etait — ARP | aptkpt a: ake A (Compute Algorithm Tk 1. (10%) Given an array of integers x with MV entrios (assume >a}, we wish to fnd the to entries o= xj and b =xfj such that [o-| is 2s large as possible. {@) Write pseudo code that correctly performs tis task and returns an integer areay asl} containing and j. Solve this problem as efclentiy as you can. (©) Give the eunning time ofthis code in terms of using © notation. 2.(20%) (a) Define precisely what fin) = Olain), fle) = Qlatn), andfin) = @tatn}) mean. {0) llr the fllowing table, where each entry should be 0, or G, according to whether the row function i 0, or @ of the column function. more than one istrue, please put the strongest result possible (Al logarithms are base 2.) 7a i = a nea as '3, (10%) Suppose thatan array al sa max-heap that contains the distinct integer Keys 2 2, 13m Nwith W larger than 2. The key N must bein a} {2) Give al possible positions forthe key N-2. {() Give all possible positions for the key 2. 4. (10%) For each ofthe following two trees, either indicate how to color the nodes red and block (use Rand B to label the nodes) to make the tree a red-black tree, or explain why that isnot possible co} o Q Q QO © @® Q ®) Q ula 8lF 7. onlan em *[" * a ORES Sita | CR ey FRSA * SRA HAMATAComputerAlgoctimyA BEER Raeet a RR OR 4. (20%) Suppose we have a linked list with» elements, and we wish to insert new ‘elements into this list The liste appended by first traversing t and attaching new clements to the end. Whats the compleaity of bulding the ist (in Big-O}? Con you do better? 2. (45%) Suppose we have a set A with m different numbers, (2) Can you find an ofa itle-oh algorithm to determine if there exist two numbers x ‘and yin such that x+y = m? Please justify why your algorithm is ol). (6) can you find an of) itle-oh algorithm to determine if there exst tree numbers x, yand zn A such that x + y-+2=0? Please justify why your algorithm is ofa) 43. (40%) Insert the following 7 keys "","P", “H", “0”, °N", "2 and" into alinear probing ‘hashtable of size = 7, using the hath Function fQ) = 1567, where xis the fh etter of the alphabet. 4.15%) Consider the rectangular gid of integer points, f) with O2/¢2mandOz;<2n.A | —— staircase begins at A = (0,0) and resches 2= (2m, 2n) by an intermixed sequence of 2m right and 2n up moves. {2) How many staircases are there for general values of m and n? Pease gve 8 closed form expression forthe result, {b) How many stalreases ass through or below the point M = (a,b)? Please give a eosed form expression forthe result. ela, 0) Wane « oe The alo a # HY] (am) et an Bi woseeR sutemnes WF BM ARG ne agg TRAE HRMAKACompuealgodime FTES gem: ite Bedwas (Please define all the eymbels or variables as detiled as possible to get the {ull exedit) 1, Leb bbe the set of al strings in {0,2}*, where there is one more 1 then ©, For instance, 011, 101, and 110 ave the attings of length three in L. ‘Obviously there is an algorithm that can determine if w € Z for any string w, and which runs as function of in liner time. Show that ‘here is & polynomial time algorithm that can recognize the language E*. You uny present your idea via a high-level recursive subroutine for this algorithm. (16%) 2, List at least 4 approaches we usually use to solve the NP-complete problems. You should give an axample to support each of your answers ‘without superficial deseription. (16%) ', ‘Te Cops and Robbers problem is defined beced on an undirected grap G= (VB) where each ease € B hasalength Le). There are two spe ial disjoint sots of vertices: police stations PC Vand banks BV. ‘At the moment that robbers lave a bank with stelen money, en elarm 4s broken and the police start streaming cut of every police station in every direction (because they do not have any idea whch bank has been robbed owing to the broken alarm). The tine for both pelice and rob- Der to traverse an edge i the sume, i, L(e). A vertax v € G's secure if lts distence from the closes: police station i ess than that from the closest bank, otherwise a vertoxis insecure. Assume thatthe distences from a bank and a police station to a vertex are unequal, write dows, ‘8 preudocode to determine the aoure and insecure vertices of G. Also ‘aualyze the corresponding time complexity. You may frst model this ‘ueston by defining any necessary viable and constructing graph baoed on the possible situation. (18%) Pale RE, 7 elon oem | * ae Hake RAS BERR Bn PARMA kk sR D ORERR AGMA he ASME E APSARA k( Computer Algortin)A EH ggg RAM * 1, Ase tbe flowing guess (10 pois) (0) Li wo pobans that have polaseal ie algun Ss your answer. (i) List te eaiosip eset NP and NPC. Give exp foreach of them, 2 Consider ih raph C15 pois) (69 Fi a nim spanning Ue for the pk G seg Pei’ ‘Show de atone sp Oy Sep 6) Fiadaminimor spnang ee forte raph Gustg Krahl’ agri Show te ctens sep 0 ep. (6) Dew ara ht ba orth ove minino spaalg ee, i, 14. Cireatnearsine gor ta dine wheter alext en eyeicoaon faethe sng 7, Foresale a0 tod ont arecytororaons of enc ole (10 pe) 4 Dey dese he ral of yan programming. Ue te dynanic programming approach o wre a gor ‘ith th Gch anime suey comes SIs a ives Is el wales. 3 pont) HEITUIU 3d | se) OF Sete nie al i slo yan an Behe a oe | BROMO AMELAEBS ne : Aen: ARAL APORRES fst amRaL (Computer Algoritim)B 2. (25%) Please gve a definition and draw a graph to llustrate each ofthe folowing. OMY §—WAGTOY (eda) 2. (10%) Consider the construction of «binary search tre (8ST) by successively inserting m distinct items into an intially empty tre and storing one tem per internal node. Be sure thatthe items are sorted from lotto right (left child < parent < right child) without ever rebalancing the tree. {2) How many different trees can you get forn=3 items? Please draw athe --| possible trees, (b) 1s tte that if you pick a random sequence ofthe aitems, then each ofthe possible treesis equally Bkoly? Please justify your answer. — 3. (258) Each ofthe following lava functions takes 2 nonnegative integer a its ‘put, and returns a string of length W = 2" with all's’. choose the best matching asymptote complexity bound from (A. fog 8, B.C. log HO. NY, ond 2"), Please recall thot concatenating two strings in Java takes time proportional tothe — ‘sum of thelr lengths Please justify your answer. (a) pute sate tron a ‘sings="), i foe(tneo:en te) aan | par | Im Foe ( those 6] al nerd 1 (c) pubte nave sng are (a {emo} tune — ‘tsar fanea-oencsot a SAHA 7 eae @ a rae elo a r + micom am am a ome OR fk FROM OREER— BMH RBA ae : APSR: SPEAR A (Computer Algorithm FH ag ABER] + Part B 1, (10%), (@) What are Huffinan codes? ()Given the character count in the following table, what are their Huffman codes? a b e d Elf cout [4s [3 [2 ie [9 5 2. (15%) ‘The keys in a binary search tree are always stored in such a way as to setisfy the binary-search-tree property: Let x be a node in a binary search tree. Ify is a node in the left subtree of x, then keyly]<=key[x] fy is a node in the right subtree of x, then key[x]<=key[y]. Note that the binary search te is not a balanced tree. Assume that we insert <12, 8,15, 7, 17,21, 4,5, 30, 2, 3> to an empty binary search tree T. ( Please draw T after insertion. (b)Please write the search algorithm for a binary search tree, 3. (0%) {a) What i the definition of NP-complete? (0) What isthe knapsack problem? (Note that the knapsack problem is NP-complete.) 4. (SY (a) What is the definition of B-trees? (b) What is the definition of Binomial trees? a ane =e ae Fee [fr Ht) mics am aR Ba geaa ss sent ae rt ih ARPA eRe : Ai a BA RAB secgeeks ACCompuerslgodtimA Reman (©) Whats th tine comple fan algo? How doe ao tht an lpr is pina fora pote? 10 1, Answer following questions —“ (@ Plee gre rst dalltion forthe oto. (peas) (Gy Elin why qucoor is Olas wort ce ad O(a) i ge. pints) elt) 2. Wea slgithnto mers sored ith a lngtiffcemly. Wharistheexecaton eof yo titi? (25 pains) |——— 1 Given am ty with leet, we an lpr ht determines wheter he ray sma, Antz the —_ ‘ening Une of our ages ater of. (IS pons) rar CES =e aston oem | fl ae BLEBARAE pa heed i. a RPM AK BORK Oe Rea Ram a re RAB SESGeE ob Jbaka ak A ea RRS | Pat A 1. newer the following questions (4) Please give a pesze definition for he O-noxaton. (Spots) () 2"! =O]? 152* = OTT Why? G poins) {e Baplia why guichaotis Ol) init wos ease, and O{rlogn) in average. points) {) Compare the efcieney of sequen each algorithm anda binary search algorithm. Which is more efficient? ‘Why? (10 points) ‘Wace he diterece between the binary-each-tee property snd he min-heap popety? Can the min-esp prop {ry be used to pint ot the Keys ofan w-node we ie sod order in O(a) dine? Expais how or why nor? (10 pola) 43, Letxit.n) and [abe two snd ays sch contain 2 numbers in increasing ore Give an O(logn time ‘igor on Be median of ally elements nara X andY. 15 pola) TAT RLEBHRAR RAS CAR ARML RE Tf ASS SURALE San anus PartB 1. (10%) (2) What isthe longest common subsequence (LCS) problem? (@)Determine an LCS of <1,0,0,1,0,1,0,1> and <0,1,0,1,1,0,1,1,0>. 2, (15%) ‘The keys in a binary search tee are alovays stored in such way 2s to satisfy the binay-search-ree propery: Let x be a node in binary search tree. If y is a node in the right subtree of x, then key[y]<+key[x. If y is a node in the left subtree of x, then key[x]<=key[y]. Note that the binary search tree is not a balanced tree. ‘Assume that we insert 12,10, 8 6,15, 7,21, 17,3, 5,30, 2, 4 t an empty binary search tee Goo {(@)Please write the insert ale bake (b)Please draw T after insertion. i pet % - ay 3. (15%) Sierra eens (@) What is the definition of NP-complete? (©) What isthe traveling-salesman problem? (Note thatthe ‘raveling-salesman problem is a NP-complete problem.) (©) What is the hamiltonian-cycle problem? (Note that the hamniltonian-cycle problem is a NP-complete problem.) 4, (10%) (@) What is the purpose of the Prim’s algorithm? (b) Write the Prim’s algorithm. val Ff 8ne ae eminem [YF eo BEER Ea AP AL Hh RO ORR OW mY, Fay REE ee ston oan */° 4 ae HLEMARAL SeRR Gh ARMM kone BERT eee Oo a A pang: a-ak Fak(Computec Algoritmds HAE gay 9H 1. Anower te fllowing. (Plessis preci dln fr O-riton. paints) (4) Wate the string tine ef ues for dint clement in detesng odes (Spots) (© LaSand 7 borne amye of and n lamest respectively. Wee alga Sal ‘Secommon slemats aed tore tam in an sey U- Anlye you ager nd show te ‘als wang onder totston 0 pales) 2, Atary heap ke binary hep et onde nades have dein instead of wo cle, (4) How wuld you epresennion ry mx bap in an aay? ( ol) (©) Whatsthe eight d-ary axe ofm lames a rms of and poll) (© Forn-ary naa, pv an fie! gerithe HAX wich reroes ad seme he largest ‘Somcot Atalaeheroning ie in terms of and nD pnt). eal faa Fee mle of @ 8) (am) a BR BH Rat “Senak-amerunes §,,, 7M TRRAAR 6 APRA ARAL ¢ af HAeoe M ok (Computer AlgorithmyB 3x #4 Amal jindaes Part B — 3. (15%) (@) Write the Bellman-Ford algorithm. {b) What is its time complexity? (¢) Prove that the Bellman-Ford algorithm can solve the single-source shortest-paths problem in the more general case in which edge 44, (10%) The keys in a binary search tree are always stored in such a way — as to satisfy the binary-search-tree property: Let x be a node in 3 binary search tee. If y is a node in the right subtree of x, then key{x}<-key{y]. Note thatthe binary search tree is not a balanced tee. ‘Assume that we insert 5, 10, 19, 6, 15, 7, 4, 17, 3, 12,82, 21 to an [— empty binary search tree. Please draw T after insertion. of NP-complete? (b) What is the definition of NP-hard? Fee (©) What isthe vertex-cover problem? (Note thatthe vertex-cover problem is NP-complete problem.) () Write the Ford-Fulkerson algorithm, (b) What sits time complexity? -—- ‘weights can be negative a — keylyl R. Then, we wish to find an acyclic subset T cE that connects all of the vertices and whose total weight w(r)= Yiw(u.»)is minimized, Please write an algorithm to find T'and analyze the time complexity using big-O notation, 2, (10%) The keys in a binary search tre are always stored in such a way as to satisfy the binary-search-tree property: Let x be a node in a binary search tree. If y is a node in the left subtiee of x, thea keylylkey(x]. If y is a node in the right subtree of x, then keyix} Lee oe gi at con dei beth an aay (La) coins 2 sj element, an iso Ree — es rogour agit and show the eu sing ender soto (18 pots) 4. What isan tinal Htfnan code forthe following st equence, esd on te fat 8 booze nembes? ast bit oid d:3 2S #28 ge13 Bs2t omit your answer od he opin cod wen the fue te isin bons nters plas) WEF, a Fee OB tr a as |cem em BLkPARKE SERB a BRPRRAR ® BRERA BML RE Tee gue: AR RR EB Oseeane (19%) Given an algorithm that determines whether or not & given undirecsed graph G = (V,B) contains @ cycle. Your algorithm should run in O(V} time, independent of [21 (155%) Show thet a graph G = (V, 2) has a unique minimum spanning tree if, for every cut | __-__ ‘of the graph, there Is 2 unique light edge crossing the cut. Show thet the converse is not true by giving & counterexample 3. (20%) (A problem about Dijkstra’s algorithm) (a) Deseribe Dikstra's algorithm ia words, oe (B) Applying Dilkstra's elgoitira to the graph chown In Figure 1(a), find all shortast ‘paths from source node s to all nodes. (6) Applying Dikstes's algorithm to the graph shown in Figure 1(b), find all shortest paths from source nede » to all nodes. {€) Discuss the running time of Dijkstr's elgorithm in verms of big-O notation. Figure 1: Graphs forthe problem related to Dijkstre's algorithm. ae OF | Puy FPF «® Fee mle a ani cem pee a BLdeARAF RERE hh ARAL a RR OE BRAS TTT TT SRR RR— BIER : Puatregaatan knee “Solve the flowing ecurence exactly. (15 polit) nel? ifn =0,1,2003 tL gates otherwise Pease give precise defn forthe © notation. The egress Your ane assimply as posiby sing the © station. vac acay Teortangn lems, You wan to find he mamas whee ms mh smaller han fn Would you (srt T an pick the fst m element oF plats) (@) use some other method? (10 potas) “analyze te rong ies of be agit in tems of #84 Sappoee thatch ow ofanmxcnarayA cons sand Se8 a pe of Ayall1's Saree et rom, Amung A ea a marorys essa eneion AE sr age) ame for counting te numberof V's 4. 20 pln) en Fal aE ee elas oe aa HLePARAS Sane 90 SRORAR oe RF SEAR RMR RBS EL gael: “ste TEARERB oe & x ea EHP PrEEEHE erro eee 25%) 1. (a) Beifly deseribe the principle of dynamic programming. (0) What is the al Stil way te compute A, A, Ay A, where the dimensions of the mates ae TAs 20%, ys 1540, AMOS, Acs 5x30? (Using dynamic programing approach, Please show the table.) (5%) 2. Find all the articulation points and the biconnested components inthe following raph (how the nanviow ofall the vertices, andthe content of stack, (Starting with node A a “oer is # Fl cam) eae a BL eBanre 74 BERK | BAG ARON KR OTR Ouse aesgapa : (avERee A) Chee fatal: Graeme MITT Answer the following. (a) Please givea precise detition for he big-O notation S points) (@) Explain wy quicksor is O(7?) ints worst ease, end Ofnogn in average. ( pals) ‘suppore you ae given an aay A of sorted muibers hat hasbeen circularly shied postions pest, For example, {35,42,5,15,27,29} isa sorted array that has boen circalarly shifted (ces) pontons, while {27,29,35,42,5, 5} hasbeen cireulely shified k= 4 poston (@) Suppose you know what Kis. Give an O(1)algocthm to find the largest number A. 0 points) (6) Suppote you do not know what kis, Give an O(log) sigh to find the largest number ‘4-5 points) . Suppose that we are given a sequence 5 of m elements, each of which is eolred red or be aereng Sis represented a5 an array, give ai-place method for ordering So hat all he bloe ‘ements are listed before all here elements. (15 points) WL wal A AEE Fee lem a} (en em RLEMARAE GU SER | PHY ROMA Cm a SRA eR RIB Bags aa: r Ozeenes {Close Books and Notes) est) 1. Hind all he strong components in the following graph (show the dfs number of all the vertices) (starting with node A.) 5%) 2. (@) Give the definitions of P and NP. {@) Give the definition of NP-complete. {0} Which problem asthe historical honor of being the first problems ever shown to be NP-complete? Deserbe this probiem briefly. {ho How to prove a given problem to be NP-complete (by the methodology of reductions)? {@) Why isi “herd to solve NP-complete problems? Hint: Prom the definition a a cr a * Siam jem em Bi kReere > Sea% > Seis sRoaAK a RRO SRE UBB Re AK gees ARAL (Closed Books) i 1. (20%) Given e graph G and 2 minimum spanning tree T, suppose that we decrease the weight of one of the edges in T. Show that T's still a minimum spanning trve for C. More formally, lot T be a minimum spanning tro for C with edge weights given by weight function w. Choose one edge (z,y) € 7’ snd a positive number k, and define the weight function & by Joya) ={ 2%) Ea) AG, vou {ES 2 BODE ES tH Stow that is «minimum spanning tes for G with edge weights given byw 2, (20%) Give an algoritam that determines whether or not a given unidrected graph @ = (V,E) contains a cycle. Your algorithm should run in O(V) time, independent of [El (Hint: By theorem B.2, in an acyclic undirected forest [BS |V|~1. ) 3. (10%) Explain how a vertex u of adirected graph can end up in a depth-first tree containing only u even though u has both incoming and outgoing edges in G. oa (%01) “wety Jo sexxe;duico aoe (%01) “way Jo sanixajduiod at (%01) Ww eee pue yosdeay :wejqoid Bupios om, :SUU9} BUIMOTIOJ € oewreso heey es ewe WUROREY bl We < EXwe ae we0 OP ]w & fe oely wes ate are |e val 7 eer alo a = | cam) & BAERHRAS ® eeRR | BHP SoA me Fane PEAR E ZAG Gigs | Asal: Bintuan (Closed Books) 1. (20%) {a) Define the following terms: (1) DAG (directed acyclic graph), (2) topologies! sort. (b) Deseribe an approach to topologically sort a dag by using DFS (depth-first search) algorithm, You do not need to describe the DES slgorithm in deval, just use it. (0) What isthe running time of your approach ? Represent it in terms of big-O notation. (20%) Assume that you heve an algorithm forthe single-source shortest-peths problem. (6) Show that the following problems can be solved by the single-source shortest-paths algerithen: (1) Singlo- destination shorvest-paths problem, (2) Single-pair shortest-patlt problem, (3) All-peireshortest-pathe problema. You do not need to run the algorithm fn detail, just give how you use the elgrithma. (0) If Dipkotra's algorithm is used as the algorithm for solving the single source shortest- paths problem. Give the time complexity for each problem listed in (a). The time complexity of Djkstra’s algorithm is O(V log V +B). (10%) Let (u,») be & minimum-weight edges in a graph G, Show thet (ux) belongs to some minimum spanning tree of G. (7 HL SRARAKE sae: a hg F Ose 8% Gee Aaa: Biasues Pale eae ra valance tes > ReRR | SB GRARGMMR nome OF Part B 1. To sort a sequence of numbers in increasing order we can use heapsort. A. What is a heap? (5%) B. Show how heapsort works for sorting the following numbers 5,4, 1,8, 3, 2, 7 (10%) C. What kind of data structure you would use for the heap in the heapsort program? Why? (5%) 2. Order the following 5 growth rates in increasing order. (1.001)", n°, 2°", nl, nlogn (10%) 3. Show that any algorithm which sorts by comparisons only must have a worst case computing time of O(nlogn).(15%) 9 . = 7 HAkRARAE Ge BRE ie SME Sho e RRO vans yh of BebEnen S80: (1) 20% Design an efficient greedy algorithm to solve the traveling on salesman problem. What is the time complexity of your algorithm? |= Compared it to the optimal solution. (2) 20% Show that the complete graph of order p 2 3 contains (p-1)!/2 hamiltonian cycles (order: the suber of vertexes). —— (3) 10%Fow to use the depth-first-search algorithm to find the cut vertex ———~ of a connected graph? 1 : a ere =m . biel ree fle &| ss] irm em ae HiePaers Te BERK a Snes FRewA BORA kin HE Re Aaa SRE Ewe Brednas ©" | — ae 25%) Sno 1. Find he optima binary search ie forthe fllowing keys: (The Sequences sppear nthe parentheses afer ech Key. (Please show the vals in the marx) oo | ‘A(10), BQI2). CC), DUS) 5m) 2. (@) Give the definitions of P and NP, (@) Give the definition of NP-complete (© What is Cook's theorem? Describe its proof brill. {@) How to prove a given problem to be NP-complete? {@) Why is t hard” to solve NP-complete problems? Hint: From the definition. BRERA RAE SRB tk wth ake Brtznay 68% a a 7 alan ee 7 * an 1 FERE — SWE aROMM I ke 1. (19%) One the following functions by growth rate (ie, Big-Oh). indicate ‘whieh foetions grow a the same rate NWS, NY, NlogN, Nloglog2, Nlog! M, Nlog(N), 201, 2", 2*°, 37, 0? 2, (13% Briefty desert the principle of dynamic programming. Describe how to consuctthe opimatbiuay search ee by dynamic programming. as 3. _{@) Deseibe the propeties oF an AVL tee (b) Draw the AVL tree built when the eys 3.2, 5, 6,9, 4,7, and B ae inserted ini av inally empty Wee. ease show the AVL wees flr each insertion) (e) Draw the AVL re bull whe tl keys 6 and 5 ae deleted from the resultant AVL tee of pt (0) (Please Show the AVL toes afer cach deletion) 15 ee 7 ane = oon THR BR Ml saloon ee = — Hin PRGA We ot Cone : ees 3h FURS SG bah BE Shenae © (Closed Books) 1. (10%) Banks often record transactions on an aecount in order of the times of the trans actions, but many people tke to roceive their bonk statements with checks listed in order by check mmber. Peoplo usually write checks in order by ceck anime, and merchants ‘usally casi them wit reasonable dispatch. ‘The problem of converting time-of-transaction ‘ordering to ceck-numbor ordering is thorefore the problem of sorting almest-sorte input. Argue tat the procedure Insertion Sort would tend to beat the procedure Quick sort on this problem, 2, (1056) We say that a langiage £5 is pelysomil-time redasible to language La, denoted 8 by Sp Ly, if there oxsts © polynomial-time computable function f+ (0,1}* + {0, 1)" sich that forall 2 € {0,1}*, © € Ly if and only if f(z) € La. Show that the

Odo Hanoi, 65,3); end {hint time complexity em) 1 ifm 1) 2. (1) Show that itis possible to multiply two men matices i atime O(a). (15%) ao @ What do you do about matrices whose size isnot «power of 2? (10%) aa) 8 Te wie # fate a cam am us HREM ARAE SRE | Om RERSMRAK kone sean: ob aig et ! TEA, Ane 1. The procedure MinMax below finds the minimam and maximum in an array X(1.2) cfm numbers with at most n-2 comparisons of real numbers minsx(}; mace for i= 2 t0nd0 XG] max then max = XTi] end () Weite your ow version of Miniax that uses significantly fewer comparisons of «eal numbers. For simplicity, assume that >=2, (15%) (©) Exactly how many compatisons of real numbers does your new algorithm make inthe wore eae? (10%) 2. Consider two sorting algorithms: Mergesot and Heapsort fee (@) Deseribe them, (10%) (@) Show that the runing time for each of them is O(ntogn. (10%) (©) Show that the Mergesor is faster that Heapsort by a constant factor. (5%) iy Wane at Fen ele a ws] com am Dike eka we SRERE — BM TH GER IM aH 8 3R3a pel: eRe 44 343m we eee ag OOH as%) 1G) Show that for alt the nonempty bieary trees whose nonterminal nodes have tracy two nonempty childen, the number of leaves ais greater than the umber of nonterminal nodes kd mrt (6) Let Tio be te ime complexity oF the felling fneton F. Express Tin) in terms of Fy). int Fata) itfec=t) return ts return lol HE(O2}, ) (2%) 2. (@)Athiof robbing a safe finds it filled wih W types of tems of varying size and valu, buts only a small Krapsac of eapacity Mo use to carry the goods. The knapsack problem i to find the combination of ems which the thet shoal -choese for his knapsack in order to maximize the total value ofall the items he lakes, Suppose thatthe sizes of items and AY are integec. Can you derive an algorithm forthe knapssck problem with time complexity O(HD07 Ifyou ean, ‘write down your algort. (6) Suppose that the sizes of items and M are real numbers. Can you derive an algorithm forthe knapsack problem with polyromisl time complexity? Explain your aner * we Fee nie a tM] came) er an HASM AR AS So BRE, = BAAN | me | sane: ALAD of eo an a fi: reg a 1. Find the time complexity ofthe fllowing functions. (10%) fori=010nd0 begin ink, while j#0 do =5/25 oe end was, furetion Euclid (m,n) while m>0 do begin t= mod my; mat end eee retumn 2. Consider the following internal sorting slgoithms: (selection sort (insertion sort eee (Obubbte sort (@aquick sort Answer the following questions with brief explanation: (25%) frESEEEEEaG (@) Which method run fastest for file which ie already sorted? (b) Which method run fastest fra file in reverse order? (©) Which method run fastest fora file whose keys are all equal? é (© Which method implies the fewest exchanges? (©) Whiet method uses “Divide & Conquer" technique? 23. Please answer the following question briefly with “yes” or “no” {IF any one NP-Complete problem can be solved in polynomial tne, then ll the [NP problems car be solved in polynomial time? (10%) a are 2 cee FFh at | mM kamal Se at WRI RE FH Bes ae / -16,30,8,28.4.10,20,6,18) at the end of each [-— phase of the following algorithms: (0) QuickSore C105) 8) MergeSort (10 9) 2 Derive jhe time complexity ef the Play ¢_aXbarithm for Lincling the minimum enning. tree of a groph Gis I EF, |, |__car_ he graph is_ represent by aay) by) the. gsaph is _topresent by adjacency list” C/T #) {Assume that G has at least one vertex) T:=Q; TV:= {1}; {start with vertex f and no edges) }— dione := false; while T contains fewer than n—1 edges and not done do begin Let (u, v) be a least cost edge such that we TV and v ¢ TV; if there is no such edge then done := true — else add v to TV and (u, v) 10 T; end; if contains fewer than 1 edges then writeln (‘no spanning tree’); Prim’s minimum spanning tree algorithm HLfRHRAF Fa, Fe eee] = Fee ele ot + m| cen en eo YEAR > SHR ASME saan UtRetle pe Biba Om 3. Write a context free grammar that generates all words of an equal number ofa's and b’s. 2576 4 Design a data structure that may access sparse matrices efficiently. Use an example to demonstrate your design. 25% % pRR I Hh el ee * S| Cam) ee at Ri eBARKE ap eeae | BR GHARSRAK 8 sua: pee A Gee Aa: 1a D (CLOSE BOOKS & NOTES) 20% int reeursivetint n) t inti, sum-0; if(n- Steet RoMMe 2 ne OR ata: Hea ot | sata: ERT} Biaduay © .Peonve._the following. Chaotew.s _ ae eee Any. decision tree. that_sorts 1 distinct. NL has_a height Of ok Beast. dogg 80th CBI algoritten that sorts only by comparisons must have a f= Case. computing. hime _of OCs). C15 2) 2. The following. is 0 Sametion ‘that ul idan Caleran. walk tr a connected, undirected groph that Ras wo vertices with odd edges. Path Graph::euler (vertex v) eee oe 2 Path path = { }5 3 for (all vertices w adjacent to v) && (edge (v,w) not yet used)) { 4 mark edge (v,w) as used; 5S path = {(»,w)) VU euler (w) U path; 6 eet 7 return path; 8) shoo that_if_o graph rie represented aby tts. adjacency mubtilists Ard." path” hy. a finlerd Uiat, the. Suine-tion euler’ wortes ta €_.vepresents she of vestices |____dnd. edge « 4 G, respectively. Clo) eal A ake aa Fee mle em] (am) a jae on BLERIRAMER CL PERB > MBA FREMAK % AR ARAL Oars + Baty Bs a : Lees Besduas 9 (CLOSE BOOKS & NOTES) 1 (25%) (@) Describe P and NP. (b) Describe NP-hard and NP-complete. (©) Describe Cook’s theorem, (@)_ What is the first NP-complete problem? (©) Give a method for proving that a problem is NP-complete (ic. list the steps) Explain your answer, 2. (5%) Tong int caleu(int n) l Tong int sum = 0; int is ifn <= 1) return 15 for (i= 1; i<= 10; 144) sum +2 calcu(n-1); return sum; (Find the value of calou(n). (write down the recurrence equation and solve it) (©) Find the time complexity of “calcu” function. (write down the recurrence equation and solve it) bk ar a em Fee Ble tm] (am) oem jae Rieereewgem Seeee | #a HRA Fy We aaans Ut Ere a BEY cay ABA: Groene: 1. 5%) Functions d ands map set of postive integers into set of postive integers. You are given dQ) =5(2) = 13 dQ) = 53) = 2 ny = dna) +2 tne; sto) = sti) +n—1 if nis odd and n> s(n) = s(n2) +n —2. if mis even andn> 4. For integer n 2 2, prove ln) + s(n) =2n-2 and (a) = 2Llogy nl 1 ifgicn<3x24 and i2 ls (ni) =2 Logg nl if3x2H! Sn< 2H and i2 1. 2. (25%) (@) You are given an input file of characters S, A, O,R,T, I,N, G, A,N, D. Use a heap of size three to show how the replacement selection can be used to produce initial runs in the first par of the sort-merge process. (b) What are the meri of the replacement selection when compared with internal sorting algorithms (such as quicksort)? & a) A ake fe Fee mle tt of ay (em) ae ae asewctawem wegee | ewHeReMRM og, ge ae nem . saa 1A IEe. Besdeas 98 + The following procedure Dijkstra is used to solve Single Source Shortest Paths problems. C{ij] stores the length of the a from vertex i to vertex j. If tore is no are from vertex ito vertex j Cf] = 0. S isa set }- _of vertices to which the shortest paths from the source are known. Di] is an array and stores the length of the known shortest path from source to vertex i, We have a digraph G with 10 vertices and vertex 1 is the source. I the original data C[5,4] is damaged, then which part of the answer setD is unaffected? |___ procedure Dijeiro; { Dijkstra computes the cost of the shortest paths from veriex | to every vertex of a ditected graph } Desi wo eee ata Q iniitize Dy |__ «a for 1:= 1 t9 n—1 do begin o choose a vertex ib in V—S such that _ lw] is minimums o add w 0S; oO for each vertex» in VS do @ Div = min(Dlr}, Diw] + Cw. wD od anne end; (Dijkstra }

You might also like