Exercise2_Solution_Part1

Exercise2_Solution_Part1 - —n—..—__—__—'__—...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 4
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 6
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: —n—..—__—__—'__— Solutions to Quiz 2 Problem 1 Design an efficient algorithm to find a spanning tree for a connected, weighted. undirected graph G = (V. B} such that the weight of the maidmum-weight edge in the spanning tree is minimized. 1itrisers-r: The key observation is that. an},' minimum spanning tree minimizes the weight of the maxhnum-weight edge. Algorithm: Run Prim's algorithm to find an MST Time: OLE -i— Vlg V] ifnse Fibonacci heap for queue Correctness: We need to show that an MST the weight of the maxhnmn—weight edge. Proof: We will use a cut-and-paste technique, similar to the proof of The- orem 24.1. Let T he a minimum spanning tree for G, and assume that some other spanning tree T“ is “better” than T. i Let e be a maidmnm—weight edge in T and a“ he a. maximum-weight edge in T'. Then we are assuming that wie’} s: wfie). - Removing e from T breaks T into two components. Some edge e“ in I" must connect these components. or T’ would be disconnected. Adding that edge to our disconnected components reconnects them to form a new spermng tree T” = T _— e + e". Note that wIEe") S wie’), because 93 is a maximum-weight edge in 3"“, and hence tale”) 5 tie“) e: site]. Thus T” has lower weight than T: w{T’) = wET} -— ro[e} + rote") -:: mlT} - But there cannot be a spanning tree T” with lower weight than T. because T is an MST. Thus an:,.r MST minimizes the weight of the maximum-weight edge. Note: The above answer gets full credit. It is, however, possible to come up with a better algorithm. Note that minimizing the weight of the maximum—weight edge is not as strong a constraint as minimizing the total weight of the tree- For example, sesame that there‘s an MST for G in which all edges have weight 1, except one edge that has weight 5. There might also he a. spanning tree in which all the edges have weight 5. The required spanning tree can he oonstructed in 0(Eo(E, V}] expected time with a dividemdeonquer algorithm that uses RANDOMIZED- PARIITION and ideas from Kruslral's algorithm. Problem 2 Professor Uriah has developed a hardware priority queue for his computer. The priority queue devioe can store up to p reoordsI each consisting of a key and a. small amount of satellite data {such as a pointer}. The computer to which it is attached. can perform loans: and Exraacr—MIN operations on the priority queue, each of which takes GU} time, no matter how many records are stored in the device. The professor wishes to use the hardware priority queue to help implement a sorting algorithm on his computer. He has n records stored in the primary memory of his machine. If u 5 p, the professor can certainly sort the keys in Din} time by first inserting them into the priority queueI and then repeatedly extracting the minimum. Design an eflicient algorithm for sorting n :5 p items using the hardware priority queue. Analyze your algorithm in terms of both a and p. “This prohlmn is from an idea suggested by Mike Attallah.}} Answer: The idea is to do a modification of merge sort. r{litre idea {worth a little partial credit} is based on Problem 1—2 in the hook. Since the hardware can sort p items in Elfin] time, we can divide the input into nfp lists of length p, sort the lists using the queue in [ufp] rD(pj = D{u]l time, and then merge the lists in anlgmfpj} time as shown in Problem l~2h. The total time for this algorithm is G{nlg{nfpj}. The above approach uses the hardware only for sorting sublists; the hard ware doesn’t help with the merging. A hotter idea [north full credit} is to use the hardware to implement a p—way merge that runs in Olfnjl time [for 1: lists containing n elements total}, and use it the same way merge sort uses its DEM-time 2-way merge. Algorithm: Soar-{A} if A has length 1 then return Divide A evenly into 1:: suharrays A1,. “A SoariAI}, . . -, Soar{A,,} P—War—Mnuoeml, . . . , A?) F P-WAY-MERGE works as follows. Lil-3e 2—way MERGE, it repeatedly moves the smallest element (the minimum of the elements at the front of the p lists] from the input lists totha output list. The hardware queue is used to find the minimum each time in only 0(1) time {instead of the 011p} time it would normally take to scan the p list minimums}. At any given time, the queue holds the minimum element each list. 1. Start by moving the smallest element from each list into the hardware queue, along with an indicator'of which list it came Erom. T‘ime: 11 elements, on) an to lesser each e orer total time 2. EXTRACT-MIN toget the mefieet element. Say it when: the ithserted list. Mme the next element [if any} from the ith list into the queue. to replace the one that wee just Time: {3111] to EXTRACT-MIN end to INSERT Repeat this EXTRACTeMIHfINSERT until all n elements have been ex- treated. Time: 11. iterations. 0(1) time each =9 DEVI} tetel tinte- Run time of P—WAY-MEHGE: O{p+ ft] = Olin} CeneetnueeISenT: Semeeemergeaert. Run. time of Euler: TEn] = pT[nfja} + Gin} Seirttion: Tm} = Gilli log, n} eaten heeeenfi-emereeureien tree: 121%" when: {The master theorem is not appropriate because we don’t went to treat 1: as a constant. Case 2 of the theorem would give us Utfnign}. in which p deem't appear-i This Ofin log], n] time is asymptotically better than the Gin iglfinfpjl of the first approach shown above. nee we are not treating p as a. constant. 103,11 == (hamlet!) while Isiah!) = {Ian — lee} Prehlema Aefirenteiegmeyheempairsuteirie. wherethe hdghteftheithpeirof Skin is“. Thereerel'lskiere who wish to rent side. where the height of the ftheiszieriehe Ideefly,eecheiriereheuidehteieepeirefeitiewheeeheight mateheehismheighteeeloeelyespueeihle. Dmiyamefieient algorithm to maids maiden eothnt the sum of the eheuitste difierencee of the heights efeechekierendhieefisieminimized. {Fhrpartinleredit,mm1em=n.} Answer: The key; observation is that there is no advantage to “cross metehinf—mmfingtheheiflteedflefefieteendsfis. Thetiejfnfieg anth {hathereiemrmntamflehn'th Indlgflht. ' 'Iheheerthls.wefiretluekateflthepdw'hlereletienehipeeftheeheighte. Indjhuwthetthe “met‘ efmetchingtheehortereftweefierewiththe eherternfteueideheiweysetleaetugmdeethematefmmetehing them. "Withnut lose 61' generality, we can meme 51 it the melIeet height (1153“)- 1. Case 1: The sum of the absolute djfierences of the matched ski,“ skier heights is F If match .91 H ill and .92 4-4 fig, hi -31+31-h2=i$s—Sii" (he—hill P Ifmatch 31 Hit: and a; H h“ he-31+52—h1=i32—31}+ih«2—h1l Sinoe (it; — hi} :3- 0. the first matching costs less than the second. 2. Case 2: The sum of the absolute differences of the matched skifakier heights is e Ifrnatoh s1H hi and 32 H fig, h1_51+h'2—32={h2 *31i—i52-h1i 9' [fmatch .9; H h; and 32 u—r hi: hi —31+32—h1 z “12—31er- {32 —h1] Since {an - hi) 3 i]. the first matching oosts not more than the second. 3. Case 3 can be verified similarly. v To show that there is always an optimal solution with no cross matching. let 3 he an optimal matching. If 5' has no cross matches. we are done. OtherwiseI oousider two skiers and two skis involved in a cross match. and reverse their matching so that the shorter of the two skiers has the shorter of the two skis. We saw show that this change cannot increase the cost of the match, so this revised solution is at least as good as 5'- Algorithms: - If m. = a. simply sort the skiers by height, sort the skis by height, and match the ith skier with the ith pair of skis. Correctness: Any other assignment would have a cross match, so this so- lution is optimal. Time: amigo} {to sort the lists} * If m at a, start as before by sorting the skiers and skis {because there’s no advantage to matching them up out of order}. Then use dynamic pro- gramming, as follows. _ First of ail, notice that dynamic programing is an appropriate approach. 9- If you try all ways of matching up the skiers and skis, there will be lots of repeated subprohl-ems Imagine that you've matched in H 3:" and then decide to match in; o— si. You're left with the same suhprohlem as when you first try matching in; H s; and then select in H .35 next. ”* Solutions have optimal substructure. Imagine that some subset of an optimal matching is not optimal — that there’s a better wag,r to match that subset of skiers with that subset of skis. Substituting that better suhset mat-d: in the original solution improves the original solution, so it couldn't have been optimal. Assume that 1-: :5 so (there are more skis than skiers]. {This is okay because the problem is symmetrical: If m. c: a just interchange the skiers with the skis in the algorithm. In any case, you want to match up all of whichever thing there are fewer of.) After sorting the skiers and skisI consider how to match the first i skiers with the first 5‘ pairs of skis. Let A[i,j] he the optimal cost {sum of absolute differences of heights} for matching the first i skiers with the first 3' pairs of skis so that all i skiers have slris. The solution we seek is A[u,m.]. "We can define A recursively as follows: 13 ifi=florj=fl 2‘1[1'1.i]= miflifllisi - H1145" 1.3' - 1l+ Ihe — Sill if 1 S i 53' oo ifioj 3 i This is correct because ” If there's an optimal match not using 5:. it matches the first i skiers to the first 3' — 1 pairs of siris. a If there's an optimal match using 45,-, it can assign h.- H 3;, because all skiers {it's} get matched up, and any other wag.r of using both hi- and s; would either be a cross match or would involve another skier of height: in or another pair of skis of height= sJ: {and would thus has the same cost as this match}. The rest of the match must be an optimal match of the first i— 1 skiers with the first 3' — 1 pairs of skis. Since Ah, 3'] depends on a Value in the previous row of A and an earlier mine in the same row of A. calculate A in row—major order [top row to bottom row, left to right within rows.) this (s) m________v___#_____.. flies] Note that only the part of A between the diagonal lines needsto be com- outed1 because the triangle at the bottom left just has so and the triangle at the upper right [marked 1"]I does not influence the value A[fl,m]. To find the actual assignment of skiers to skis, we can trace a path from Afn,m] to see where each value came from. At each step, "" Iffiliai] = AItj ‘ 1]. continue tracing at inc,- _1], :- Cltherwise, match hr H a; and continue tracing at AH — 1T 3' — 1], Time: 6(1rt1gn} to sort skiers + G{mlgm} to sort skis + 3001 — njn to compute A =e 91:11 lg'n. + mlgm+ {m — elm] Notice that when m. = n, this comes to {31:11. lg a), like the simple algorithm shown above for the m = 11 case. If you compute the whole A table, the time is S[nlgn + mlgm + ma}. Note: Full credit was given for the 81:11 lg n. + m lg to + moi-time solution, with bonus points for the Elfin 1g 11. + m lg m + [m — ninj-time solution. If you come up with Bfn lg n + to lg m + me), however, you might suspect that there is a better solution, since this reduces to Son?) when m. = 1'1, but the algorithm is doing essentially the same in—order matching-up as the Elinlgn} algorithm we saw for the in = at case. This kind of obsenat-ion is typical of what happens in algorithms research: if the time needed by a general algorithm in a special case is greater than the time needed by a more specialized algorithm for that case, there may he a better general algorithm. Also note that if n s: or there’s a. way to improve the algorithm by using only 11.2 of the m skis during the dynamic programming. rs: example, if m = Elma}, working with in skis contributes {m — njn = fl[n3] to the time, but using ordy n2 pairs of skis tightens that term to ow). The total time is Bmlgn + mlgm + [min{m, 1'12} — njn}. {The 1:.2 candidate pairs of skis can he picked in 06.1 lg m + n?) time, which doom-Ct aEect the total asymptotic running time of the algorithm.) To pick the candidate skis, D Assume the skis are sorted, which we need to do anyway '- Match each skier to the best pair of skis, in 0|[nlg or) time. {It skiers x Dflg in] time fix a binary search of the skis.) P Note that conflicting choices can't force a skier to he bumped more than n. 'skis away, because at most in. pairs of skis on either side of the best choice can have hoen chosen for someone else. D In (Ff-n?) time, select the Dirt“) candidate pairs of skis as follows: For each skier, take the n skis preceding and the n skis following the best- matching pair of skis. '- It is also possible to devise a greedy matching algorithm in which each skier ismatchodtothehestpairofslds,andconflictsareresohredbybumping askiertoadifierentpairofskis. ...
View Full Document

This note was uploaded on 10/21/2011 for the course COT 6401 taught by Professor Staff during the Spring '09 term at FAU.

Page1 / 6

Exercise2_Solution_Part1 - —n—..—__—__—'__—...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online