In this course, our focus will be largely on problems in 2-dimensional space, with occasional forays into spaces of higher dimensions Because the field was
Computational Geometry Exercise 1 Exercise 2 a1 3 http://www ti inf ethz ch/ew/courses/CG10/ 3 S1 a2 Exercise 3
Computational Geometry http://www ti inf ethz ch/ew/courses/CG07/ Exercise 1 (10 points) k a1 S1, , ak Sk k O(n 2 n) k k Exercise 2 (10 points)
These lecture notes are designed to accompany a course on “Computational Geometry” three hours of lecture and two hours of exercises each week
The exercises below are intended to provide a means to test your understanding of the programming-related material covered in the course
https://cw felk cvut cz/doku php/courses/a4m39vg/start What is Computational Geometry (CG)? CG Solves geometric problems that require clever
19 oct 2015 · Course Information Lecture Slides Exercises Additional Material Computational Geometry in Computer Science Master's Studies
This course is about Computational geometry (theory): Study of geometric problems on geometric data, and how efficient algorithms that solve them can be
14 avr 2001 · Computational geometry is concerned with the algorithmic study of elemen- tary geometric problems Ever since its emergence as a new branch
algorithms to computational geometry 1 Geometric analogues of classical graph algorithm problems Typical issue: using geometric information
Copyright,DavidM.Mount,2012, Dept.ofComputerS cience ,UniversityofMaryland,CollegePark, MD, 20742.Theselecturenotesw ere
preparedbyDavidMountfor thecou rseCMSC754,Compu tationalGe ometry,attheUniversityof Maryla nd.Permiss iontouse,copy,modify,an d
distributethesenotesforeducationalpurpos esandwithoutfeeisherebygranted,providedthatthiscopyrightnoticeappearinall copies.
recognition,andithasalsobeenuse doftentodescrib ealg orithmsformanip ulatingcu rvesandsurfacesinsolid
modeling.Its mostwidelyrecognizedus e,however, isto describethesubfieldof algorithmt heorythatinvol ves
thedesig nandanalysisofe fficientalgo rithmsforproblemsinvolvinggeometricinputand output. Thefield ofcomputationalgeomet ryde velopedrapidlyinthe late70' sandthroughthe8 0'sand90' s,anditstillc ontinuestodevelop.Historically,c omp utationalgeometrydevelopedasa generalizationofthestudy of
algorithmsforsortingands earchingin1- dimensionalspacetoproblemsinvolvingmulti-dimensionalinputs. Becauseofits hist ory,thefieldofcomput ationalgeometryhasfocus edmostlyonproblems in2-dimensionalspaceandtoaless erextenti n3-di men sionalspace.Whenpr oblemsarec onsidered inmulti-dimensionalspaces,
itisu sually assumedthatthedimen sionofthespaceis asmallconstant(say,10orlower).Nonetheless,recent workinthis areah asconsidered alimitedset ofproblem sinveryhighdimens ionalspaces,par ticularlywith respecttoapproximation algo rithms.Inthiscourse,ourfocuswil lbelargelyonprobl emsin 2-dimensional space,withoccasional foraysinto spacesofhigherdimensions. Becausethefiel dwasdevel opedbyresearcher swhosetrai ningwasindiscretealgorithms(asopposedtonu- mericalanalysis)the fieldhasalsofocusedmore onthe discretenatureof geometricproblems( combinator ics andtopol ogy,inparticular), asopposedtocont inuousissues.Thefield primar ilydealswi thstraightorflatobjects(lines,l inesegments,polygons,planes,and polyhedra)orsimpl ecurv edobjectssuchascircles. Thisis
inc ontrast,say,tofieldssuch assolidmodeling ,wh ichfocusonissuesinvolvingcurvesandsurfacesandtheir representations. Therearemany fieldsofcomputers ciencethatdealwi thsolvingprobl emsofageometricnat ure.Thes eincl ude computergraphics ,computervisionandimageproces sing,robotics,computer-aideddesign andmanufacturing, computationalfluid-dynamics,andgeographi cinformationsystems,tonameafew .On eofthegoalsof com - putationalgeometryistopr ovidethebasic geometrictool sneededfr omwhichapplicationar eascanthenbui ldtheirprograms.T herehasbeensignifica ntprogressmadeto wardsthisgoal ,butitisst illfarf rombeingf ully
realized. ATypicalProbleminComputationalGeometry:Hereisanexample ofa typicalproblem, calledtheshortestpath problem.Givenasetpolygonalobstaclesintheplane,findtheshortestob stacle-avoidingpathfromsomegivenstartpoint toagivengoalp oint (see Fig.1).Althoughitispossibletoreducethisto ashortest pathproblemon
agraph(calledthevisibilitygraph,whichwewilldiscusslaterthissemester),andthenapplyanongeometric algorithmsuchasDijkstra' salgorithm, its eemsthatbysolvingthepr obleminit sgeometricdomainit should beposs ibletodevisemoreefficients olutions. Thisisoneofthemainrea sonsforth egrowthofinterestin geometricalgorithms. ststonconti nuousobjects(e.g.,s olvingdifferent ialandintegralequations) cannotguaranteethattheirresul ts
arecorrectnor thattheyconverge ins pecifiedamountoft ime.Notethatitispossibletoapproximate curvedobjectswit hpiecewiseplanarpol ygonsorpolyhedra.Thisassumptionhasfreedcomputational geometrytodealwit hthecombinator ialel ementsofmostofthepr oblems,asopposedtodealingwi th numericalissues. Emphasisonlow-di mensional spaces:Onemore limitationisthatcomputationalgeometry hasfocu sedpri- marilyon2-dimensional problems, and3-dimensionalproblemsto alimited extent .Thenicethingaboutindividualpairsofprimitiveentities(e.g., linesegments)inte rsect.Wewilldiscusseffic ientalg orithmsfor
computingtheinters ectionsofas etoflinesegments. TriangulationandPartitioning:Triangulationisacatchwordforthemore genera lpr oblemofsubdividinga complexdomainintoa disjointcol lectionof"simple" objec ts.Th esimplestregionin towhichoneca n decomposeaplanarobj ectis atriangle (atetrahedronin3-d andsimplexinge neral).Wewilldiscuss howtosubdi videapolygon intotrianglesandlater int hesemesterdiscussmore generalsubdivisionsinto trapezoids. Low-dimensionalLinearProgramming:Manyoptimizationproblemsincomputationalgeometrycanbestated inthe formofalin earprog rammingprob lem, namely,findtheextremepoints(e.g. highestorlowest) that satisfiesacollectiono fline arinequalities.Linearprog rammingisani mportantproblem int hecom- binatorialoptimization,andpeopleof tenneedtosolvesuchproblemsinhundredtoperhapsthousand dimensionalspaces.However therearemanyint erestingproblems(e.g.find thesmallestdi scencl osing asetofpoints)thatcanbeposedaslowdimensionallinearprogrammingproblems.In low-dimensional spaces,verysimpleeffic ientsolutionse xist. VoronoiDiagramsandD elaunayTriangulations:GivenasetSofpoint sinspace,oneofthe mostimportant problemsistheneares tneighborproblem. Givenapoint thatisn otinSwhichpointof Sisclo sesttoit? Oneofthe techniquesused fors olvingthispr oblemistosubdividespaceint oregions,accor dingtowhich pointisclos est.Thisgi vesrisetoageometricpar titionof spacecalledaVoronoidiagram(seeFig.3 ). Thisgeometric structurearisesin manyapplicationsofgeometry.Thedualstructure, calledaDelaunay triangulationalsohasmanyint erest ingproperti es. LineArrangementsandDual ity:Perhapsoneofthemostimportantmathematicalstructuresincomputational geometryisthatofan arrangementofli nes(orgeneral lyt hearrangementofcurvesands urfaces ).Givenn linesintheplan e,a narrange mentisjustthegraphforme dbyconsideringtheintersectionpoi ntsasvert ices andli nesegmentsjoini ngthemasedges(seeFig.4). Wewillshowthatsuch astructur ecanbeconstr ucted inO(n 2 )time. Thereas onthatthisstr uctureiss oimportantist hatmanyproblemsinvol vingpointscanbetransformed intoproble msinvolvinglinesbyameth odofpoint-lineduality.Intheplane,thisisatransformationthatSlopeStatis tics:Today,weconsider asimpl ewarm-upexerciseasanexa mpl eofatypicalproblemincomputational
geometry.Tomotivatet heproblem,imagi nethatamedicalexperimentisrun,where thetherapeuti cbenefitsof acertaintreatmentregimenisbeingstudied.Asetofnpointsinreal2-di mensionalspace,R 2 ,isgiven.We denotethiss etbyP={p 1 ,...,p n },wherep i =(a i ,b i ),wherea i indicatestheamountoftreatme ntandb i indicatesthetherapeuticbe nefit.Th ehypothesisisthatincreasingtheamountoftreatment by!aunitsresults ina nincrease intherapeuticbenefito f!b=s(!a),wheresisan unknown scalefactor. Ino rdertostudytheprop erties ofs,astatisticianconsidersthesetofslopesofthelinesjoiningpairs ofa points(sinceeach sloperepresentstheincr easei nbenefitforauni tincr easeint heamountoftreatment).For(seeFig.6 (a)).Sothatw edon'tnee dtoworrya boutinfinite slopes,letusmaketh esimplifyinga ssumptiontha t
thea-coordinatesofthepointsarepairwised istinct,and toavoidties, letusassu methatthe slopesare distinct.
CountingNegative SlopesandInversions:Inthis lecturew ewillconsiderthela stproblem ,thatis,c ountingthe
numberofslopesthatliewithinagiveninterval[s ! ,s + ].Beforeconsideringthegeneralproblem,letusconsider asimplerversionbyconsideringthecasewheres ! =0ands + =+#.Inotherwords,wewillcountthe numberofpai rs (i,j)wheres i,j isno nnegative.Thisproblemisinterestingstatistically,becauseitrepresents thenumbe rofinstancesinwhichinc reasingth eamountoftreatmentresult sinanincreaseinthetherapeut ic benefit. Ourapproach willbetocountthenumber ofpairs suchthat s i,j isstrictly negativ e.Thereisnolossofgenerality indo ingthis,sincewecan simplysubtrac tthecountfro m ! n 2 " too btainthenumberof nonneg ativeslopes.(The reasonforthisothe rformulatio nisthatit willallowustointroducetheconceptofin versioncount ing,whi ch willbeus efulf orthegeneralproblem.)Itwill simplifythepresentationtomaketheassumptiont hattheset sof a-coordinatesandb-coordinatesaredistinct. Supposewebegin bysor tingthepointsof Pininc reasingorderbytheira-coordinates.LetP=$p 1 ,...,p n %be theresulting orderedsequence ,andletB=$b 1 ,...,b n %bethe associated sequenceofb-coordinates.Observe that,for1"iToge neralizethistoinversioncounti ng,inadditio ntore turningthesorted subsequences,the recursivecalls
returnthecou ntsI L andI R ofthe inversi onswithineachoft hesubs equences.Inthe mergingprocesswecount theinversio nsIthatoccur betweenthetwosub sequenc es.Thatis,foreachelementofB L ,wecomputethe numberofs maller elementsinB R ,andaddthesetoI.Intheend,wereturnthetotalnumberofinversions, I L +I R +I. Thealgor ithmispresentedinthecodebl ockbelow.T omergethesubs equences,wemaintaintwoindi cesiand j,whichindicatethecurrentelementsoftherespectivesubsequencesB L andB R .Werepeatedly 2 copythe smallerofB L [i]andB R [j]tothe merged sequenceM.Becausebothsubsequencesaresorted,whenwecopy B L [i]toM,B L [i]isinv ertedwithrespecttotheeleme ntsB R [1...j!1],whosevaluesaresmallerthanit(see Fig.7(b)). Therefore,weaddj!1toth ecount Iofin versions. Themain loopstopsei therwheniorjexceedsthenumberofele mentsini tssubsequence.Whenw eexit,on e ofthe twosubsequences isexhausted.Weappend theremainingelementsoftheothersubsequencetoM.In 2thex-coordinateoftheirintersectionpoin tbyeq uatingtheright-handsidesofthes etwoequations,whi chyi elds
a i x!b i =a j x!b j 'x= b j !b i a j !a i .x-coordinateoftheintersectionofthe irduallin esisthesl opeoft heli nepassingt hroughthepoints(seeFig.8 ).
(Thereasonfor negatingthebcoordinateisnowevident. Otherwise,we wouldgett henegationofthe slope.)SlopeRangeCounting int heDual:Basedontheabo ve observations ,weseethatthepr oblemofcountingtheslopes
ofSthatliewithinthein terv al[s ! ,s + ]canber einter pretedinthefollowingequivalentform. Givenasetofn nonverticallinesinR 2 andgiv enaninterval[s ! ,s + ],countthepairsoflineswhoseintersectionsliewithinthe verticalslabwhoselefts ideisx=s ! andwhose rightsi deiss + (seeFig. 9(a)).Fig.8:Point- line dualityandtherelationshipbetweent heslopeofalineb etweentw opo intsand thex-coordinateof
theduals ofthetwopoints. (a)(b) x y s ! s + 6 5 4 3 2 1 6 4 2 1 3 5counting.Toseet his,observ ethattwo linesintersectwithinthe slabifand onlyifthe orde roftheirinte rsection
withthelef tside oftheslabisthe inverseof theirinters ectionwiththe right sideofthe slab. Weca nreduceth eproblemtoinversi oncountin g,therefore,asfol lows.First,considertheorderin whichthe linesintersect theleftsideoftheslab(take nfromtopto bottom).Inpartic ular ,theliney=a i x!b i intersectsat thepoint y=a i s ! !b i .Sortthelinesaccordingindecreasingorderofthesey-coordinates,thusobtainingthe orderfromt optobottom,andrenumber themfrom1 tonaccordingtothisor der(seeFig. 9(a)).Next,comput etheorder inwhichthe(renumbere d)lin esintersectth erightsideoftheslab.Inparticular,lineiisasso ciated
withthev aluey=a i s + !b i .LettingY=$y 1 ,...,y n %denotetheres ultings equence,itiseasytoseethat thenumbe rofinversionsin!Yiseq ualtothenumberofpa irsof linesthat intersectwithintheslab.T hetime toco mputetheintersectionalong theleftside andsortaccordingtothisorde risO(nlogn),andthetimeto computetheint ersectionswi ththerightsideandcounttheinversionsisalsoO(nlogn).Therefore,thetotal runningtimeisO(nlogn). NegativeSlopeRangeCountingRevisit ed:Bythe way,youmight wonderwhattheearlier ins tanceofcounting negativeslopesmapstointhisi nstance.Inthis caset heintervalis[!#,0].Observethataverticallineat x=!#(fromtoptob ottom)in tersec tsthelinesinincreasingord erofslope,orequivalently,inorderofa- coordinates.Thus,sortingthe pointsfrom toptobottomorderbyt heiri ntersectionwith s ! =!#iseq uivalent tothe sortingbya-coordinates,whichisjustwhatwewe didinthecaseofne ga tiveslop es.Theri ghtsideofthesl abisdeterminedbyt het op-to-bottom orderofinter secti onsofthelineswithverticalline
atx=0.Clearly,lineiintersectsthisverticalaty=!b i .Therefore,countingtheinversionsofthesequence !Y=$!y 1 ,...,!y n %iseq uivalenttotheprocessofcountinginversio ns inthesequenceB=$b 1 ,...,b n %, exactlyaswedidbefor e.Thu s,thec aseofcoun tingnegativeslopescanindeed beseentobea specialcaseof thisalgorith m. Review:Insum mary,wehaveseenhowan appare ntly2-dimensionalg eometricprobleminv olvingO(n 2 )(implicitly defined)object scanbesolvedin O(nlogn)timeth roughreductiontosimple1-d imensionalsortingalgorithms. Namely,weshowed howto solvethesloperangecounting problemin O(nlogn)time.Thep roblemsof computingtheminimumand maximumslopescan alsobesolved inO(nlogn)time.Wewillle avethisp roble m asane xerci se.Theproblemofcomputingthek-thsma llestslopeisaconsid erablyharder prob lem. Itisnot toohardto devisearando mized algorithmwhoserunn ingtime isO(nlog 2 n).Suchanalgorithmappliesa sortof"ra ndomize dbinarysearch"indualspacetolocatetheintersectionpointofthedesiredrank.Improving theexpe ctedrunningtimetoO(nlogn)timeis ano ntriv ialexercise,andmakingthealgo rithmdeterministicis evenmorec hallenging.I donotknowofanefficientsolutiontotheproblemofcomputingtheaverageslope. Thereduct ionofageometricproblem to1- dimensi onalsortingands earching isquitecommonincomputational geometry.Wewillseeot herexamplesoft hislaterint hesemester.Wehave alsoseena niceapplicationo fthe notionofpoint-li neduali ty,whichwillbeseenmanymoreti mesthiss emester.Convexity:Letuscons idera fundamentalstructure incomput ationalgeometry,calledtheconvexhull.Wewillgive
amoreformaldefinitionlater,but,givenasetPofpoi ntsintheplane,t heconvexhul lofP,denotedconv(P), canbedefined intui tiv elybysurroundingacollectionofpointswitha rubberbandandthenlett ingt herubber band"snap" tightlyar oundthepoints(seeFig.10). Thereareanumber ofreasonst hatthe conve xhull ofapointsetisanimportantgeometricstructure.Oneis thatitisoneo fthe simplest shapeappro ximationsfo rasetofpoints.(Otherexamplesincludeminimumarea enclosingrectangles,circl es,andellipses.)Itcanal sobeusedforapproximatingmorecomplexshapes.For example,theconvexhullofa polygoni ntheplaneorp olyhedronin 3-spaceist heconvexhullofi tsvert ices. Alsomanyalgorithms computetheconvex hullasaninitialst agein theirexecut ionortofilterout irrelevant points.Forexample,thediameterofapoi ntset isthemaximum distancebetween anytwo pointsoftheset.ItThebreakpointscommonto bothhulls willbethe leftmostandright mostverticesoft heconv exhull,t hatis,the
pointsofPhavingthesmalles tandlargest x-coordinates,respectively.(Bygene ralposition,wemayassume therearenodu plicatex-coordinates,andsotherewillbeauniqu eleftmostpoin tan duniquerightmostpoints.) Afterbuildingboth,the twohullscanbeconcatenated intoasinglecyclicco unterclockwiselist.Letusj ustcons iderhowtocomputet heupperhull,since thelowerhullis similar.Reca lltha tthepointsofPare
firstsortedin increasingorderoftheirx-coordinates,andtheywillbeaddedo ne-by-one. Westorethevertices ofthe currentupperhull inastackH,wherethetopofthestackcorrespondstothemostrecentlyaddedpoi nt ofP.LetH[top]denotethetop ofthestack, andletandH[top!1]denotetheelement immediatelybel owthetop.Observeth ataswereadthestac kelementsfromto ptobot tom(thatis, fromrighttoleft)c onse cutive triples
ofpoint softheupperhullwil lmake a(stri ct)"l eft-handt urn"(seeFig .11(b)).A swepushnew pointsonthe stack,wewillmainta inthisprop erty,byp oppingpointsoffofthe stackift heyfailtosat isfyt hisproperty. Turningandorientati ons:Beforeproceedingwith thepresentationof thealgorithm,w eshouldfirstmakeashort digressiontodiscussthemeaningof"l eft-handtur n."Givenanorderedtripleofpoints$p,q,r%inthe plane,wesay thattheyhave positiveorientationifthe ydefineaco unterclockwiseorientedtria ngle (seeFig.12(a)),
negativeorientationifthe ydefineaclo ckwiseorientedtriangle(see Fig. 12(b)),andzeroorientation ifthe yare
collinear,whichincludesaswellt hecasewheret woormoreofthepointsareidentical(seeFig.12(c)).Note thatorientation dependsontheorderinwh ichthepointsaregiven. (a)(b) (c) p q r p q r p q r p=r q orient(p,q,r)>0orien t(p,q,r)<0orien t(p,q,r)=0q.Thusorientationgeneralizes<,=,>in1-d imensionalspace.Alsonotethatthesignof theorientationofanorderedtriplei sunchangedi fthe pointsaretran slated,rotated,orscaled(bya positivescale
factor).Areflectiontran sfo rmation,e.g.,f(x,y)=(!x,y),reversesthesignoftheorientation.Ingeneral, applyinganyaffinetr ansformation tothepoi ntaltersthesignoft heori entationaccordi ngtothesignofthe matrixusedin thetransformation. Givenasequenceofthree pointsp,q,r,wesaythatthesequence$p,q,r%makesa(str ict)left-handturnifOrient(p,q,r)>0.
Graham'salgorithmcont inued:Letp
i denotethenext pointtobeadded inthelef t-to-r ightorderingoft hepoint s (seeFig.1 3(a)).Ifthetriple$p i ,H[top],H[top!1]%formsastrictleft-ha ndtu rn,thenw ecansimplypushp i ontothest ack.Otherwise, wecaninferthatthe middlepointofthe tripleH[top]cannotbe onthe upperhull ,andso wepopitoff thes tack.W erepeatthis untilreachi ngapositivelyorientedtriple(seeFig. 13(b)),orthere
arefewert hantwoelementsont hestack.Thepoppi ngprocessendswhenp i 'spr edecessoronthestackisits predecessorontheconvexhul l(s eeFig.13(c)) .Thealgorithmis presentedin thecodeblockbelow. (b) p i p j (c) pop p i p j (a) processingp i afteraddingp i p i p j pop beforeaddingp iFig.13:Graham's scan.
Graham'sScan
(1)Sortthe pointsaccordin gtoincre asingorderofth eirx-coordinates,denoted'p1,p2,...,pn(. (2)pushp1andthenp2ontoH. (3)for i#3,...,ndo: (a)while(|H|)2andOrient(pi,H[top],H[top&1])%0)popH. (b)pushpiontoH. Correctness:WhyisGr aham's algorithmcorrect?Wecans howinductivelythatthe contentsofHatany stageof thealgorith mconstitutetheupperhu llofthepointsthatha vebe enprocessed sofar.Fortheinductionbasis (H={p 1 ,p 2 })thisistriviallytrue.Fortheinductionstep,observethatp i isth erightmostp ointamongthe pointsprocesseds ofar,andthereforeit mustlieon theupperhull.Letp j bethe neighboringv ertextop i on theuppe rhullofthefirstipoints(seeFig.13( a)).Itiseasy toseet hatp j mustbeinHpriortotheaddit ion ofp i .Eachpointp k inHthatliesbetwee np j andp i liesben eaththeedgep j p i ,andsop k shouldnotbepart ofthe upperhullafter p i isad ded.Foreachsuchpoint itiseasytoseeth atOrient(p i ,p k ,p j )"0.Itfollows that,aseach ofthesep ointsp k isteste dwithinthewhileloo p,itwillbe deleted .(Weareb eingabitslo ppy here,becausethi sisnotexact lythesameorient ationtes tmadebyt healgor ithm,since p j isno tnecessarilyp k 's predecessoronthestack.W e'll leavefixing thisproofupasa nexercise.)Finally,whenp
j reachesthetopofthestacke itherfind thatp j =p 1 ,andhencetherearelessthantwoelementsonthe stack,orwefind thatwefinallyhave the tri plet hatsatisfiestheorienta tiontest.Ine ithercase,theloop
terminatesandp i ispu shedonthestack,asde sired. Thelo werhullcanbecomputedbyan essentiall ys ymmetri calgorithm,butworkingfr omrightto leftinstead. Oncethetw ohulls arecomputed,wesimply concatenatethetw ohullsintoasinglecircularlist.LectureNotes13CMSC754
Running-timeanalysis:Wewi llshowthatGr aham'salgori thmrunsinO(nlogn)time.Clea rly,ittakesthismuch timefor theinitialso rting.Afterth is,wewillshowtha tO(n)timesu fficesfortherestofthecomp utation. Letd i denotethenumberof pointsthatar epopped( deleted) onprocessingp i .Becauseeachorientationtest takesO(1)time,theamo untoftime spentprocessingp i isO(d i +1).(Theextra+1isfor thelastpo inttested, whichisnot deleted.)Thus ,thetotal runningtime isproportionalto n ' i=1 (d i +1)=n+ n ' i=1 d i .Tobo und
( i d i ,observethateachofthenpointsispushedont othestack once.Onceapointi sdeleteditcan neverbedeletedagai n.Since eachofnpointscanbedeletedat mostonce, ( i d i "n.Thusaftersorting,the totalrunningtime isO(n).Sincethisistrueforthelowerhullaswell,thetotaltimeisO(2n)=O(n). ConvexHullbyDivide-and-Conquer: Aswiths orting,ther earemanydifferent approachestosolv ingtheco nvex hullproblemf oraplanarpointset P.NextwewillconsideranotherO(nlogn)algorithm,whichisbasedon thedivid e-and-conquerdesigntechnique.ItcanbeviewedasageneralizationofthefamousMergeSortsortingalgorithm(seeanystandardal gorithmstext). Hereisan outlineofthe algorithm.It beginsb ysortingthepoints
bythei rx-coordinate,inO(nlogn)time.There mainderofthe algorithmisshowninthecodese ctionbelow .Divide-and-ConquerConvexHull
(1)If|P|%3,the ncomputethe convexhullbybrutefo rceinO(1)timeand return.(2)Otherwis e,partitionthepointsetPintotwose tsAandB,whereAconsistsofhalfthepointsw iththelow estx-coordinates
andBconsistsofhalfofthepo intswiththe highestx-coordinates. (3)Recurs ivelycomputeHA=conv(A)andHB=conv(B). (4)Merge thetwohullsintoacommo nconve xhull,H,by computin gtheupperandlowertangen tsforHAandHBand discardingallthepointslyingbetwee nthese twotange nts. Theasympt oticrunningtimeofthealgori thmcanbeexpress edbyarecurrence.Givenaninputofsizen,considerthetimeneeded toperform allthepartsoft hepr ocedure,ignoring therecursivecalls. Thisincludes the
timetop artition thepointset,compu tethetwota ngents,andreturnthefinalresult.Clearlythefirstandthirdof
thesestepscan beperformedinO(n)time,assumin galinkedlistrepresen tation ofthehullvertices.Belowwe wills howthatthetangentscanbecomputedin O(n)time.Thu s,ignoringconstant factors,wecandescribeth e runningtimebythefollowin grecurren ce. T(n)= )1ifn"3
n+2T(n/2)otherwise. Thisisthe samerecurrence thatarises inMergesor t.Itiseasytosh owth atitsolvestoT(n)(O(nlogn)(see anystandard algorithmstext).All thatremainsisshowinghowto comput ethetwotangents. Onething thatsimplifies theproces sofcomputingthetangentsisth atth etwopointsets AandBareseparatedfromeac hotherbyavertica lline(assumingnodu plicatex-coordinates).Let'sconcentrateonthe lowertangent,
sincetheuppe rtangen tissymmetric.Thealgo rithmoperatesbyasimple"walking"procedure.Weinitialize atobe therightmost pointof H A andbisthe leftmostpoin tofH B (seeFig.1 4(a)).Thesetwo pointscanbe computedinli neartime. Lowertangencyi saconditionthatcan betested locall ybyanorientationtestinvolvingthet woverticesand neighboringverticesonthe hull.Weiteratethefol lowi ngtwolo ops,whichmarchaandbdown,until they reachthepointslo wertang ency(seeFig.14(a )-(c)).Givenapointaonthe hull,leta.succanda.preddenote itssuc cessorandpredecessorinCC Worderabo utthehull.Thecondition"abisnotthelowertangentofH
A "canbeimplementedwiththeorientationtestOrient(b,a,a.pred))0,andtheothertestforH
B isan alogous.Provingthecorrectnessofthis procedureisalittletrick y,butnottooLectureNotes14CMSC754
AaABB B
a b b b (a)(b)(c) lowertangent uppertangent A aFig.14:Computing thel owertangent.
FindingtheLowerTan gent
LowerTangent(HA,HB):
(1)Let abetherig htmostp ointofHA. (2)Let bbethelef tmostpo intofHB. (3)While(abisno talowertang ent forHAandHB)do (a)While(abisno talowertang ent toHA)doa#a.pred(mov eaclockwise). (b)While(abisno talowertang ent toHB)dob#b.succ(movebcounterclockwise). (4)Returnab. hard.(Theis sueispro vingthatthetwoinner whileloopsne vergobe yondthe lowertangentpoi nts.)See O'Rourke'sbookoutforacarefulproof .Theimpor tantthing istha teachverte xoneachhullca nbevisitedat mostoncebythes earch, andhenceits runningtime isO(m),wherem=|H A |+|H B | " |A|+|B|.Thisis exactlywhatweneede dtogettheovera llO(nlogn)runningtime. Gift-WrappingandJarvis'sMarch:Thenext algorithmt hatwewillconsiderisavari antonanO(n 2 )sortingalgo-rithmcalle dSelectionSort.Fo rsorting,thisalgorithmrepeatedlyfindsthenext elementt oaddtothe sortedorder
fromtherem ainingitem s.Thecorrespondingconv exhullalgorithmiscalledJarvis'smarch.whichbuildsthe hullinO(nh)timeby aprocess calle d"gift-wrapping".Thealg orithmoperatesbyconsid eringany onepoint thatisontheh ull,sa y,thelowe stpoint. Wethenfindth e"next"ed geonthehullinco untercloc kwiseorder .Assumingthatp
k andp k!1 werethelasttw opointsadded tothehull,computethepoint qthatmaximizesth e angle!p k!1 p k q(seeFig. 15).Clearly,w ecanfindthe pointqinO(n)time. p 0 =(!",0) p 1 p 2 p 3 qFig.15:Jar vis' smarch.
Afterrepeatingthishtimes,wewillretu rnb ack tothestartingpoin tandwearedone.Thus ,theover allrunning timeisO(nh).Notethatifhiso(logn)(asymptoticallysmallerthanlogn)thenthisisabettermethodthanGraham'salgorithm.
LectureNotes15CMSC754
Onetechnicaldetail isthatwhen wetofind anedgef rom whichtostart.Oneeasywaytodothisistoletp 1 be thepoint withthelowesty-coordinate,andletp 0 bethe point(!#,0),whichisinfinitelyfartotheright.The pointp 0 ison lyusedforcomp utingtheinitiala ngles,afte rwhichitisdisc arded(seeFig.15).Lecture4:MoreonConvexHull s
OutputSensitiv eConvexHullAlgorithms:Weha veseentwoalg orithmsforp lanarconv exhull,Graham'salgo- rithmand thedivide-an d-conqu eralgorithm,thatbothruninO(nlogn)time.Weha vealsose enJarvis's algorithm,whichrunsinO(hn)time,wherehisthe numbero fverticesonthehull.Traditionally,algorithmsareanalyzedinte rmsoftheirrunningtimeas afunctionofinputs izeal one.Ho wever,
manygeometricalgorithms produceoutputswhoses izesvarygreatly(fromaconstant uptoalargepolynomial inn).Fo rsuchproblem s,itiscommon toexpressrunningtimeasafunctionofboththeinp utandth eoutput sizes.Suchan algorithmissaidtobeoutputsensit ive.Jarvis'salgorithmissuchanexample. Whenhisasy mptoticallysmallerthanlogn,Jarvis'salgorithmissuperiortoGraham'salgorithm.Sinceneit her algorithmisoptimalinall cases,iti snaturaltowonderwhe therthereissome "ultimate"plana rco nvexh ull algorithmthatisoptimalwit hrespectto bothnandh.Sincetheobject iveist ooutputthepointsonthehulli ncyclicord er,itisprettyeasytoseeth atth isre quiressort-
ingthepo intsofthe hull.Itiswellknownth atany comparison-basedalgorithm forsortingrequires"(nlogn) time. 3 Ifwe ignorehandconsi dertheworstcase inwhichall ofthepointsarevert icesoftheco nvexhu ll,then itisp rettye asytoprovetha tthe"(nlogn)lowerboundc annotbebeaten.(We leavetheproofofthisasa n easyexerci se.Laterinthesenoteswepresentanout putsensitivelowerbou nd.) Today,wepresenta planar convexhullalgorithm, cal ledChan'salgorit hm,whoserunningtimeisO(nlogh), andweshow thatth isisessenti allythebestp ossible.Whil ethisalgorit hmistoosmallanimprovemento verGraham'salgorithmtobepractical, itisquiteinteresting nonethelessfromtheperspect iveofthetechniques that
ituse s. •Itisd eriv edbasedonacombinationo ftwosloweralgorith ms,Graham'sandJarvis's. •Itisb ased on"knowing"the finaln umberofverticesontheconvexhu ll.Sincethisnum berisnotknown, itad optsaninterestingguessin gprocess todetermineitsvalue(roughl y).Itisremarkablethatthet imeto runthegu essingversio nisasymptoticallythesam easifyouhadknown thenumberinadv ance! HowtoBeatGraham andJarvis:Tomo tivateChan'salgorithm,o bservethattheprobl emwithGraham'sscanis thatitsortsall thep oints,and henceis doomed tohavingan"(nlogn)runningtime,irrespective ofthesizeofthe hull.Onthe otherhand,Jarvis's algor ithmisnot limitedinthisw ay. Unfortunate ly,itiswaytooslow if
therearemanyp ointsonth ehull.So,how canwecombinethe setwoinsights toproduceafaster solutio n? Thefirs tobservationneededf orabetterapproachisthat,ifwehopeto achieve arunning timeofO(nlogh), wecanonly aff orda logfactordependingonh.So,ifwerunGraham'salgorithm,wearelimitedtosorting setsofsize atmosth.(Actually,anypolynomialinhwillwor kaswell.Thereasonis that,for anycons tantc, log(h c )=clogh=O(logh).Forexample,loghandlog(h 2 )areasymptot icallyequivalent.Thisobservation willcomein handylateron.) Howcanweuse thisobser vation?Suppos ethatwepartitionedthesetinto roughlyn/hsubsets,eachofsize h. Weco uldcomputetheco nvexhullofeachsubset intimeO(hlogh),whichwe'llcallaconvexmini-hull.The totaltimetocompu teall themin i-hullswouldbeO((n/h)hlogh)=O(nlogh).Wearewithinouroverall timebu dget,butofcoursewewould stillhavetofigu reouth owtomer gethesemini-hullsinto thefinalglob al convexhull. 3Recallthatasymptoti c!-notationisthe lower -boundanalogto theO-notationupperbound.Formall y,wesaythatafun ctionf(n)is!(g(n))
if,asntendstoinfinity ,theratio g(n)/f(n)isbounded. Thatis,fgrowsatleastasfas tasg.Th erearefastersor tingalgo rithmsthatarenot
comparisonbased,buttheyappl ytodiscreteobject ssuchassmallintege rsandstrings,nottorealn umbers.LectureNotes16CMSC754
Butwai t!Wedonotknowtheval ueofhinad vance,soitwouldseemthatwearestuck befo rewe evenget started.Wewilldea lwiththisc onundru mlater,but,justtogetthe ballrolli ng,supposefor nowthatwehadan estimateforh,callith " ,whosevalueisatleastaslargeash,butnottoomuchlarger(sayh"h " "h 2 ).Ifw e runtheab ovepa rtitioningprocessusingh " ratherthanh,thetotalrunningtimetocomputeallthemini-hullsisO(nlogh
" )=O(nlogh).Originalpoin tset
(a)(b)Partition(h
! =8) andmini-hullsFig.16:Part iti onandmini-hulls.
Thepart itioningofthepointsisdonebyanyarbit rary method(e.g.,justbreaktheinputupintogroupsofsize roughlyh " ).Of course,th eresultingmini-hullsmighto verlapo neanother(seeFig.1 6(a)and (b)).Although wepres umethath " isaro ugh approximationtoh,wecannotinferanythingaboutthenumbersofverticeson thevariou smini-hulls.Theycouldran gefrom3upto h " . Mergingtheminis:Thequest ionthatremainsishowt omergethe mini-hullsinto asingleglobalhull.Theideaisto runJarvis's algorithm,butwetre ateachmini-hullasifitisa"fatpoint".Ateachstep,ratherthancomputingtheangle fromthecurrenthull vertextoe verypo intoftheset,wec ompu tethetangentlinesof thecurren thull
vertextoeacho fthemi ni-hulls,inc ludin gthemini- hullcontainingthisvertex. (Therearetwot angentsfroma
pointtoami ni-hull,and weneedt otakecaretocomputetheproperone.) Notethatthe currentvert exison the globalconvex hull,soitcannotlie intheinterior ofanyofthemini -hulls.Amongallthesetangents,wetaketheoneth atyieldsthe smallestexternal angle.(Theproce ssisillustratedinFig.17(a).)Notethat,eventhough
apointcanappearonlyonceonthefinalglobalhull,asinglemini-hullmaycontribute manypoin tstothefinal hull. Youmigh tthinkthat,sin ceamini-hullmay haveasmanyash " vertices,thereisnothingto besavedincom- putingthesetangents overthestrai ghtforwardmethod. Thekeyisth ateach mini-hullisa convexpolyg on,andhenceit hasquiteabi tmore structurethan anarbi trarycoll ectionof(unsorted) points .Inparticular,wemake
useofthe foll owinglemma: Lemma:Consideraconvexpol ygonKinthe planean dapointpthatisexterna ltoK,suchthatthevertices ofKarestored incyclicorderinanar ray.Thenthe twotangentsfromptoK(moreformally,th etwo supportinglinesforKthatpassthrou ghp)caneachbecomputedintimeO(logm),wheremisthe numberofv erti cesofK. Wew illleavethep roofofthislemm aasanexer cise,butthekeyideaisthat,sincetheverticesofthehullform acyclicallysortedsequence,itispossibletoadaptbinarysearchtofindthede siredp ointsoftange ncywith p (Fig.17(b)).U singtheabovelemm a,itfollowstha tweca ncomputethetangent from anarbitr arypointtoa singlemini-hullin timeO(logh " )=O(logh). Thefinal "rest rictedalgorithm"(sinceweassumewehave theestimateh " )ispresentedinthecodeblockbelow.(Thekthstag eisillustratedinFig .17 (c).)Sincewedono tge nerallykn owwhatthevalueo fhis,itis possib le
thatourrestricte dalgorithmmayb erunwithavalueof h " thatisnotwith inthe prescribedrang e,h"h " "h 2 .LectureNotes17CMSC754
q 1 q 2 q 3 q 4 p k p k!1 Jarvis'salgorithm onmini-hulls kthstageof Jarvis'salgorithm (a)(c)(a)(b) binary search p K tangent Fig.17:Using Jarvi s'salgorithmt omergethemini-hulls. (Inpa rticular,ourfinalalgorithmwillm aintainthegua ranteethath " "h 2 ,butthelowerboundofhmaynot hold.)Ifh "Chan'sAlgorithmfortheR estrictedHullProblem RestrictedHull(P,h
" ): (1)Let r#!n/h " ". (2)Partition Pintodisjoin tsubsetsP1,P2,...,Pr,e achofsizeatmo sth " . (3)For (i#1tor) computeHull(Pi)usingGraham's scanandstoretheverticesinano rderedarray. (4)Let p0#(&*,0)andletp1betheb ottommos tpointofP. (5)For (k#1toh " ) (a)For(i#1tor) computepointtangentqi+Hull(Pi),tha tis,theverte xofHull (Pi)thatmaximize stheangle!p k#1 p k qi. (b)Let p k+1 bethep ointq+{q1,...,qr}thatmaximiz estheangle!p k#1 p k q. (c)Ifp k+1 #p1thenreturn 'p1,...,p k ((success). (6)(Unable tocompletethehullafterh " iterations.)Return"Failure:h " istoo small." Theupshot softhisare:(1) theJ arvisphasenever performsformore thanh " stages,and(2)ifh"h " ,the algorithmsucceedsinfindingthehull .Toanalyzei tsrunnin gtime,recallthateachpartitionhasroughlyh " points,andsotherear eroughl yn/h " mini-hulls.EachtangentcomputationtakesO(logh " )time,and soeach stagetakesato talofO((n/h " )logh " )time.By(1 )thenumb erofJarv isstagesis atmosth " ,sothetotal runningtimeoftheJarvisp haseisO(h " (n/h " )logh " )=O(nlogh " ). Combiningthiswit hthefactthatthe GrahamphasetakesO(nlogh " )time,theto taltimeofth erestricted algorithmisO(nlogh " ).Ifwemaintaintheconditionthath " "h 2 then,irrespective ofsuccessorfailure,the runningtimewillbeO(nlogh). GuessingtheHull'sSize: Theonl yquestionr emainingishowdoweknowwhat valuetogivetoh " ?Rememberthat, ifh " )h,thealgorithmwillsucceedincomputingthehull,andifh " "h 2 ,therunningtimeoftherestricted algorithmisO(nlogh).Clearlywedonotwanttotryavalueofh " thatiswayto ohig h,orwearedo omedto havinganexcessiv elyhi ghrunningtime.So,weshouldstartourguess small,andw orkuptolargervalues untilLectureNotes18CMSC754
weachiev esuccess.Eachtimewetr yatestvalueh "Asas tart,we couldtryh " =1,2,3,...,i,untilweluckoutassoonash " =h.Unfortunately,thiswouldtake waytool ong.(Con vinceyourselfth atthiswouldresultinatotaltimeof O(nhlogh),whichisevenworsethan Jarvis'smarch.)
Thenext ideawouldbe toperform adoublingsearch.Thatis,let'stryh " =1,2,4,8,...,2 i .Wh enwefirst succeed,wemighthaveoversh ottheva lueofh,butnotbymorethanafactorof2,thatish"h " "2h.The convexhullwillhave atleastthr eepoints,andclear lyforh)3,wehave2h"h 2 .Thus,thisvalueofh "willsatis fyourrequirements.Unfortunately,it turnsout thatthisisstilltoo slow.(You shou ldd otheana lysis
yourselfandconvinceyourself thati twillresult inarunningti meofO(nlog 2 h).Betterbutstillnotthebest.) Soif doublingisnot fastenough,whatisnext ?Recallthat weareallowed toovershoottheactualv alueof hbyasmuch ash 2 .Therefore,let'stryrepeatedlysquaringthepreviousguess.Ino ther words,let'stry h " =2,4,16,...,2 2 i .Clearly,assoonaswereachavalueforwhichtherestrictedalgorithmsucceeds,wehave h"h " "h 2 .Therefore,therunningtimeforthisstagewillbeO(nlogh).Butwhataboutthetotaltimefor allthepr eviousstages ?Toan alyzethetotaltime,co nsiderthe ithguess,h
" i =2 2 i .TheithtrialtakestimeO(nlogh " i )=O ! nlog2 2 i " = O(n2 i ).Weknowthatwewillsucceedassoonash " i )h,thatisifi=*lglgh+.(Throughoutthesemester, wewillus elgtode notelogarithmbase2an dlogwhenthebas edoesnot matter. 4 )Thus,thealgorithm'stotal runningtime(uptoconsta ntfacto rs)isT(n,h)=
lglgh ' i=1 n2 i =n lglg h ' i=1 2 i . Thisisageomet ricseri es.Let ususethewellknownfact that ( k i=0 2 i =2 k+1 !1.Weobtainatotalrunning timeofT(n,h)
1+lglgh
=n·2·2 lglgh =2nlgh=O(nlogh), whichis justwhat wewant.Inother words ,bythe "miracle"ofthegeome tricseries,thetotaltimetotryallth epreviousfailedguessesi sasymptoticallythes ameasthetimefor thefinalsuccessf ulguess .Thefinal algorithm
ispre sentedinthecodeblockbelo w.Chan'sCompleteConvex HullAlgorithm
Hull(P):
(1)h " #2.L#fail. (2)while(L,=fail) (a)Leth " #min((h " ) 2 ,n). (b)L#RestrictedHull(P,h " ). (3)ReturnL.LowerBound(Opti onal): Nextwewillsho wthatChan' sres ultisasymptoticallyoptimalin thesenset hatanyalgo-
rithmforc omputing theconvexhullofnpointswithhpointsonthehullr equires "(nlogh)time.Thep roofis ageneralizationoftheproofthatsortingasetofnnumbersrequir es"(nlogn)comparisons. Ifyo urecallthepro ofthatsortingtakes atleast "(nlogn)comparisons,itisbasedonthei deathatanys orting algorithmcanbedescribedint ermsof adecisiontree.Eachcomparisonhasatmost3outcomes(<,=,or>). Eachsuch comparisoncorr espondstoaninternalnodei nthetree.Theexe cutionofana lgorithmcanbeviewed asat rav ersalalongapathintheresulting3-ar ytree.Thehe ightofthetre eisalower boundo ntheworst-c ase runningtimeofthealgorith m.There areatle astn!differentpossibleinputs, eachofwhichmustbereordered 4Whenlognappearsasafactorwithi nasymp tot icbig-Onotation,th ebaseo fthelo garithmdo esnotmatterprovideditisacon stant.Thisis
becauselog a n=log b n/log b a.Thus,changingthebaseonlyalterstheconstantfactor.LectureNotes19CMSC754
differently,andsoyouhavea3-arytreewi that leastn!leaves.Anysuchtreemusth ave"(log 3 (n!))height. UsingStirling'sappr oximationforn!,thissolvesto"(nlogn)height.(Forfurt herdetails,seet healgorithms bookbyCor men,Lei serson,Riv est,andStein.) Wewi llgivean"(nlogh)lowerboundfo rtheconvexhullprob lem.Infa ct,wewillgi vean"(nlogh)lower boundont hefol lowingsi mplerdecisionproblem,whoseoutputis eitheryesorno. ConvexHullSizeVerificationPr oblem(CHSV) :GivenapointsetPandint egerh,doestheconvexhullofPhavehdistinctvertices?
Clearlyifthistakes "(nlogh)time,thenc omputingthehu llmusttakeatleastaslong. Aswithsortin g,we willas sumethatthecomputationisdescribed inthef ormof adecisiontree.Thesorts ofdecisionsthata typicalconvexhulla lgorithmwillmakewilllikelyinvolve orientationprimitives.Let'sbe evenmoregeneral, byass umingthatthealgorithmi sallowedt ocomputeanyalgebraicfunctionofthe inputcoordinates.(Thiswil l certainlybepowerfulenoughtoincl udeall theconvexhullalgorithmswehavediscu ssed.) Theresultiscalled analgebraicdecisiontree. Theinput totheCHSVpr oblemisas equenceof2n=Nrealnumbe rs.Wecanthinkofthesenumb ers asfor mingavectorinrealN-dimensionalspace,thatis,(z 1 ,z 2 ,...,z N )=#z(R N ,whichwewillcalla configuration.Eachnodeofthedecisiontreeisassociatedwithamultivariatealgeb raicformulaofdegreeat mostd,wheredisan yfixedconsta nt.Forexample, f(#z)=z 1 z 4 !2z 3 z 6 +5z 2 6 , wouldbeanalg ebraic functi onofdegree2.Thenodebranche sinon eofthreeway s,depen dingonwheth ertheresult isnegative, zero ,orpositive.Eachleafoftheresultingtreecorresp ondstoa possibleanswerthatthe
algorithmmightgive. Foreach inputvector#ztothe CHSVprob lem,theansweris either"yes"or"no" .Thesetofall"yes"points isjust asubseto fpo intsY,R N ,thatisaregioninthisspace.Givenanarbitraryinput#zthepurpo seofthe decisiontreeistot elluswhetherthispoi ntisin Yornot. Thisisdoneby walkingdown thetree,e val uatingthefunctio nson#zandfol lowingtheappropriatebranchesuntilarr ivingata leaf,whichis eitherlabeled "yes"
(meaning#z(Y)or"no".Anabstractexample(notfortheconvexhullproblem)of are gionofconfigur ationspaceandapossible algebraicdec isiontre e(ofdegree1)is showninthefollowing figu re.(Weha vesimplified
itby makingita binarytree.)Inthisca sethe inpu tisjustapairofrealnumber s. 1 2 3 4 5 6 no Y Y no no no no Y Y 1 2 3 4 5 6 Y YTheset
Hierarchicalpartition
Decisiontree
(a)(b)(c) Fig.18:Thegeometr ic inter pretationofanalgebraicdeci siontree. Wesa ythattwo points#u,#v(Yareinthe sameconnectedcomponentofYifthe reisapathinR N from#uto # vsuchthatallth epointsalong thepatha reinthese tY.(Therearetwoconnectedcomponentsinthefigure.)Wewi llmakeuseoft hefollowing fundament alresu ltonalge braicdecisio ntrees,duetoBen-Or.In tuitively,it
statesthatifyo ursethasMconnectedcomponents,t hentheremustbeatl eastMleavesinanydecisiontre e fortheset, andthe treemusth aveheighta tleastthe logarithmoft henumberof leaves.LectureNotes20CMSC754
Theorem:LetY(R
N beany setandlet Tbeany d-thord eralgebraicdecisio ntreethatdeterminesmemb er- shipinW.IfWhasMdisjointconnectedcomponents,thenTmusthaveheight atleast"((logM)!N).Wewi llbeginourp roofwithasimple rproblem .
MultisetSizeVerificati onProblem(MS V):Givenamultisetofnrealnumbers andanintegerk,confirmthat themultiset hasexactlykdistinctelements. Lemma:TheMSVpr oblemr equires"(nlogk)stepsintheworst case inthed-thord eralgebraicdecisio ntreeProof:Interm sofpointsinR
n ,thesetofpointsforwhichtheansweris"yes"is Y={(z 1 ,z 2 ,...,z n )(R n :|{z 1 ,z 2 ,...,z n }|=k}.Itsuf ficestoshowthatthereareat least k!k
n!k differentconnectedcomponentsinthiss et,becauseby Ben-Or'sresultitwoul dfollowthatthet imetotes tmembershipinYwouldbe " (log(k!k n!k )!n)="(klogk+(n!k)logk!n)="(nlogk).Considertheallthetuples(z
1 ,...,z n )withz 1 ,...z k settothedistinctintegersfrom1tok,andz k+1 ...z n eachset toanarbit raryinte gerin thesamerange.Clearlytherearek!waystosele ctthefi rstkelements andk n!k waystosel ectthe remainingelements. Eachsuch tuplehasexactlykdistinctitems,butitis nothard toseet hatifweatt empttocontinuous lymodifyone ofthesetuplestoequalanotherone,we mustchangethenumber ofdistinct elements,implying thateachof these tuplesisinadi fferentconnected componentofY. Tofin ishthelowerboun dproof,w earguethatanyin stanceofMSVcanbe reducedt othe convexhull size verificationproblem(CHSV).Thusa nylowerboundforMSVpro blemappliest oCHSVaswell. Theorem:TheCHSVpr oblemr equires"(nlogh)timetoso lve.Proof:LetZ=(z
1 ,...,z n )andkbean inst anceoftheMSVproblem.Wecreat eapoi ntset{p 1 ,...,p n } inth eplanewh erep i =(z i ,z 2 i ),andseth=k.(Observethatthepointslieonaparabola,sothatall thepoints areontheconve xhull.)Now ,ifthemultise tZhasexact lykdistinctelements,thentherear e exactlyh=kpointsinthepoi ntset(si ncetheothers arealldupli catesofthese)andsothereareexactly hpointsonthehull. Conver sely,if therearehpointsontheconve xhull ,thenthere wereexactlyh=k distinctnumbersinthemultis ettobegin within Z. Thus,wecannotsol veCHSV anyf asterthan"(nlogh)time,foroth erwisewecou ldsolveMSVinthe sametime. Theproof israther unsatisfyi ng,becauseitrelies onthefactt hatthereare manyduplicatepoints .Youmightwonder,doesthelower boundstillh oldifther earenoduplicates?Kirkpatri candSeidelactuallyproveastronger
(butharder)re sultthatthe"(nlogh)lowerbound holdsevenyouassumeth atthepointsared istinct.Lecture5:LineSegmentInte rse ction
Geometricintersections :Oneofthe mostbas icproblems incomputationalgeometryist hatofcomput ingi ntersec-
tions.Intersection computationin2-and3-spac eiscentraltomanydifferentapplicationareas. •Insolid modeling complexshapesareconstruc tedbyapplyingvariousbooleanoperations(intersection, union,anddiff erence)t osimpleprimitiveshapes .Theprocessiscall edconstructivesolidgeometry(CSG). Computingintersecti onsofmodelsurfacesisanessentialpartofthepr ocess.•Inro boticsandmotionplann ingitisimportan ttoknowwhent woob jectsintersectforcollisiondetection
andcollisionavoidance.LectureNotes21CMSC754
•Inge ographicinformationsystemsitisoftenusefu ltooverlaytwosubdi visions(e.g.aroadnetworkand countyboundariest odeterminewhereroad maintenanceres ponsibilitieslie).Sincethesenetworksare formedfromcollection soflinese gments,thisgeneratesaproblemofdeterminin gintersectio nsofline segments. •Inco mputergraphics,rayshoo tingisan importantme thodforrenderingscen es.Thecomputationally mostintensive partofrayshootingisdeterminingtheinter sectionoftheraywith otherob jects. Linesegmentint ersection:Theprobl emthatwewillconsi deris,giv ena setSofnlinesegmen tsintheplane, report(thatis,outpu t)allpointswh ere apairoflinesegmentsinters ect.Weassumethateachlinesegmenti s representedbygivingthecoordin atesof itstwoendpoints. Observethatnlinesegmen tscanintersectinasfewa szeroanda smanyas ! n 2 " =O(n 2 )differentintersection points.Wecouldsettl eforanO(n 2 )timealg orithm,claimingthatitiswo rst-caseasymptoticallyop timal,butitwouldnotbever yusefulin pract ice,sinceinm anyinstancesofint ersectionproblemsintersectionsmayberare.
Therefore,itseemsreasonabl etodesign anoutputsensi tivealgorithm,thatis,onewhoserunningtimedepends notonly ontheinputs ize,b utalsoont heoutputsi ze. GivenasetSofnlinesegmen ts,letI=I(S)denotethenumber ofintersect ions. Wewi llexpresstherunning timeof ouralgo rithmintermsofbo thnandI.Asusual,wewillassumethatthelinesegmentsareingeneral position.Inparticular,weas sume: (1)Thex-coordinatesoftheendpointsandinte rsectionp ointsarea lldistin ct.(Thisimpliesthatn oline segmentisvertical.) (2)Iftwose gme ntsintersec t,thentheyintersectinasingl epoint.(Theyarenotcollinear.) (3)Nothre elinesegm entsintersectin acomm onpoint.Generalizingthealgorithmto handledegener aciesefficientlyisa ninte restingexe rcise.(Seeourbookfo rmore
discussionofthis.) PlaneSweepAlgorit hm:Letusno wconsi derthealgori thmforreporti ngthesegment intersections.LetS= {s 1 ,...,s n }denotetheli nesegmentswhos eintersectionswe wishtocompute.Themethod,cal ledplane sweep,isafundamentaltechniqueincomputationalgeometry.Wesolvea2-dimensional problem bysimulating theproce ssofsweepinga1-dimension allinea crosstheplane.Thei nters ectionsofthesweeplinewiththeseg- mentsdefinesa collectionofpoints alongthes weepline.W ewillstore thesepoin tsinadatastructu re,which wecallthe sweep-linestatus. Althoughwe mightvisualize thesweeping processasacontin uousone,t herei sadiscreteset ofeventpoints whereimportantthingshappen. Asthelinesweepsf romlef ttoright,pointsareinserted,deleted,andmay swaporderalo ngthesweepline.T hus,wereducea static2-dimensionalproblemto adynamic1-dimensional problem. Therearethr eebasicelement sthataremaintained atanytimeinanyplane-sweepalgorithm:(1)thepartialsolutionthathasalre adybeenco nstructedtothe leftofthesweepline,(2)the currentstatuso fobjects alongthe
sweeplineitself,and (3)a(sub)se tofthefu tureeventsto beprocessed(seeFig.19). Theke ytodesigninganef ficientplane-sweep algorithminvolvesdetermining thebestwaytostoreandupd atethesethreeeleme ntsaseachn eweventisprocess.L et'scon sidereacho ftheseelementsingre aterdeta ilinthe
contextofline-s egmenti ntersection.Sweepli nestatus:Wewi llsimulatet hesweepingofaverticalli ne"fromleftto right.The swee p-linestatuswill
consistofthelinese gmentst hatintersect thesweeplines orted,say,fromto ptobottom.Ino rdertom aintain thissetdy namically, wewillstoretheminadatastructure,whichwillbe described below.Notethateach timethes weeplinemo ves, allthey-coordinatesoftheintersectionpointsch angeas well.Itw ill
betoo inefficientto continuallyupdateallthe y-coordinateseachtimethesweeplinemo ves.Weexploitth efact
thatitisnot thea ctua ly-coordinatesthatwereallycareabout, justtheirorder.Todothis,ratherthanstoringLectureNotes22CMSC754
futureeven tpoint discoveredintersection ! sweeplineFig.19:Planes weep.
y-coordinates,foreachlinesegments i thatintersects thesweepline,westoretheco efficien ts(a i ,b i )ofthe equationoftheline, e.g., y=a i x+b i .(Thesecoefficientscaneasilybederivedfromthesegmentendpoints.) Inthis way,w henevertheswee plinearrivesatanewx-coordinate,sayx=x 0 ,wecandeterminethecurrent y-coordinateatwhichsegments i intersectsthesweeplineas y(x 0 )=a i x 0 +b i (seeFig.2 0).Asweshall see, onlyaconst antnumberof suchintersections needto beev aluatedateachev entpoi nt. ! (a 2 ,b 2 ) s 2 s 1 (a 1 ,b 1 ) y 1 (x 0 )=a 1 x 0 +b 1 y 2 (x 0 )=a 2 x 0 +b 2 x=x 0Fig.20:Thesweep- line stat usstorescoefficientsoftheli neequations,andthey-coordinatesoftheintersectionsare
computedasneeded. EventsandDetectingI ntersect ions:Itsu fficestoprocesseventson lywh enthereisachangein thesweep-line status.Thesex-coordinatesarecalledeventpoints.Forourapplication,wehavethreetypesofeventpoints, correspondingtowhenthesweepline encounters(1)t hel eftendpointofase gment,( 2)the rightendpointofa segment,and(3)anintersectio npointbetw eentwose gments. Notethatendpoint events canbepr esortedbeforethes weepruns.Incontr ast,inter sectioneventswillbediscoveredasthesweepexecutes.I tis importantthat eacheventbedet ectedb eforetheactualeventoccur s.Our
strategywillbeasfollows .Whenevertwol ineseg ments becomeadjacentalongthesweep line,wewil lcheck whetherthe yhaveaninter sectionoccurringtotheright ofthesweep line.Ifs o,wewilladdthis newevent toa priorityqueueoffutureevent