Beruflich Dokumente
Kultur Dokumente
ProblemStatement:
Givenatreewhoseedgesandverticesaredefined.
Giventwonodesuandv,determineitsLCA.
BasicSolution:1.ApplyDFStodeterminetheimmediateparentofeachnodeandstarttime
andendtimeofeachnode.
2.Nowbringboththenodestothesameheightfirstbymovingthroughparentofeachnode.
3.Thenkeepmovingupwardstillacommonnodeisencountered,whichistheLCA.
Example:DetermineLCAofbottommostpinknodeandbottommostgreennode.
Heightofpinknode:4
Heightofgreennode:6
Bringthegreennodetoheight4first.
Thenmoveuptillacommonnodeisencountered.
LCAisthegreennodemarked17.
Complexityforksuchqueries:O(k*d)whered=depth
Approximatelycomplexitybecomes:O(k*n)
Worstcase:
Hereworsttimeisproportionalton/2wherenisnumberofnodes.
NOTE:Skewedtreeisnottheworstcasebecausethestarttimeandendtimehelpstodetect
theLCAdirectly.
Now,complexityishighduetotwofactors:
1. Movingonestepatatimetoreachthesameheight
2. Movingonestepatatimetoreachthecommonnode
THINK:Whatcanbedonetoreducethiscomplexity?
HINT:UnboundedBinarySearch
IDEA:
Generatethe2nd,4th,8thparentofeachnodeandsoon
Findthe2^iparentstill2^i<=n
Thiswillgenerateatableofsizen*log(depth)wheredp[i][j]determines2^jthparentofith
node.
Ifweknow2^ithparentifanodethenits2^(i+1)thparentwillbe2^ithparentof2^ithparent
ofthatnode.
temp=dp[i][j1]
dp[i][j]=dp[temp][j1]
Nowwecanapplyunboundedbinarysearch.
http://algorithmsgeek.blogspot.in/2013/06/algo26binarysearchinunboundedarray.html
ALGO:Wefirstgothesameheightasbeforethenweapplyunboundedbinarysearch.
Whentoterminatetheunboundedbinarysearch:
When2^ithparentofthenodesissamebut2^(i1)thnodeisntsame,then2^ithnode
becomestheupperboundand2^(i1)becomesthelowerbound.
Exception:Whennoparentisfoundsamethenupperboundistheroot.
eg:If8thparentofthetwonodesissamebut4thparentisdifferent,thentheLCAmustbe
betweenthe4thand8thparent.
Forbringingthenodestothesameheight,wecanusethese2^iparents,i.e.
Insteadofmovingstepbystepwecanmoveinstepsofpowersof2.
eg:Ifwehavetomove12stepsupwecangotothe8thparentthenthe4thparentofthat
node.
So,ifheightofonenodeisaandtheheightofothernodeisbandb>a,
thenbacanbetraversedusing2^iparentsasrequired.
Complexity:Precomputation:O(n*logd),d=depthO(n*logn)
Foreachquery:O(logn)forreachingthesameheight.+O(logn)fordetectingupperbound+
O(logn*logn)Secondlognforreachingmid
egsuppose16thparentistheupperboundand8thparentisthelowerbound.
nowmid=12
Toreachmidweneedtogofrom8thto12thusing2^iparentmethod...wellgotosecond
parentof8th,i.e10thposthensecondparentof10i.e12thposition.
SooverallcomplexityisO(k*logn*logn)
QUESTIONTOSOLVE:
Givenatreewithnnodes.Edgesareweighted.Thereareqquerieswhereeachqueryisof
theform:Giventwonodesuandv,determinethedistancebetweenthetwo.
HINT:Isthereanynodewhosedistancefromeveryothernodeisknown?
SOLUTION:DeterminetheLCAofuandv
Thenanswer=roottou+roottov2*roottoLCA
Referto
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor
tostudymoreaboutthis.
SEGMENTTREE
Subtopics:
1.BasicSegmentTree
2.LazyPropagation
3.OfflineQuery
4.BinarySearch
5.PersistentSegmentTree
ItisacompleteBinaryTree.
Concept:
1.Construction
2.RangeQuery
3.PointUpdate
4.RangeUpdate
SampleRangeMinimumQuery
query(i,j)>min(a[i]toa[j])
(x,p)>a[p]=x
(i,j,x)>a[p]+=xforeverypbelongingto(i,j)
Heightofsegmenttree:h=Ceil(log2N)
Numberofnodes=1<<(h+1)
CONSTRUCTION
Indexoffirstelementofthearrayinleaves:2^h
Whenstartingindexis1,Startiteratingfrom2^handstartinitialisingnodeswithelementsof
thearray.
Makeapostordertraversaltoinitialisethesegmenttree.
QUERY
intquery(intnode,intu,intv,intleftmost,intrightmost)
leftmostrightmost>rangeofelementscoveredbyanode
Giveexample
Initialisel,rto+infinity
Ifleftmostrightmostareintherangeofuv,thenreturnasitis.
elseifu<=mid
mid=(leftmost+rightmost)/2
l=query(2*node,u,v,leftmost,mid)
v>mid
r=query(2*node+1,u,v,mid+1,rightmost)
Implementmerge(l,r)asperquestion(Heremergeisminfunction)
POINTUPDATE
Propagateupwards
Complexity
Query:UsingWorstCaseAnalysis:2*logninworstcase=>O(logn)
Update:O(logn)
LAZYPROPAGATION(RangeUpdate)
Conceptofdirtybit
1meansupdated.
root1>0
andchildren0>1
ANOTHERMERGEFUNCTION
Thereisanothermergefunctionthatmovesfromroottoleaves.
Ifwehavetoadd2tonode3,thenwe'llmakeuandvequalto3.
Firstcallleftandrightsubtreesandthenupdatethecurrentnode(analogoustoquery)
Ifleaf,justreturntheupdatedvalue.
MERGINGfromRoottoleavesismorebeneficialbecauseitalsoallowsrangeupdation.
LAZYPROPAGATION(RangeUpdate)
Conceptofdirtybit
0meansupdated.
root1>0
andchildren0>1
SegmentTreehasthefollowingfunctions:
1.Query
2.Update
3.Merge
4.Split
Update(i,j,val):Addvaltoarangeofelementsfromitoj.
Howtodothis?
1.First,changethestructureofthenode:
Nowthenodehas:min(minimuminthatrange)
add(LikeDirtybit)
Supposewehavetoadd5toa[1]toa[4]
Gouptonode2andupdatenode.min(node.min+=5)
node.add+=5
Defaultvalueofnode.add=0
Nowwegetaqueryforindices2to3
split()iscalledwheneverwehavetogotowardstheleavesforaquery.Itwon'tbecalledfora
nodeunlessrequired.
Nowsplitwillbeused:
split()Wecallitatanytimebecauseresultwontbeaffectedifcurrent.add==0
left.add+=current.add
right.add+=current.add
left.min+=current.add
right.min+=current.add
current.add=0
Nowwehavearangeupdateforindices2to6:Add10tothem
Pathofnodesfollowed:
14
12
2(makedirtybithigh)
34soupdatethisnodeandreturn(makedirtybithigh)
58
56updatethisnodeandreturn(makedirtybithigh)
COORDINATECOMPRESSION
Ifnosliebetween1to10^9,thereare10^6suchnos..Compressthemtobringtheminto1to
10^6
Wecanusemaps.
OFFLINEQUERY:Storethequeriesandprocessinadesirablemanner.
Givenanarrayfrom1ton,eachelementlessthan10^6.
Thereisasingletypeofquery:Q(i,j):Countthenumberofdistinctnumbersinthisinterval
Ifweusemapineachnode,thenproblemwillbeinmerging(asO(n)formerging)
HINT:Sortthequeriesonthebasisofjandarrayisstoredintheformof0(dontcount)or1
(count)
Startmovingfromlefttorightinincreasingj.Wheneveranelementrepeats,makeitslast
occurrence0andpresentoccurrence1(Usingboolarrayormap).Andtakerangesumtoget
numberofdistinctelements.
BINARYSEARCH
SpojQuestion:ORDERSET
Firstapplycoordinatecompression.
UseofflinequeriestocreateamapofnumbersthatareinsertedintotheSet.
Thismapindicatestheindexofanumberinthesegmenttree.
Nowapplyrangesumfromindices0toindexofx
Insegmenttree,0indicatesabsenceand1indicatespresence.
Forkthsmallest,eitherapplybinarysearchon0to2*10^5,if(a[mid]>or<k)takeadecision.
O(logn*logn)
ItcanbedoneinO(logn)bylookingatleftandrightchildinsteadofusingmid.
GoogleQuestion:
Infinitenumbersarestreamingin.Anumbermightberepeated.Atanygiventime,determine
themedian.
(ThesenumbersarethesearchtimesinGoogle)
SpojQuestion:GSS3(DepictstherelationbetweenDivideandConquer&SegmentTrees)
UseD&C
Maxsum=Bestofleftsum,rightsumand(bestsuffix+bestprefix)
Ifweknowbestprefixandbestsuffixofleftandrightchild,wecanremoveO(n)factor
thenbestprefixofcurrent=max(bestprefixofleft,leftsegmentsum+bestprefixofright)
bestsuffixofcurrent=max(bestsuffixofright,rightsegmentsum+bestsuffixofleft)
Now,byusingsegmenttree
Wejusthavetochangemergefunctionandstructureofthenode.
QUESTIONSTOPRACTICE:
SPOJ:GSS3,BRCKTS,HORRIBLE,DQUERY,ORDERSET,CAKEQUERIES
REFERENCE:
http://letuskode.blogspot.in/2013/01/segtrees.html