You are on page 1of 23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

Enter|Register
HOME

CONTESTS

GYM

PROBLEMSET

GROUPS

RATING

API

HELP

TESTLIB

AIM FUND ROUND

RCC

5 YEARS!
Searchbytag

PRINCEOFPERSIA

BLOG

TEAMS

SUBMISSIONS

GROUPS

TALKS

CONTESTS

Payattention

PrinceOfPersia'sblog

AlgorithmGym::Datastructures
ByPrinceOfPersia,7monthsago,

Beforecontest

CodeforcesRound#318
[RussianCodeCupThanksRound]
(Div.1)
2days

TodayIwanttointroduceyousomeveryveryusefuldatastructures.
Inthislecture,wearetryingtoimproveyourdatastructuresskills,staywithusandclickon
readmore.Importantdatastructures:

Trees

Beforecontest

CodeforcesRound#318
[RussianCodeCupThanksRound]
(Div.2)
2days
Like 105peoplelikethis.Bethefirstofyour
friends.

Treesareoneofthemostusefuldatastructures.Atreeisaconnectedacyclicgraph.There
aretoomanytypesoftrees,like:rootedtrees,weightedtrees,directedtrees,tries,etc.

Partialsum
Therearetwotypesofproblemssolvablebypartialsum.
1.Problemswhichyouareaskedtoanswersomequeriesaboutthesumofapartof
elements(withoutmodifyqueries).
Solutionofallofthisproblemsarethesame.Youjustneedtoknowhowtosolveoneof
them.
Example:Youareaskedsomequeriesonanarraya1 ,a2 ,...a,n .Eachquerygiveyou
numberslandrandyoushouldprintal+al+1 +...+ar.
Solution:Youneedtobuildanotherarrays1 ,s2 ,...,sn whichsi=a1 +a2 +...+aiand
answerissrsl1 .
2.Problemswhichyouareaskedtoperformsomequeriesaskingyoutomodifyapartof
elements(withoutprintingqueries.)
Solutionofallofthisproblemsarethesame.Youjustneedtoknowhowtosolveoneof
them.

Toprated

User

Rating

tourist

3503

Petr

3029

vepifanov

2963

qwerty787788

2947

rng_58

2941

subscriber

2873

niyaznigmatul

2853

WJMZBMR

2853

TooSimple

2826

10

scott_wu

Countries |Cities |Organizations

2824
Viewall

Topcontributors
#

User

Contrib.

Example:Youneedtoperformsomequeriesonanarraya1 ,a2 ,...a,n .Eachquerygive


younumbersl,randvandforeachisuchthatliryoushouldincreaseaibyv,and
thenafterperformingallqueries,youshouldprintthewholearray.

Endagorion

157

PrinceOfPersia

157

Petr

157

Solution:Youshouldhaveanotherarrayp1 ,p2 ,...,pn which,allofitsmembersareinitially


0,foreachquery,youshouldincreaseplbyvanddecreasepr+1byv.

Egor

157

Swistakk

147

Anthen,foreachi,startingfrom1youshouldincreasepibypi1 .So,finalarraywouldbe
a1+p1,a2+p2,...,an+pn.

I_love_Hoang_Yen

144

I_love_Tanya_Romanova

141

Hardproblemofpartialsum:TroynacciQuery

Rubanenko

140

Monyura

137

10

marat.snowbear

135

Disjointsets
Disjointsetsarealsousefuldatastructures.Usingthemisfastandeasy.Weusethemein
manyalgorithms,likeKruskal'sandPrim's.

Viewall

Finduser

Disjointsets,orDSU(DisjointSetsUnion)astheirname,aresumsets.Imaginewehave
http://codeforces.com/blog/entry/15729

1/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

someboxesandsometoolsandinitiallyeachtoolisinonebox.Mostly,wearegivensome
queriesandasktomergetwoboxesorprintthemembersofaboxorfindwhichboxis
sometoolin.
Forrestofthese,let'sconsiderthatinitiallythereisexactlyonetoolinabox.Thatis,we
haventoolsandnboxesandinitially,toolnumberiisinboxnumberi.
Forthispropose,wecanusesomanycontainers.Like:

Handle:
Find

Recentactions

Miyukine1stHungerGamesLarge
EditorialCommunitysolutions

Trees
TreesarethemostusefulcontainersforDSU.Foreachvertex,wekeepit'sparent(and
parrentoftherootis1).So,initiallyareparentsaresetto1,andwehavequeriestofind
therootofeachbox(havingtheroot,wecaneasilyfindthebox'sindex)andqueriesfor
mergingtwotrees.Forbettertimecomplexity,everytimewewanttofindtherootofeach
vertex,wesetit'sparenttotherootforthenextqueries.Andwhilemerging,wealwayswant
tominimizetheheightofthetree,sowhenwewanttomergetheboxes,it'slikeweputall
thetoolsoftheboxwithfewertoolsintheotherbox.

arbitCommonAncestorinaDirected
AcyclicGraph(DAG)
mewat1000yourfavoritetypeof
problems?
KostromaCodeforcesRound#317
[AimFundThanksRound]Editorial
beatoricheTopcoderSRM666
ironman7453ChefandtheDual
Palindromes
DeterminismMITOCWAdvancedData
Structures
PrinceOfPersiaThe1stHungerGames
Miyukine1stHungerGamesSmall
EditorialHints
ngoisao_93CodeforcesRound#273
EnglishEditorial(Cisavailablenow!)
vontmanAnyhintforthismathproblem?

ThebestwayI'veseentocodethiskindofDSU,isstyleofbmerry:(C++)
introot(intv){returnpar[v]<0?v:(par[v]=root(par[v]));}
voidmerge(intx,inty){

//

xandyaresometools(vertices)

if((x=root(x))==(y=root(y))return;

if(par[y]<par[x])

par[x]+=par[y];

par[y]=x;

//balancingtheheightofthetree

swap(x,y);

Inthecodeabove,foreachrootv,par[v]equalsthenegativeofnumberoftoolsinthat
box.

Arrays,vectors
Wekeeptoolsinavector(oranarray)andwhenwehaveaquerytomergetwoboxes,we
putallthetoolsoftheboxwithfewertoolsintheotherbox.

EgorSNSSRound#4
hellcoderTopcoderSingleRoundMatch
666
heretocodeInterestingrecursionbased
question.
josdasCodeforcesRound#316Editorial

seifGamal_FCiHelp..WAonaneasy
interestingGYMproblem
hanfei19910905Simplesolutiontovkcup
QualificationRound1and2
zelibobaCodeforcesRound#317
d4rkh4ck3rDPtopdownproblem
lighters[HackerRank]SprintDebugon
29thofAugust.
vsanjay_nitdgpbinaryindexedtree
vsanjay_nitdgpbinaryindexedtreespoj

Thetimecomplexityisgoodbecauseforeachtool,wetakeandputitinanotherboxat
mostlog(n)times(eachtimethesizeofthevectorwillbeatleastdoubled).

matheuscscpImproveminimumspanning
treewithnewedge,withbetterrunning
timethanO(|V|)

SotimecomplexitywouldbeO(n.log(n)).

msskWhydidweusethiscondition
if(a[k1]<b[vm])?

Sets(redblacktrees)
Otherwayistokeeptheminaredblacktree(inC++it's set ).Wedoexactlylike
vectors,sotimecomplexitywouldbeO(n.log2 (n)).(Onelogisforinserting).

DuXBubbleCup8Finals
Detailed

Problems:Hamroandtools,TROYQuery(JointhegroupACMOIfirst)

Tries
Triesaresomekindofrootedtreesinwhicheachedgehasacharacteronit.Actually,trieis
http://codeforces.com/blog/entry/15729

2/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

somekindofDFA(DeterminingFiniteAutomata).Forabunchofstrings,theirtrieisthe
smallestrootedtreewithacharacteroneachedgeandeachofthesestringscanbebuild
bywritingdownthecharactersinthepathfromtheroottosomenode.
It'sadvantageis,LCP(LongestCommonPrefix)oftwoofthesestringsistheLCA(Lowest
CommonAncestor)oftheirnodesinthetrie(anodethatwecanbuildthestringbywriting
downthecharactersinthepathfromtheroottothatnode).
Generatingthetrie:
Rootisvertexnumber0(C++)
intx[MAX_NUMBER_OF_NODES][MAX_ASCII_CODE],next=1;//initiallyallnumbers
inxare1
voidbuild(strings){

inti=0,v=0;

while(i<s.size()){

if(x[v][s[i]]==1)

else

v=x[v][s[i++]]=next++;
v=x[v][s[i++]];

Problem:Alotofgames

Suffixarray
Suffixarrayisadatastructurethathelpsyousortallthesuffixesinlexicographyorder.
Thisarrayconsistsofintegers,thebeginningofsuffixes.
Therearetwowaystoachievethisgoal:
One)Nondeterministicalgorithm:UseRobinCarpandforcheckifasuffixis
lexicographicallylessthananotherone,findtheirLCPusingbinarysearch+hashandthen
checkthenextcharacteraftertheirLCP.
Code:
namespaceHashSuffixArray
{

constint

typedefunsignedlonglonghash;

consthashBASE=137;

intN;

char*S;

intsa[MAXN];

hashh[MAXN],hPow[MAXN];

#definegetHash(lo,size)(h[lo]h[(lo)+(size)]*hPow[size])

inlineboolsufCmp(inti,intj)

intlo=1,hi=min(Ni,Nj);

while(lo<=hi)

MAXN=1<<21;

http://codeforces.com/blog/entry/15729

intmid=(lo+hi)>>1;

3/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

if(getHash(i,mid)==getHash(j,mid))

else

returnS[i+hi]<S[j+hi];

voidbuildSA()

N=strlen(S);

hPow[0]=1;

for(inti=1;i<=N;++i)

h[N]=0;

for(inti=N1;i>=0;i)

stable_sort(sa,sa+N,sufCmp);

lo=mid+1;
hi=mid1;

hPow[i]=hPow[i1]*BASE;

h[i]=h[i+1]*BASE+S[i],sa[i]=i;

}//endnamespaceHashSuffixArray

Two)Deterministicalgorithm:Wesortthemlog(MaxLength)steps,intheithstep
(countingfrom0),wesortthemaccordingtotheirfirst2icharactersandputthesuffixes
i
whitthesameprefixwith2 charactersinthesamebuckets.
Code:
/*
SuffixarrayO(nlg^2n)
LCPtableO(n)
*/
#include<cstdio>
#include<algorithm>
#include<cstring>
usingnamespacestd;
#defineREP(i,n)for(inti=0;i<(int)(n);++i)
namespaceSuffixArray
{

constintMAXN=1<<21;

char*S;

intN,gap;

intsa[MAXN],pos[MAXN],tmp[MAXN],lcp[MAXN];

boolsufCmp(inti,intj)

if(pos[i]!=pos[j])

i+=gap;

j+=gap;

return(i<N&&j<N)?pos[i]<pos[j]:i>j;

voidbuildSA()

http://codeforces.com/blog/entry/15729

returnpos[i]<pos[j];

4/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

N=strlen(S);

REP(i,N)sa[i]=i,pos[i]=S[i];

for(gap=1;;gap*=2)

sort(sa,sa+N,sufCmp);

REP(i,N1)tmp[i+1]=tmp[i]+sufCmp(sa[i],sa[i

REP(i,N)pos[sa[i]]=tmp[i];

if(tmp[N1]==N1)break;

voidbuildLCP()

for(inti=0,k=0;i<N;++i)if(pos[i]!=N1)

for(intj=sa[pos[i]+1];S[i+k]==S[j+k];)

++k;

lcp[pos[i]]=k;

if(k)k;

+1]);

}//endnamespaceSuffixArray

(Codesbymukel)

Heaps
Aheapisabinaryrootedtree(arootedtreethateachnodehasatmost2children)and
eachvertexhasavalue.
Heapproperty:Heapusuallyhasaproperty,likethevalueofeachvertexisequaltoor
greaterthanthevalueofitschild(ren)(wecallthisamaxheap).Wecanuseheapsinheap
sort.

Fibonacciheaps
Afibonacciheapisakindofheapwithbettercomplexities.Wedon'tneedtoknowwhata
fibonacciheapis.C++alreadyhasone, priority_queue .

BinarySearchTree(BST)
Abinarysearchtree(BST)isabinaryrootedtreethateverynodehasavalue,andforeach
node,thevalueofeverynodeinitsleftchild'ssubtreeislessthanitsvalueandthevalueof
everynodeinitsrightchild'ssubtreeisgreaterthanthat.Usuallyweperformsomequeries
onBSTs,likeinserting,deleting,askingand....
http://codeforces.com/blog/entry/15729

5/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

Binarysearchtreesaretoouseful.

Redblacktrees
AredblacktreeisakindofBSTthataftereachquery,BSTwillbebalancedinsuchaway
thatit'sheightremainsO(log(n)).
C++alreadyhasaredblacktreeinside, set .
YoucanreadabouttheminC++references.

Unfortunately, set hasnotanyfunctiontofindthekthsmallestminimumorfindthe


indexofanelement,bustthereisadatastructureinC++withdoesitinO(log(n))(also
containsall set functions), tree :
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
usingnamespace__gnu_pbds;
usingnamespacestd;
template<typenameT>
usingordered_set=tree<T,null_type,less<T>,rb_tree_tag,
tree_order_statistics_node_update>;
intmain(){

ordered_set<int>s;

s.insert(1);

s.insert(3);

cout<<s.order_of_key(2)<<endl;//thenumberofelementsinthes

lessthan2

cout<<*s.find_by_order(0)<<endl;//printthe0thsmallestnumber

ins(0based)

http://codeforces.com/blog/entry/15729

6/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

(ThankstoSwiftforsyntax using !)
ThisworkseveninC++98!
Youcanreadmoreaboutit,justgoogle sgiSTL .

SQRTDecomposition
Supposewehaveanarraya1 ,a2 ,...,an and
eachcontainingkelementsofa.
Doingthis,wecandoalotofthingsin
modifyandaskqueries.

.Wepartitionthisarrayintokpieces

.Usuallyweusethemintheproblemswith

Problems:Holes,DZYLovesColors,RMQ(rangeminimumquery)problem

SparseTable
ThemainproblemthatwecansolveisRMQproblem,wehaveanarraya1 ,a2 ,...,an and
somequeries.Eachquerygivesyounumberslandr(lr)andyoushouldprintthevalue
ofmin(al,al+1 ,...,ar).
SolvingusingSparseTable:Foreachithat1inandforeachjthat0jand
i+2j1n,wekeepthevalueofmin(ai,ai+1,...,ai+2j1)inst[i][j](preprocess):
(codeis0based)
for(intj=0;j<MAX_LOG;j++)

for(inti=0;i<n;i++)if(i+(1<<j)1<n)

st[i][j]=(j?min(st[i][j1],st[i+(1<<(j1))1][j1]):

a[i]);
x

Andthenforeachquery,firstofall,findthemaximumxsuchthat2
x
ismin(st[l][x],st[r2 +1][x]).

rl+1andanswer

So,themainideaofSparseTable,istokeepthevalueforeachintervaloflength2k(for
eachk).
YoucanusethesameideaforLCAproblemandsomanyotherproblems.
SopreprocesswillbeinO(n.log(n))andquerywillbeinO(1)
Problems:Strip,GCDSSQ,LCMQuery.

Heavylightdecomposition
Heavylightdecompositionisawaytopartitionatree'svertices(oredges)inagoodway.
Inthiskindofdecomposition,wehavesomechains,andeachvertexbelongstoonlyone
chain.
Ifvertexvistheparentofusize_of_subtree_of(v)/2<size_of_subtree_of(u),uandvarein
achainandwecalltheedgeuv,heavy,otherwiselight.
Thereisatmostonesuchchildforeachvertexv.Ifweconsiderthepathfromanyvertexv
totheroot,therewillbeatmostlog(n)lightedgesthere(gofromvtotheroot,everytime
weseealightedge,sizeofsubtreewillbeatleastdoubled).So,thenumberofchainson
theway=O(log(n)).
Ineachofthesechains,wecancontainacontaineroranotherdatastructurelikesegment
treeoretc.

http://codeforces.com/blog/entry/15729

7/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

Problem:GRASSPLANTING

Fenwick
Supposethatwehavenelementsnumberedfrom1ton.
FenwickorBIT(BinaryIndexedTree)isadatastructurewithnnodesthatnodenumberi
hassomeinformationaboutelementsintheinterval(ii&i,i].
Actually,youdon'tneedtoknowwhateachnodecontains.Theonlythingyoushouldknow,
itthis(thenyoucanchangeandconvertit):
Wehaveanarraya1 ,a2 ,...,an andallofthemareinitially0.Wearegivessomequeries,
1.increaseap byvalandprinta1 +a2 +...+ap .
OnlythingyoushouldknowisthathowtosolvethisproblemusingFenwick(andthenyou
canchangeitandsolvesomanyproblems).

WeperformeachqueryinO(log(n)).Code:(1based)
http://codeforces.com/blog/entry/15729

8/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

intfen[MAX_N];
voidupdate(intp,intval){

for(inti=p;i<=n;i+=i&i)

fen[i]+=val;

}
intsum(intp){

intans=0;

for(inti=p;i;i=i&i)

returnans;

ans+=fen[i];

Pleasenotethatitshouldbe1based.Itcan'tbedone0based.
Problems:Inversions,PashmakandParmida'sproblem,BST.

Segmenttree
Wehaveanarrayofelementsandsomequeriesonintervals.So,wewillbegladifwecan
splitthisintervaltoO(log(n))intervalsthatwehaveactuallysomeinformationaboutthem.
Segmenttreedoesthatforyou.Segmenttreeisatreethateachofit'snodesbelongstoan
interval.
Rootofthetreebelongstotheinterval[0,n)(0based).
Eachnode,has0ortwochildren.Leftandright.Ifanode'sintervalis[l,r)andl+1r,
theintervalofitschildrenwillbe[l,mid)and[mid,r)inorderwhere
,sothe
heightofthistreewillbeO(log(n)).

Eachnodehasanindex,weconsiderthatroothasindex1andthechildrenofavertexx
willhaveindices2xand2x+1inorder.
SegmenttreeisthemostusefuldatastructureandeveryproblemsolvablebyFenwickis
alsosolvablebySegmenttree.
Ifthesizeoftheroot'sintervalisn,segmenttreecouldhaveupto4nnodes.
Tosplitanintervaltosomenodesofthistree,wewillactlikethis:
SupposethatSisthesetofnodeswhichtheirunionis[x,y)andnotwodifferentnodesinS
havenonemptyintersection.
Anodeiwithinterval[l,r)isinSifandonlyifxlryandifithasaparentwith
interval[b,e),x>lorr>y.
C++code:
vector<int>s;
voidsplit(intx,inty,intid=1,intl=0,intr=n){//

idistheindex

ofthenode

if(x>=rorl>=y)

http://codeforces.com/blog/entry/15729

return;

//inthiscase,intersectof

9/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

[l,r)and[x,y)isempty

if(x<=l&&r<=y){

s.push_back(id);

return;

intmid=(l+r)/2;

split(x,y,id*2,l,mid);

split(x,y,id*2+1,mid,r);

Example:
Wehaveanarraya1 ,a2 ,...,an andqqueries.Thereare2typesofqueries.
1.
2.

Slr,Printal,al+1,...,ar
Mpx,Modifyaptox,itmeansap=x.

Firstofallweneedtobuildthesegmenttree,foreachnodewekeepthesumofitsinterval,
fornodeiwecallits[i],soweshouldbuildtheinitialsegmenttree.
voidbuild(intid=1,intl=0,intr=n){

if(rl<2){ //

s[id]=a[l];

l+1==r

return;

intmid=(l+r)/2;

build(id*2,l,mid);

build(id*2+1,mid,r);

s[id]=s[id*2]+s[id*2+1];

So,beforereadingthequeries,weshouldcallbuild().
Modifyfunction:
voidmodify(intp,intx,intid=1,intl=0,intr=n){

s[id]+=xa[p];

if(rl<2){ //

a[p]=x;

return;

intmid=(l+r)/2;

if(p<mid)

else

l=r1=p

modify(p,x,id*2,l,mid);
modify(p,x,id*2+1,mid,r);

(Weshouldcallmodify(p,x))
Askforsumfunction:
intsum(intx,inty,intid=1,intl=0,intr=n){

if(x>=rorl>=y)

return0;

if(x<=l&&r<=y)

returns[id];

intmid=(l+r)/2;

returnsum(x,y,id*2,l,mid)+

sum(x,y,id*2+1,mid,r);

(Weshouldcallsum(l,r))
http://codeforces.com/blog/entry/15729

10/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

Lazypropagation
Imaginewehaveupdatesonintervals,whatshouldwedo?
Example:
Wehaveanarraya1 ,a2 ,...,an andqqueries.Thereare2typesofqueries.
1.
2.

Slr,Printal,al+1,...,ar
Ilrx,foreachisuchthatli<r,increaseaibyx.

Weshouldn'tupdateallthenodesinthisinterval,justthemaximalones,thenpassitto
childrenwhenweneed.ThistrickiscalledLazyPropagation,soweshouldhaveanother
arraylazy(fornodes)whichareinitially0andeverytimewewanttoperformincrease
query,increaselazy[id]withx.
Asabove,wealsoshouldhaveanarraysfornodes.
So,buildfunctionwillbesameasabove.Butweneedsomemorefunctions:
Afunctiontoupdateanode:
voidupd(intid,intl,intr,intx){//

increaseallmembersinthisinterval

byx

lazy[id]+=x;

s[id]+=(rl)*x;

Afunctiontopasstheupdateinformationtoitschildren:
voidshift(intid,intl,intr){//passupdateinformationtothechildren

intmid=(l+r)/2;

upd(id*2,l,mid,lazy[id]);

upd(id*2+1,mid,r,lazy[id]);

lazy[id]=0;//passingisdone

Afunctiontoperformincreasequeries:
voidincrease(intx,inty,intv,intid=1,intl=0,intr=n){

if(x>=rorl>=y)

return;

if(x<=l&&r<=y){

upd(id,l,r,v);

return;

shift(id,l,r);

intmid=(l+r)/2;

increase(x,y,v,id*2,l,mid);

increase(x,y,v,id*2+1,mid,r);

s[id]=s[id*2]+s[id*2+1];

(Weshouldcallincrease(lrx))
Afunctiontoanswertoqueriesaskingaboutthesum:
intsum(intx,inty,intid=1,intl=0,intr=n){

if(x>=rorl>=y)

return0;

if(x<=l&&r<=y)

returns[id];

shift(id,l,r);

intmid=(l+r)/2;

returnsum(x,y,id*2,l,mid)+

sum(x,y,id*2+1,mid,r);

http://codeforces.com/blog/entry/15729

11/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

(Weshouldcallsum(l,r))
Problems:GSS1,GSS3,MULTQ3,DQUERY,KQUERY,POSTERS,PATULJCI,NewYear
Domino,CopyingData,DZYLovesFibonacciNumbers,FRBSUM

Persistentdatastructures
Considerwehavesomeelements,youperformsomeupdatesonitandthen,andafter
performingallofthem,youwanttohavetheinformationabouttheelements,aftereach
update.
Forthispropose,yougotadatastructureandsomehow,yousavetheversionofthatdata
structure.
Themostusefuldatastructureforthisproposeissegmenttree,Iwillexplainpersistent
segmenttreeandallotherdatastructures(likeFenwick)arelikethat.

Persistentsegmenttree
Exampleproblem:
Wehaveanarraya1 ,a2 ,...,an andatfirstqupdatequeriesandthenuaskquerieswhich
youhavetoansweronline.
Eachupdatequerygivesyounumberspandvandasksyoutoincreaseap byv.
Eachaskquery,givesyouthreenumbersiandxandyandasksyoutoprintthevalueof
ax+ax+1+...+ayafterperformingithquery.
Eachupdatequery,changesthevalueofO(log(n))nodesinthesegmenttree,soyou
shouldkeeprestofnodes(notcontainingp)andcreatelog(n)newnodes.Totally,you
needtohaveq.log(n)nodes.So,youcannotusenormalsegment'sindexing,youshould
keeptheindexofchildreninthearraysLandR.
Ifyouupdateanode,youshouldassignanewindextoitsinterval(forithquery).
Youshouldkeepanarrayroot[q]whichgivesyoutheindexoftheintervaloftheroot(
[0,n))afterperformingeachqueryandanumberir=0whichisitsindexintheinitial
segmenttree(ansofcourse,anarrays[MAXNODES ]whichisthesumofelementsinthat
node).AlsoyoushouldhaveaNEXT_FREE_INDEX=1whichisalwaysthenextfreeindex
foranode.
Firstofall,youneedtobuildtheinitialsegmenttree:
(Inthesecodes,allarraysandqueriesare0based)
voidbuild(intid=ir,intl=0,intr=n){

if(rl<2){

s[id]=a[l];

return;

intmid=(l+r)/2;

L[id]=NEXT_FREE_INDEX++;

R[id]=NEXT_FREE_INDEX++;

build(L[id],l,mid);

build(R[id],mid,r);

s[id]=s[L[id]]+s[R[id]];

(So,weshouldcallbuild())
Updatefunction:(itsreturnvalue,istheindexoftheintervalinthenewversionofsegment
treeandidistheindexofoldone)
http://codeforces.com/blog/entry/15729

12/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

intupd(intp,intv,intid,intl=0,intr=n){

intID=NEXT_FREE_INDEX++;//indexofthenodeinnewversionof

segmenttree

if(rl<2){

s[ID]=(a[p]+=v);

returnID;

intmid=(l+r)/2;

L[ID]=L[id],R[ID]=R[id];//incaseofnotupdatingtheinterval

ofleftchildorrightchild

if(p<mid)

else

returnID;

L[ID]=upd(p,v,L[ID],l,mid);
R[ID]=upd(p,v,R[ID],mid,r);

(Forthefirstquery(withindex0)weshouldrunroot[0]=upd(p,v,ir)andfortherestof
them,forjthqueryseshouldrunroot[j]=upd(p,v,root[j1]))
Functionforaskqueries:
intsum(intx,inty,intid,intl=0,intr=n){

if(x>=rorl>=y)

return0;

if(x<=l&&r<=y)

returns[id];

intmid=(l+r)/2;

returnsum(x,y,L[id],l,mid)+

sum(x,y,R[id],mid,r);

(So,weshouldprintthevalueofsum(x,y,root[i]))
Problems:SignonFence,MKTHNUM,COT,TheClassicProblem
algorithms, datastructures, tutorial

+607

PrinceOfPersia

Comments(76)

7monthsago

76

Writecomment?

7monthsago, # |

+6

+3

11

souseful,verythanks

Reply
New_Mahdi

7monthsago, # |

ThankyouforthisUsefultoturial
Kei.One

Reply

7monthsago, # |

thanks:)
M.D

Reply

http://codeforces.com/blog/entry/15729

13/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

7monthsago, # |

Rev.3

+27

Thanksforthearticle,especiallyforproblems!
Ididn'tknowthatpriority_queueisaFibonacciheap.BTW,areyousure?
cplusplus.comandcppreferencesaythatpush()worksinlogarithmictime.
P.S.1Thislink(HamroandtoolsprobleminDSUsection)givesaccess
error:link
P.S.2Isn't"sparse"acorrectspelling?

nic11

Reply

7monthsago, # |

Greatintro.Stillhave1question.Doesorder_setworksonlying++?Howit
isgoingtoworkinVisualC++?

Reply

edogrigqv2

7monthsago, # ^ |

Doesorder_setworksonlying++
Yes.It'spartofSGISTLextensionsofG++.

Reply

adamant

7monthsago, # |

+16

Btw, tree isn'tpartofC++standard,itisextensionofGNUC++.You


canreadmoreaboutthisdatastructureshereandhere:)
Alsoaboutpersistentdatastructures.Onecanbeinterestedinthis:
#TphcLk
(kthorderstatisticsinthearraysegmentusingpersistentbittrie.
.Fullyonline,workswithnegativenumbersalso!)

adamant

Alsoyoucanusethisstructuretoanswerallqueriesfromthisproblem.

Reply

7monthsago, # ^ |

HowtoapplyyourcodetotheXORqueryplease?

Reply
speedy03

7monthsago, # ^ |

+1

MyfullsolutionofXorQueries:#QI8sxL

adamant

Xorquerycanbedonegreedyweiteratethrough
implicitbittrieofl..rsubsegmentandeachtimewetry
totakekthbitinanswerwhichisnotequaltokthbitin
query.

Reply

7monthsago, # ^ |

Gotit,thanks!Theofficialsolutionisalso
basedontrie.Anyspecificadvantagesover

http://codeforces.com/blog/entry/15729

14/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces
basedontrie.Anyspecificadvantagesover
segmenttree?

Reply
speedy03

7monthsago, # ^ |

Actuallysegmenttreeisakindof
trie...Triejustabitmoregeneric

Reply
adamant

7monthsago, # |

TheisprobablymistakeinDSUimplementation.par[x]+=par[y]???What
isthis?

Reply

edogrigqv2

7monthsago, # ^ |

+1

Readit!
Inthecodeabove,foreachrootv,par[v]equalsthenegativeof
numberoftoolsinthatbox.
PrinceOfPersia

So,par[x]=sizeofbox(x),par[y]=sizeofbox(y).so,par[x]+
par[y]=sizeofbox(xunuiony).

Reply

7monthsago, # ^ |

HaveIunderstooditcorrectnow?par[v]showsthe
parentofv,ifvisnottheroot,otherwiseitshows
negativenumberofnodesingroup.2in1array!!!
edogrigqv2

Reply

7monthsago, # ^ |

Yep!

Reply
PrinceOfPersia

6monthsago, # ^ |

Actuallythere'sanofficialnameforthetechnique.It'scalled
unionbyrank .Moreinfocanbefoundhere.

Reply
natsukagami

5monthsago, # ^ |

Whyaresomecommentsinbluerectanglesin
codeforces(likethecommentabove)?
shmorabi2

Reply

5monthsago, # ^ |

Itisnewcommentsthatyouhadn'treadbefore.
Ifyouupdatewepbageit'llbelikeanyother

http://codeforces.com/blog/entry/15729

15/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces
Ifyouupdatewepbageit'llbelikeanyother
comment

Reply

VKundas

5monthsago, # ^ |

OKtnx:)

Reply
shmorabi2

7monthsago, # |

+25

Ithoughtc++priorityqueuesarebinaryheap.AsfarasIremember
Fibonacciheapshashugeconstantfactor.Couldyousharesourcewhere
yougetthisinformation?
ikbal

Reply

7monthsago, # ^ |

+24

cplusplus.comthinksthat priority_queue isjustawrapper


aroundpush_heap/ pop_heap / make_heap ,whichworkswith
standardbinaryheapinarandomaccesscontainerandhave
logarithmiccomplexity.
yeputons

Reply

7monthsago, # ^ |

+21

InmyVisualC++2013headerofIhavefoundmake_heapand
push_heapthatusethesamevector.

voidpush(constvalue_type&_Val)

c.push_back(_Val);

push_heap(c.begin(),c.end(),comp);

//insertvalueinpriority

order

edogrigqv2

Maybeg++usesFibonacciheap.ButitisnomorepartofSTL.
cplusplus.comusuallyhintsifindifferentcompilerssomething
maybedifferent.Hereitonlystatesthatpriority_queueuses
make_heap,push_heap,andpop_heap.
Ialsohavefoundthis.

Reply

7monthsago, # |

Fenwickcanbe0based!Change i+=i&i to i|=i+1 andchange


i=i&i to i=(i&(i+1))1

Reply
Bugman

7monthsago, # ^ |

Rev.2

+7

WhywouldIwanttoshootinmyfoot:P?

Reply
Swistakk

http://codeforces.com/blog/entry/15729

16/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

7monthsago, # ^ |

Becauseemaxxsaysso:)

Reply
adamant

7monthsago, # ^ |

+40

Fenwickcanbe12based. i+=i&i >


i+=((i11)&(i11)) :P

Reply
Swistakk

7monthsago, # ^ |

+5

:)

Reply
Bugman

7monthsago, # |

justintime:Dthanx

Reply
JUST_Yousef

7monthsago, # |

Rev.4

+3

At"Arrays,vectors",yousaid,"SotimecomplexitywouldbeO(n.log(n))."

shu_mj

However,IthinkthetimecomplexityisO(n).Thecountofcopieditemis(1
+2+4+...+N)whereN<nandN=2^kkisnonnegativeinteger.So
thecountofcopieditemis(N*21),iforiginalarraymodifyinvolved,the
countis(N*21+n).TimecomplexityisO(n).

Reply

7monthsago, # ^ |

Yes,andwecansimplydovector.reserve(N)andproblem
disappearsatall.
flashion

Reply

7monthsago, # ^ |

+9

n=O(n.log(n)),Ididn'tsay(n.log(n))
Reply
PrinceOfPersia

7monthsago, # |

Incase2ofpartialsum,canyouapplyyourformulatobinaryindextreeif
sumwithintherange[l,r]isqueried?
speedy03

Reply

7monthsago, # ^ |

Rev.3

Yes.Justincreasethevalueofalbyvandincreasethevalueof

ar+1byv(asIsaidinFenwick).

http://codeforces.com/blog/entry/15729

17/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces

ar+1byv(asIsaidinFenwick).
Reply
PrinceOfPersia

7monthsago, # |

Thankyou>:)

Reply
joaquingc123

7monthsago, # |

Amazing!Thankyousomuch.

Reply
erikgrabljevec5

7monthsago, # |

HowtosolveinversioncountusingBIT

Reply
ayushtomar

7monthsago, # ^ |

Foreverynumbercheckhowmanynumbersarebeforeit?Todo
this,addnumberstoBITsortedfromthelargesttosmallest.

Reply

flashion

6monthsago, # ^ |

Canyouexplainmore?

Reply
Shayan.To

6monthsago, # ^ |

ThisblogpostexplainshowtouseaBITfor
countinginversions.
surjection

Reply

7monthsago, # |

Thankyouverymuchforthegreattutorial!:D

Reply
cristi.dospra

7monthsago, # |

13

goodread.thankyou!

Reply
Chaze

7monthsago, # |

Thankyou

Reply
amarveer

http://codeforces.com/blog/entry/15729

18/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces
7monthsago, # |

DouyouhaveanyexampleincodeofTRIES?
Thanx.
Ware_tron

Reply

7monthsago, # ^ |

Referthisandthis.

Reply
xpertcoder

7monthsago, # |

Rev.2

Reply
Sonechko

7monthsago, # |

Niceblog/tutorial..itwouldbeusefulforbeginnersastheywillgetanidea
ofwhatalltostudy....Wouldhavebeenniceifsomethinglikethiswas
therewhenIstarted...

Reply

sachithg

7monthsago, # |

Goodstuff.Cheers

Reply
vaishious

7monthsago, # |

buGMaster

Rev.2

Hi!
Idon'tgethowsuffixarray(deterministicversion)works.
Couldyoupleasegivemesomemorecleardescriptionaboutit?
Whatdoes"tmp"store?Itseemsitcontainssomethinglike[0,1,...,N1],
doesn'tit?!
Whatabout"pos"?
What'stheinitializationof"tmp"?
Thanks...

Reply

6monthsago, # ^ |

Rev.2

?!

Reply
buGMaster

6monthsago, # |

http://codeforces.com/blog/entry/16541

Reply
buGMaster

4monthsago, # |

Anotherproblemofpartialsum
http://codeforces.com/blog/entry/15729

Rev.3

19/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces
Anotherproblemofpartialsum
http://codeforces.com/problemset/problem/433/B

Reply
sazzad8867

4monthsago, # |

Rev.11

SpeakingofDSU,here'sthesamefunction,butinamoreunderstandable
way.
introot(intv){
while(par[v]!=1){
par[v]=par[par[v]];
v=par[v];
}
returnv;

CrazzyBeer

UPD:Thisisawaytocompresspaths,butnotasefficientasthe
presentedalgorithm.

Reply

4monthsago, # ^ |

Ifyouobservecarefully,thecodeactuallydoesupdateallthe
nodesinthepathwhichiswhatyouwanttodo.

Reply

Koderok

4monthsago, # ^ |

theactualcodecompressesbetterAllofthenodes
parentwillbetherootbutincrazzybeer'scodeitdoesnt
workalsothereisaclosedbracketwhichleadstoinfinite
loop
Silver_Soul

Reply

4monthsago, # ^ |

Mistakefixed.Nowitshouldwork.(Actually,
thisisthealgorithmfromCourserasoitworks
prettywell)
CrazzyBeer

Reply

4monthsago, # ^ |

Itworks,but,Iguess,itdoesabitlesswork
thanthepresentedalgorithm.

Reply
CrazzyBeer

4monthsago, # ^ |

Iseenow.Thanks.

Reply
CrazzyBeer

4monthsago, # |

Bookmarked!Thanksforthistutorial!:)
http://codeforces.com/blog/entry/15729

20/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces
Bookmarked!Thanksforthistutorial!:)

Reply

adnanSharif

4monthsago, # |

ThankyouforthisUsefultoturial.

Reply
ypizarroza

3monthsago, # |

Whatdoesthemodify(p,x)functiondointheSegmenttreesection?

Reply

suraj021

3monthsago, # ^ |

"Modifyaptox,itmeansap=x."

Reply

hkf

3monthsago, # ^ |

Thanks
suraj021

Reply

3monthsago, # |

"Theonlythingyoushouldknow,itthis(thenyoucanchangeandconvert
it):"Ithink"it"hastobe"is",right?
shmorabi2

Reply

3monthsago, # |

CanpleasesomeoneexplainPartialsumpart2?Whatistheproblemit
solve?Weneedtofindsumofelementsofarrayawithindexes[l,r)?

Reply
dev_il

7weeksago, # ^ |

tirupati

Rev.2

PartialSumpart2solvestheproblemwhereyouaregivenan
arrayandallyouhavetodoistoprintthearrayafterperformingq
querieswhereeachqueryasksyoutochangealltheelements
between[l,r].Sayyouhaveanarrayofsizeoftheorder10^5and
youhave10^5queries.NowNaivemethodistoiterateoverallthe
rl+1elementsforeachqueryhencethesolutionwouldbeO(n^2).
Soaccordingtopart2ofthesolutionallyoudoistoupdatetwo
elementsforeachqueryandO(n)intheend.Sothesolution
wouldbeO(n).

Reply

3monthsago, # |

ThanksPrinceOfPersiaforthisveryveryusefularticle.:)

Note:pleaseedit line1 afterR/BTreeimage bust > but .:)


http://codeforces.com/blog/entry/15729

21/23

8/27/2015
HitmanBBa

AlgorithmGym::DatastructuresCodeforces
Note:pleaseedit line1 afterR/BTreeimage bust > but .:)

Reply

3monthsago, # |

Cansomeonepleaseelaboratethemethodusedforbuildingtrie?Itriedto
dryrunitonsometestcasesbutcouldnotmakeouthowtheresulting
arrayisatrie.Thanks.

Reply

manuag

3monthsago, # ^ |

Gotit!

Reply
manuag

3monthsago, # |

Veryinformative.Thanksalot.

Reply
Bazinga112

7weeksago, # |

howcanmultipleassignmentmodificationsbedonethisway?please
suggestanidea,sourcecodebingo!!

Reply

oflocon

7weeksago, # |

Rev.2

Isthereawaytosolveaproblemwhichissameaspartialsuminsteadof
addingvalue,weneedtochangevaluesintheinterval[l,r]tov.Isthere
anygoodsolutionforthis.
singh_iitian

Reply

7weeksago, # ^ |

SegmentTree+LazyPropagation

Reply
radoslav11

7weeksago, # ^ |

+13

AstrologersproclaimedtheWeekofCodeChefChallenge.Amount
ofsimilarquestionsdoubled.
slycelote

Reply

7weeksago, # |

InThepersistentdatastructurefunctionweshouldhavea
s[id]=s[L[id]]+s[R[id]]beforethereturnstatement
Adkay

Reply

http://codeforces.com/blog/entry/15729

22/23

8/27/2015

AlgorithmGym::DatastructuresCodeforces
8daysago, # |

eshaankuls25

Ifthesizeoftheroot'sintervalisn,segmenttreecouldhaveupto4n
nodes.Howcanwejustifyit?WhenIconstructedanexample,Igot2n1
nodes.Inwhatcasesitwillhave4nnodes.

Reply

8daysago, # ^ |

Rev.4

+3

Sorry,Ididn'texplainwellinthepreviouspost.
First,intervaltreeisbalancedbinarytree.Sofirstlevelhas1
node,second2,third4...ithlevelhas2^(i1)nodes.

allllekssssa

Ifyourintervalhaslenghtn,youmustaddsomeextraelements
tillnisnotapoweroftwo(conditionforbalancedtree).Nowthe
lastlevelhasmnodes(m=2^k)andhigerlevelshave2^(k1)
nodes,2^(k2)nodes...Sumofallnodesis2^(k+1)1.Thatis
equalwith2m1nodes.Theworstcaseiswhenn=2^x+1andin
thatcaseyoushouldhaveabout4nnodes,inbestcaseifn=2^x
youwillhave2n1nodes.
Ihopethatnoweverythingisclear.

Reply

Codeforces(c)Copyright20102015MikeMirzayanov
TheonlyprogrammingcontestsWeb2.0platform
Servertime:2015082709:48:27(c2).

http://codeforces.com/blog/entry/15729

23/23

You might also like