This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: —n—..—__—__—'__—
Solutions to Quiz 2 Problem 1 Design an efﬁcient algorithm to ﬁnd a spanning tree for a connected, weighted.
undirected graph G = (V. B} such that the weight of the maidmumweight
edge in the spanning tree is minimized.
1itrisersr: The key observation is that. an},' minimum spanning tree minimizes
the weight of the maxhnumweight edge. Algorithm: Run Prim's algorithm to ﬁnd 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 cutandpaste 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. maximumweight edge
in T'. Then we are assuming that wie’} s: wﬁe).  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 maximumweight 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 maximumweight 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 ﬁrst inserting them into
the priority queueI and then repeatedly extracting the minimum. Design an
eﬂicient 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 modiﬁcation 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 Elﬁn] 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
DEMtime 2way 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 PWAYMERGE works as follows. Lil3e 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 ﬁnd
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. EXTRACTMIN toget the meﬁeet 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 EXTRACTMIN 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—WAYMEHGE: O{p+ ft] = Olin}
CeneetnueeISenT: Semeeemergeaert.
Run. time of Euler: TEn] = pT[nfja} + Gin}
Seirttion: Tm} = Gilli log, n} eaten heeeenﬁ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
appeari This Oﬁn log], n] time is asymptotically better than the Gin iglﬁnfpjl of
the ﬁrst approach shown above. nee we are not treating p as a. constant.
103,11 == (hamlet!) while Isiah!) = {Ian — lee} Prehlema Aeﬁrenteiegmeyheempairsuteirie. wherethe hdghteftheithpeirof
Skin is“. Thereerel'lskiere who wish to rent side. where the height of the
ftheiszieriehe Ideeﬂy,eecheiriereheuidehteieepeirefeitiewheeeheight
mateheehismheighteeeloeelyespueeihle. Dmiyameﬁeient algorithm to
maids maiden eothnt the sum of the eheuitste diﬁerencee of the heights
efeechekierendhieeﬁsieminimized. {Fhrpartinleredit,mm1em=n.} Answer: The key; observation is that there is no advantage to “cross
metehinf—mmﬁngtheheiﬂteedﬂefeﬁeteendsﬁs. Thetiejfnﬁeg
anth {hathereiemrmntamﬂehn'th Indlgﬂht. ' 'Iheheerthls.weﬁretluekateﬂthepdw'hlereletienehipeeftheeheighte.
Indjhuwthetthe “met‘ efmetchingtheehortereftweeﬁerewiththe
eherternfteueideheiweysetleaetugmdeethematefmmetehing
them. "Withnut lose 61' generality, we can meme 51 it the melIeet height
(1153“) 1. Case 1:
The sum of the absolute djﬁerences of the matched ski,“ skier heights is
F If match .91 H ill and .92 44 fig,
hi 31+31h2=i$s—Sii" (he—hill
P Ifmatch 31 Hit: and a; H h“
he31+52—h1=i32—31}+ih«2—h1l
Sinoe (it; — hi} :3 0. the ﬁrst 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—i52h1i
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 ﬁrst matching oosts not more than the second.
3. Case 3 can be veriﬁed 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 subprohlems 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 ﬁrst 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 matd: 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 ﬁrst i skiers
with the ﬁrst 5‘ pairs of skis. Let A[i,j] he the optimal cost {sum of absolute
differences of heights} for matching the ﬁrst i skiers with the ﬁrst 3' pairs
of skis so that all i skiers have slris. The solution we seek is A[u,m.]. "We can deﬁne A recursively as follows: 13 ifi=ﬂorj=ﬂ
2‘1[1'1.i]= miﬂiﬂlisi  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 ﬁrst i skiers to
the ﬁrst 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 ﬁrst i— 1 skiers
with the ﬁrst 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___#_____.. ﬂies] 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 inﬂuence the value A[ﬂ,m]. To ﬁnd 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, "" Ifﬁliai] = 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 + moitime solution,
with bonus points for the Elﬁn 1g 11. + m lg m + [m — ninjtime 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 matchingup as the
Elinlgn} algorithm we saw for the in = at case. This kind of obsenation
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 = ﬂ[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 doomCt 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
Dﬂg in] time ﬁx a binary search of the skis.) P Note that conﬂicting 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 (Ffn?) 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,andconﬂictsareresohredbybumping
askiertoadiﬁerentpairofskis. ...
View
Full Document
 Spring '09
 STAFF
 Algorithms

Click to edit the document details