Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

6/5/2014 Blog entries - Codeforces

http://codeforces.com/blog/elfus0 1/30

codestrophe|Logout
Sponsoredby

YouhaveWow!Youhave+178!
Searchbytag


HOME CONTESTS GYM PROBLEMSET GROUPS RATING API HELP RCC
elfus0'sblog
CodeforcesRound#245Editorial
430APointsandSegments(easy)
Theproblemasksyoutooutput1ifthereisnosolution.Anaturalquestionisnow:when
thereisnosolution?Trytocomeupwithatestlikethis!
Aftersomeanalysis,youllseeanyhowwedrawthepointsandthelines,therewillalways
beasolution.Bymanuallysolvingsmallcases,youmightalreadyhavefoundthepattern.
Butfornow,letsassumeanyhowwedrawpointsandlines,therewillalwaysbeasolution.
Letshaveafixedsetofpoints.Then,anyhowwedrawaline,thereshouldstillbea
solution.So,weneedtofindacoloringofpoints,suchasforeveryline,|numberofred
pointswhichbelongtoitnumberofbluepointswhichbelongtoit|<=1.
Supposeanytimeyoucolorapointwithredyouassignit+1value.Also,anytimeyoucolorit
withblueyouassignit1value.Then,forasegment,thedrawingisgoodifS=sumof
valuesassignedtopointsthatbelongtosegmentisbetween1and1(inotherwords|S|<=
1).Letssortpointsincreasingbyabscissa.Itsusefulbecausenow,forasegment,there
willbeacontiguousrangeofpointsthatbelongtothatsegment.Forexample,supposemy
currentsegmentis[3,7]andtheinitialsetofpointswas{4,1,5,2,8,7}.Initially,pointsthat
belongtothesegmentwouldbefirst,thirdandsixth.Letssortthepointsbyabscissa.It
lookslike{1,2,4,5,7,8}.Youcanseenowthereisacontiguousrangeofpointsthat
belongsto[3,7]segment:moreexactlythird,fourthandfifth.
Wereducedproblemto:givenanarray,assigniteither+1or1valuessuchas,foreach
subarray(contiguousrange),thesumSofsubarrayselementsfollowsthecondition|S|<=
1.Beforereadingon,trytocomeupwithanexamplebyyourself.
Mysolutionusesthepattern:+11+11+11...Eachsubarrayofitwillhavesumofits
elementseither1,0or1.Howtoproofit?Whendealingwithsumsofsubarrays,agood
ideaistousepartialsums.Denotesum[i]=x[1]+x[2]+...+x[i].Then,sumofasubarray
[x,y]issum[y]sum[x1].Partialsumsforthepatternlookslike:101010....Hence,
thereare4possiblecases:
1/sum[x1]=0andsum[y]=0.sum[y]sum[x1]=0
2/sum[x1]=1andsum[y]=1.sum[y]sum[x1]=0
3/sum[x1]=0andsum[y]=1.sum[y]sum[x1]=1
4/sum[x1]=1andsum[y]=0.sum[y]sum[x1]=1
Hence,eachsubarraysumiseither1,0or1.So,generalalgorithmlookslike:sortpoints
byabscissa,assignthemred,blue,red,blue,...andthensortthembackbyoriginalorder
andprintthecolors.
430BBallsGame
Thisisanimplementationproblem.Thereisnotsomuchtoexplain.Perhapsthetrickat
implementationproblemsistodividecodeintosmallersubproblems,easytocodeandthen
putthemtogether.Idontknowifthisistheuniversallytruth,butthisishowIapproach
them.Here,therearetwomainparts:thepartwhenyouinsertaballbetween2ballsand
thepartwhenyouseehowmanyballsaredestroyedafterthemove.Wecankeepanarray
a[]withinitialconfigurationofballs,thenforeachinsertioncreateanarrayb[]withcurrent
configurationaftertheinsertion.Ifmyballisinsertedafterpositionpos,bissomethinglike
this:b=a[1....pos]+{my_ball}+a[pos+1....n].
Fornowwehavearrayb[]andweneedtoknowhowmanyballswilldisappear.The
problemstatementgivesusanimportantclue:no3ballswillinitiallyhavethesamecolor.
Thismeans,anytime,atmostonecontiguousrangeofballsofsamecolorwillexistwith
Beforecontest
CodeforcesRound#252(Div.2)
3days

Payattention
codestrophe
Rating:1489
Contribution:0
Settings
Blog
Teams
Submissions
Favourites
Talks
Contests

codestrophe
# User Rating
1 tourist 3228
2 rng_58 2795
3 Petr 2787
4 scott_wu 2767
5 WJMZBMR 2733
6 0O0o00OO0Oo0o0Oo 2718
7 vepifanov 2712
8 SergeyRogulenko 2703
9 yeputons 2690
10 meret 2655
Countries| Cities| Organizations Viewall

Toprated
# User Contrib.
1 DmitriyH 146
2 Fefer_Ivan 142
3 Petr 133
4 Sereja 131
5 MikhailRubinchik 129
5 elfus0 129
7 Egor 128
8 Zlobober 123
9 Nickolas 122
10 Xellos 120
10 dalex 120
Viewall

Topcontributors
Handle:
Find

Finduser
Byelfus0,3weeksago, ,
ELFUS0 BLOG TEAMS SUBMISSIONS TALKS CONTESTS
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 2/30
lengthatleast3.Ifitexists,wehavetoremoveit.Then,wehavetorepeatthisprocess.
Soalgorithmissomethinglikebubblesort:whileb[]arrayhaschangedlaststep,continue
algorithm,otherwiseexitit.Now,searchaniforwhichb[i]=b[i+1]=b[i+2].Then,takethe
maximumj>iforwhichb[k]=b[i],withi<k<=j.Youhavetoremovefromb[]thesubarray
[i...j]andaddji+1tothedestroyedballs.Youllneedtoreturnthissum1,becausethe
ballyouaddedwasntthereatbeginning.Payattentiononcasewhenyoucantdestroy
anything,youneedtooutput0insteadof1.ThereareO(n)positionswhereyoucaninsert
thenewball,foreachofthemtherearemaximalO(n)stepswhenballsaredeletedand
deletingballstakesmaximalO(n)time,sooverallcomplexityisO(n^3).
Note:inmysolution,Idontactuallydodeletion.IfIhavetodeletearange[i,j]Icreatea
newarrayc[]=b[1...i1]+b[j+1....n]andthencopyc[]intob[]array.ThisguaranteesO(n)
timefordeletion.
429AXortree
Thereissomethingtolearnfrompropagatingtreeproblem,usedinround#225.Itshow
thespecialoperationworks.Illcopypastetheexplanationfromthere(withsome
modification,correspondingtotheproblem):
Letsdefinelevelofanodethenumberofedgesinthepathfromroottothenode.Root
(node1)isatlevel0,sonsofrootareatlevel1,sonsofsonsofrootareatlevel2andso
on.Nowsupposeyouwanttodoaspecialoperationtoanodex.Whatnodesfromsubtree
ofxwillbeflipped?Obviously,xwillbefirst,beinglocatedatlevelL.Sonsofx,locatedat
levelL+1willnotbeflipped.Sonsofsons,locatedatlevelL+2,willbeflippedagain.So,
nodesfromsubtreeofxlocatedatlevelsL,L+2,L+4,...willbeflipped,andnodes
locatedatlevelsL+1,L+3,L+5wontbeflipped.LetstakethosevaluesofLmodulo2.
AllnodeshavingremainderLmodulo2willbeflipped,andnodeshavingreminder(L+1)
modulo2willnot.Inotherwords,forafixedx,atalevelL,letyanodefromsubtreeofx,at
levelL2.IfLandL2havesameparity,ywillbeflipped,otherwiseitwont.Wellusethisfact
later.Fornow,letsthinkwhatshouldbeourfirstoperation.Letsconsidersomenodes{x1,
x2,...,xk}withpropertythatx1issonofx2,x2issonofx3,...xk1issonofxkandparityof
levelsofthesenodesisthesame.Supposebynowwefixed{x1,x2,...,xk1}(theircurrent
valueisequaltotheirgoalvalue),butxkisstillnotfixed.Aftersometime,wellhavetofix
xk.Now,bydoingthis,allnodes{x1,x2,...,xk1}willgetflippedandhenceunfixed.Weve
donesomeuselessoperations,soourusedstrategyisnottheonethatgivesminimal
numberofoperations.
Whatwelearnfromthisexample?SupposeIwanttocurrentlyfixanodeX.Thereisno
pointtofixitnow,unlessallancestorsYofXwithpropertylevel(Y)=level(X)(mod2)are
fixed.ButwhatifanancestorYofXisnotfixedyetandlevel(Y)!=level(X)(mod2)?CanI
fixnodeXnow?Theanswerisyes,asfutureoperationsdoneonYwontaffectX.But,by
samelogic,IcanfirstlyfixYandthenfixX,becauseagainoperationsdoneonYwont
affectX.Wegetaniceproperty:thereisnopointtomakeanoperationonanodeXunless
allancestorsofXarefixed.
Howcanweusethisproperty?Whatshouldbethefirstoperation?Weknowthatnode1is
theroot,henceitalwayswonthaveanyancestor.Allothernodesmighthavesometimes
notfixedancestors,butweknowforsure,forbeginning,node1wonthaveanyunfixed
ancestor(becauseitwonthaveany).So,forbeginningwecanstartwithnode1.More,
supposenode1isunfixed.Theonlywaytofixitistomakeanoperationonit.Sinceits
unfixedandthisistheonlywaytofixit,youllbeobligatedtodothisoperation.Thismeans,
inanoptimalsequenceofoperations,youllbeobligatedtodothisoperation,too.
So,ifnode1wasunfixed,wedidanoperationonit.Ifitwasalreadyfixed,weredonewith
it.Whatarenextnodesweknowforsurethatwillhaveallancestorsfixed?Sonsof1,
becausetheyhaveonlyoneancestor(node1),whichweknowitsfixed.Wecanonlyfix
thembydoingoperationsofthem(doingoperationsonnode1/sonsofthemwontaffect
them).Sinceeventuallytheyhavetobefixedandonlywaytobefixedistodoanoperation
onthem,inanoptimalsequenceofoperations,wellhavetomakeoperationsonthem.
Letsmoveon.Whatarenextnodesthatweknowforsureallancestorsofthemwillbe
fixed?Sonsofsonsof1.Wecanfixthembydoinganoperationofthem,orbydoingan
operationon1.Butdoinganoperationon1isnthelpful,becauseevenifitfixesthisnode,it
unfixes1.Then,youllhavetodoonemoreoperationon1,whichwillunfixcurrentnode,so
wedotwouselessoperations.Itturnsout,theonlywaytofixthemistodoanoperationon
them.
Generally,supposeallancestorsofnodexarefixed.Wegetthecurrentvalueofnodex
aftertheoperationsdoneonancestorsofx.Ifthecurrentvalueisnottheexpectedone,
wellhavetodoanoperationonnodex(thisistheonlywaytofixthenodex).Now,after
nodexisfixed,wecanprocesssonsofit.Thisstrategyguaranteesminimalnumberof
RodionGorkMysiteforgreycoders
CodeAbbey
praveen123CodeforcesRound#251Editorial
AkshajKVeryweirdbug
praveen123CodeforcesRound#251
LLintSpojProblem
Fefer_IvanCodeforcesAPI
byte_gamblerCodeforcesround250
byte_gamblerSPOJFibosum
alaudoCodeexecutionerroronalengthyinput
howtodebugthisissue?
huzecongCodeforcesRound#248Editorial
alliumnskbisIhaveaproblem
ping128Loopingthroughallsubsetsofasetof
Nelements
ravelo1991AboutRound#251badthings
happenonjudge
ShadekRound251DIV2ProblemC
yak_exColorizestandingsbyusedprogramming
language
yak_exMultipleratinggraphwithotheraccounts

TparsaProblemC(Div.2)Round#94
t.janssen52numberofsolvedsubmissions
wrong?
mobitOnlydiv2contests
EgorCHelper3.9
ErdemKirezGoodSolutionFor440A
RupaiSPOJEPALINTLE
MikeMirzayanovFrequentlyAskedQuestions
alpha_RAUClassesofgraphisomorphism
yashar_sb_sbblitzcontests
Detailed

Recentactions
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 3/30
operations,becausewedoanoperationonlywhenwereforcedtodoit.
ThisleadsimmediatelytoanO(N^2)algorithm,byeverytimeweneedtodoanoperation
toupdateittonodesfromitssubtree.HowtogetO(N)?Supposeweareatnodexand
wanttoknowitscurrentvalueafteroperationsdoneforitsancestors.Obviously,itis
definedbyinitialvalue.Ifweknownumberofoperationsdonesofarbyevenlevelsforits
ancestors,numberofoperationsdonesofarbyoddlevelsandcurrentlevel,wecan
determinethecurrentvalue.Supposethesevaluesare(initial_value,odd_times,
even_times,level).Weobservethat2operationscanceleachother,sowecantakethis
numbermodulo2.Iflevelmod2=0,thenonlyeven_timeswillmatter,andcurrent_value=
(initial_value+even_times)%2.Otherwise,current_value=(initial_value+odd_times)%2.
Wecansend(even_times,odd_timesandlevel)asDFSparameters,socurrent_valuecan
becalculatedinO(1),andoverallcomplexityisO(N).
429BWorkingout
Theparticularityofthisproblemwhichmakesitdifferentbyotherproblemofthiskindisthat
pathsneedtocrossexactlyonecellandIahubcangoonlyrightanddown,Iahubinacango
onlyrightandup.Let'strytocomeupwithasolutionbasedonthesefacts.Agoodstartis
toanalyzeconfigurationspossibleformeetingcell.Iahubcancomeeitherfromrightor
downandIahubinacancomeeitherfromrightorup.However,ifbothIahubandIahubina
comefromright,theymusthavemetinothercellaswellbefore(thecellintheleftofthe
meetone).Similarly,ifonecomesfromupandotheronefromdown,theirpathswillcross
eitheronuppercell,lowercellorrightcell.
Only2possiblecasesare:Iahubcomesfromright,IahubinacomesfromuporIahub
comesfromdown,Iahubinacomesfromright.Bydrawingsomeskatchesonpaper,you'll
seenextcellvisitedaftermeetingonewillhavethesamedirectionforbothofthem.More,
theywillnevermeetagain.SoIahubcomesfromright,goestoright,Iahubinacomesfrom
up,goestouporIahubcomesfromdown,goestodownandIahubinacomesfromright,
goestoright.
Inthedrawing,Iahub'spossiblevisitedcellsareblue,Iahubina'spossiblevisitedcellsare
redandmeetingcellispurple.Denote(X,Y)meetingcell.
Forfirstcase,Iahubcomesfrom(1,1)to(X,Y1)bygoingdownorright.Next,hegoes
from(X,Y+1)to(N,M)bygoingdownorright.Iahubinagoesfrom(M,1)to(X+1,Y)by
goinguporrightandthenfrom(X1,Y)to(1,M)bygoingwithsamedirections.In
secondcase,Iahubgoesfrom(1,1)to(X1,Y)andthenfrom(X+1,Y)to(N,M)and
Iahubinagoesfrom(M,1)to(X,Y1)andthenfrom(X,Y+1)to(1,M).
Wecanprecalculatefordynamicprogrammingmatrixesandwe'redone.
dp1[i][j]=maximalcostofapathgoingfrom(1,1)to(i,j)onlydownandright.
dp2[i][j]=maximalcostofapathfrom(i,j)to(1,m)goingonlyupandright.
dp3[i][j]=maximalcostofapathfrom(m,1)to(i,j)goingonlyupandright.
dp4[i][j]=maximalcostofapathfrom(i,j)to(n,m)goingonlydownorright.
Andhereismyfullimplementationofrecurrences(C++only):
for(inti=1i<=n++i)
for(intj=1j<=m++j)
dp1[i][j]=a[i][j]+max(dp1[i1][j],dp1[i][j1])
for(intj=mj>=1j)
for(inti=1i<=n++i)
dp2[i][j]=a[i][j]+max(dp2[i1][j],dp2[i][j+1])
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 4/30
for(inti=ni>=1i)
for(intj=1j<=m++j)
dp3[i][j]=a[i][j]+max(dp3[i+1][j],dp3[i][j1])
for(inti=ni>=1i)
for(intj=mj>=1j)
dp4[i][j]=a[i][j]+max(dp4[i][j+1],dp4[i+1][j])
Also,payattentionthatmeetingpointscanbecells(i,j)with1<i<nand1<j<m.(why?)
429CGuesstheTree
Theconstrainn<=24immediatelysuggestusanexponentialsolution.24numbersseems
tobenottoobig,butalsonottoosmall.Whatifwecanreduceitbyhalf?Wecandothis,by
analyzingproblemsrestrictionmorecarefully.
Theproblemstatesthateachinternalnodehasatleasttwosons.Afterdrawingsometrees
likesthese,onemaynoticetherearealotofleafsinthem.Foratreewiththisproperty,
numberofleafsisatleast(n+1)/2.Wellproofthisaffirmationbymathematicalinduction.
Forn=1,affirmationistrue.Now,supposeourtreehasnnodes,andtherootofithas
sons{s1,s2,...,sk}.Letsassumesubtreeofs1hasn1nodes,subtreeofs2hasn2nodes,
...,subtreeofskhasnknodes.Byinductionwegetthats1hasatleast(n1+1)/2leafs,...,
skhasatleast(nk+1)/2leafs.Summingup,wegetthatourtreehasatleast(n1+n2+...
+nk+k)/2leafs.Butn1+n2+...+nk=n1.Soithasatleast(n+k1)/2leafs.But,
byhypothesisk>=2,soourtreehasatleast(n+1)/2leafs.
Forn=24,therewillbeatleast13leafs,soatmost11internalnodes.Itlooksmuchbetter
nowforanexponentialsolution!Beforepresentingit,weneedonemoreobservation.
Supposewesortedc[]arraydecreasing.Now,thefatherofnodeicanbeonlyoneofnodes
{1,2,...,i1}.Nodes{i+1,i+2,...,n}willhaveatmostasmuchnodesasnodei,sothey
cantbefatherofi.Bydoingthisobservationwecanstartalgorithm:startwithnode1and
assignitssons.Then,movetonode2.Ifitdoesnothaveafather,wewonthaveone,so
currentconfigurationisgood.Ifhehasafather(inthiscasenode1),thentreeisconnected
sofar.Sowecanassignchildrenofnode2.Generally,ifanodeidoesnothaveafather
whenitsprocessed,itwonthaveinfutureeither.Ifithas,thetreeisconnectedsofar,so
weaddchildrenofi.
Letsintroducethefollowingdynamicprogramming.Letdp[node][mask][leafs]=isit
possibletocreateatreeifallnodes{1,2,...,node}havealreadyafather,exactlyleafs
nodesdonthaveoneandinternalnodescorrespondingto1inbitmaskmaskalsodont
haveone?Ifyouneverheartaboutbitmaskword,thisproblemisnotgoodforyoutostart
with.IrecommendyouproblemEfromround#191,whereIexplainedmorehowbitmasks
work.Backontheproblem.Ifnodehas1initsbitfromthemask,thenweknowforsurethe
treecantbebuilt.Otherwise,letsassignsonsfornode.Wetakeallsubmasksofmask
(numberobtainedbychangingsomebitsfrom1to0)andmakesumofdegreesfor
correspondingnodes.DenotethisnumberasS.Thesearetheinternalnodes.Howabout
theleafs?WeneedtohaveavailableL=c[node]S1leafs.IfLis<=thanleafs,wecan
usethem.IfL<0,obviouslywecantbuildthetree.WillremainobviouslyleafsLleafs.
Thenewmaskwillbemask^submask.Also,weneedtoiteratetonode+1.Ifdp[node+1]
[mask^submask][leafsL].Onemoreconditionthatneedstobeconsidered:nodeneeds
tohaveatleast2sons.ThismeansL+cnt>1(wherecntarenumberofinternalnodes
used).Whendowestopthedp?Whenc[nod]=1.Ifmask=0andleafs=0,thenwecan
buildthetree.Otherwise,wecant.
Letsanalyzethecomplexity.ThereareO(2^(n/2))masks,eachofthemhasO(n)leafs,
foreachO(n)node.ThisgivesO(2^(n/2)*n^2)states.Apparently,iteratingoverall
submasksgivesO(2^(n/2))timeforeachsubmask,sooverallcomplexityshouldbeO(4^
(n/2)*n^2).Butthiscomplexityisoverrated.Takingallsubmasksforallmaskstakes
O(3^(n/2))time,insteadofO(4^(n/2))time.Why?Considernumberswritteninbase3:
foramaskandasubmaskwecanassign3ternarydigitstoeachbit:
0ifbitdoesnotappearinmask
1ifbitappearsinmaskbutnotinsubmask
2ifbitappearsinmaskandinsubmask
Obviously,thereareO(3^(n/2))numberslikethisandthetwoproblemsareequivalent,
sothissteptakesO(3^(n/2))andoverallcomplexityisO(3^(n/2)*n^2).
429DTrickyFunction
LetsdefineS[i]=a[1]+a[2]+...+a[i].Then,f(i,j)=(ij)^2+(S[i]S[j])^2.Tryingto
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 5/30
minimizethisfunctionseemscomplicated,soweneedtomanipulatetheformulamore.We
knowfromthemathsthatiff(i,j)isminimized,thenalsof(i,j)=sqrt((ij)^2+(S[i]S[j])
^2)isalsominimized.Doesthisfunctionlookfamiliartoyou?Supposeyougettwopointsin
2Dplane:onehavingcoordinates(i,S[i])andtheotheronehavingcoordinates(j,S[j]).One
canseethatf(i,j)isexactlyeuclideandistanceofthosepoints.So,iff(i,j)isadistance
betweentwopointsinplane,whenisachievedminimalf(i,j)?Fortheclosesttwopointsin
plane(thepointswhicharelocatedatminimaldistance).So,havingsetofpoints(i,S[i]),we
needtocomputeclosesttwopointsfromthisplane.Thereisaclassicalalgorithmthatdoes
thisinO(n*logn).
429EPointsandSegments
Theproblemasksyoutocheckthepropertyforaninfinityofpoints.Obviously,wecantdo
that.However,wecanobservethatsomecontiguousrangesonOXaxishavethesamerx
andbxvalues.Likeasweeplinealgorithm,apossiblechangemayappearonlywhenanew
segmentbeginsorwhenanoldoneends.Soletsconsidersetofpointsformedbyallli
reunitedwithsetofpointsformedbyallri.Sortthevaluesincreasing.Supposethesetlooks
like{x1,x2,...,xk}.Thenranges[0,x1)[x1,x2)...[xk1,xk)[xk,infinity)aretheonlyones
thatneedtobeconsidered.Ifwecantakeanarbitrarypointfromeachrangeandthe
propertyisrespectedforallpoints,thenthedrawingisgood.
Weneedtocolorsegments.Buteachsegmentisareunionofrangesliketheonesfrom
above.Whenyoucolorasegment,allrangesfromitwillbecoloredtoo.So,aftercoloring
thesegments,foreachrange,|numberoftimesrangewascoloredwithbluenumberof
timesrangewascoloredwithred|<=1.
Itstimetothinkcreative.Wecanseerangesasvertexesofagraphandsegmentsas
edges.Forexample,ifasegmentisformedbyranges{Xi,Xi+1,...,Xj1,Xj}weaddan
undirectededgefromitoj+1.Weneedtocolortheedges.Wedividethegraphinto
connectedcomponentsandapplysamelogicforeachcomponent.Next,bygraphIllrefer
toaconnectedgraph.
Letsassumethatourgraphhasalldegreeseven.Then,itadmitsaneuleriancycle.
Suppose{x1,x2,...,xk}isthelistofnodesfromthecycle,suchasx1x2x2x3...xkx1are
theedgesofit,inthisorder.Weapplyarule:ifxi<xi+1,wecoloredgebetweenxiandxi+1
inred.Otherwise,wecoloritinblue.Whathappensforanode?Wheneverarededge
crossesit(forexampleedge15crossesnode4)ablueedgewillalwaysexisttocrossit
again(forexampleedge62crossesnode4).Thisisbecauseofpropertyofeulercycle:
supposewestartedfromanodexandgoneinleft.Weneedtoreturntoit,buttheonly
waytodoitisanedgewhichgoestoright.So,whendegreesofgrapharealleven,for
everypointonOXaxis,differencebetweenrxandbxwillbealways0.
Letssolvethegeneralcasenow.Somenodeshaveodddegree.Buttherewillalwaysbe
anevennumberofnodeswithodddegrees.Why?Supposethepropertyisrespectedfor
someedgesaddedsofarandnowweaddanewone.Therearetwocases:
1/theedgeconnectstwonodeswithodddegree.inthiscase,thenumberofnodeswith
odddegreesdecreasesby2,butitsparitydoesnotchange.
2/theedgeconnectsonenodewithodddegreeandonenodewithevendegree.Now,
degreeofoldoddonebecomesevenanddegreeofoldevenonebecomesodd.So
numberofnodeswithodddegreesdoesnotchange.
SosupposethenodeswithodddegreesareX1X2...Xk(kiseven).AssumeX1<X2<...<
Xk.Ifweaddonemoreedgetoeachofthesenodes,aneulercyclewouldbepossible.
However,wecantaddedges,becauseedgesaresegmentsfromtheinput.Butwecan
imaginethem.Ofcourse,thiswellcreateanimbalancebetweenredandblueedges,but
letsseehowbigitis.WhatifweaddafictiveedgebetweenX1toX2,betweenX3toX4,...,
betweenX(k1)toXk?Inthisway,allthosenodeswillhaveevendegree.SoforeachXi(i
odd)weaddadummyvertexYiandsomedummyedgesfromXitoYiandfromYitoXi+1.
Nowletsseetheeffect:ifthefictiveedgesexisted,thebalancewouldbe0.Buttheydonot
exist,sooneofrxorbxwilldecrease.Sonow|rxbx|<=1,goodenoughforproblems
restrictions.
Readmore
TutorialofCodeforcesRound#245(Div.1)
TutorialofCodeforcesRound#245(Div.2)
codeforces, round, 245
+115
elfus0 3weeksago 31


6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 6/30
CodeforcesRound#245
Helloeveryone!
WeinviteyoutoparticipateinCodeforcesRound#245,scheduledforSunday,11thMayat
7:30MSK.ThisisthefourthroundIwriteforCodeforces.Afterthelastroundyourupvotes
helpedmegetintotheContributorsTop10.ThanksforallyourgoodremarksI'lltryanddo
mybestinorderforthisroundtobeatleastasgoodasthepreviousone.
ThisroundispreparedbymyfriendIoanPetcu(authorofD1E)andI(allproblems,except
D1E).We'vechosentheproblemstobeasdiverseaspossiblenotwoproblemswill
sharethesameprogrammingtechnique.Astheproblemsarevaried,wehopeyou'llfindat
leastoneproblemofyourtaste.ThemaincharacterisIahub,currentlythenumberone
rankedcontestantintheRomanianselectioncampsforIOI.Afterreadingtheproblem
statements,you'llseewhatthelifeofaverygoodRomaniancompetitiveprogrammerislike
(justkidding,it'sjustmyevilimagination).
Thisroundwouldn'thavebeenpossiblewithoutthepeoplethathelpedmetestit:Gerald
Agapov(Gerald),DamianStraszak(DamianS),DanAlexandru(danalex97)andVlad
Badelita(vladb).Asalways,wedliketothankMikeMirzayanovforcreatingthePolygon
systemandCodeforcesplaftormandtoDelinurfortranslatingtheproblemsinRussian.
Wewishhighratingstoeveryoneand,aboveall,havefun!
UPDScoreDistribution
Division1:5001000150020002000
Division2:5001000150020002500
Iapologizeforalltechnicalissuesduringtheround,fromtheambiguousproblem
statementstoveryeasyproblemD1D.Inmytrialtoinventanicetask,Ididn'tseethat
straightforwardsolutionforitandIhavenoexcuseforthis.
UPDWinners
Division1:
1. SergeyRogulenko
2. scott_wu
3. vepifanov
4. WJMZBMR
5. ballon
Division2:
1. clavichord93
2. backstreetboy
3. Dgleich
4. PopovkinAndrey
5. roben_76
UPDEditorial
UPDStatistics
Readmore
AnnouncementofCodeforcesRound#245(Div.1)
AnnouncementofCodeforcesRound#245(Div.2)
codeforces, round, 245
CodeforcesRound#225Editorial
384A
Usually,whenyoudonthaveanyideahowtoapproachaproblem,agoodtryistotake
Byelfus0,4weeksago, ,
+313
elfus0 4weeksago 194


Byelfus0,4monthsago, ,
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 7/30
somesmallexamples.
SoletsseehowitlooksforN=1,2,3,4and5.WithCInotedthecoderandwith*Inoted
anemptycell.
BynowyoushouldnotethatanswerisN^2/2whenNisevenand(N^2+1)/2whenN
isodd.Good.Generally,afteryoufindapossiblesolutionbytakingexamples,youneedto
proveit,thenyoucancodeit.
Inordertoproofit,oneneedstodofollowingsteps:
1/proveyoucanalwaysbuildasolutionhavingN^2/2(or(N^2+1)/2)pieces.
2/provethatN^2/2(or(N^2+1)/2)ismaximalnumbernootherbiggersolutioncan
beobtained.
Forproof1/imagineyoudocoloringlikeinachesstable.
Thekeyobservationisthatbyplacingallcodersonblacksquaresoftable,notwocoders
willattack.Why?Becauseapieceplacedatablacksquarecanattackonlyapieceplaced
atawhitesquare.Again,why?Supposechesstableis1based.Then,asquare(i,j)is
blackifandonlyifi+jiseven.Apieceplacedat(i,j)canattack(i+1,j),(i1,j)(i,j+1)or
(i,j1).Thesumofthosecellsisi+j+1ori+j1.Butsincei+jiseven,i+j+1andi+j
1areodd,hencewhitecells.
DependingonparityofN,numberofblackcellsiseitherN^2/2or(N^2+1)/2.ForN
even,onecanobservethatthereareequalamountofblackandwhitecells.Totalnumber
ofcellsisN^2,sonumberofblackcellsisN^2/2.ForNodd,numberofblackcellsis
numberofwhitecells+1.Wecanimaginaryaddawhitecelltotheboard.Now,numberof
blackcellswillbealsoequaltonumberofwhitecells,soansweris(N^2+1)/2.
2/Twocodersattackeachotheriftheyareplacedattwoadjacentcells,oneblackand
otheronewhite.Oneneedstoprovethataddingmorethannumberfrom1/willcausethis
tohappen.Ifyouplaceacoderatawhitecell,youwontbeabletoplaceatleastonecoder
atablackcell,soinbestcaseyoudontwinanythingbydoingthis.Hence,itsoptimallyto
placeallcodersonsamecolorcells.Sincecellscoloredinblackarealwaysmoreorequal
towhiteones,itsalwaysoptimallytochooseblackcolor.Butnumberfrom1/isthenumber
ofcellshavingblackcolor.Addingonemorepiecewillforceyoutoaddittoawhitecolor
cell.Now,youllhaveapieceplacedatablackcoloredcellandoneplacedatanadjacent
whitecoloredcell,sotwocoderswillattack.Hence,wecantplacemorethannumberfrom
1/pieces.
Code:http://pastie.org/8651801
384B
LetsstartbysayingwhenarrayA[]issorted:
1/issortedinascendingorderwheni<jandA[i]<=A[j].ItisNOTsortedwheni<jandA[i]
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 8/30
>A[j].
2/issortedindescendingorderwheni>jandA[i]<=A[j].ItisNOTsortedwheni>jand
A[i]>A[j].
Iahubcanchoose2indicesi,jandswapvalueswhenA[i]>A[j].IfA[i]<=A[j],hellignore
operation.Hence,ifhewantstosortallarraysinascendingorder,hechoosesindicesi,j
wheni<jandperformoperation.Otherwise,inallhisoperationsheusesindicesi,jsuchas
i>j.Agoodoperationiswhenchoosingindicesi<jforascendingordersortingandi>j
fordescendingordersorting.Bydoingonlygoodoperations,afteranarrayissorted,itwill
staysortedforever(forasortedarray,allgoodoperationswillbeignored).
Fromherewegetourfirstidea:useanysortingalgorithmyouknowandsorteacharray
individually.Whenprintswapsdonebysortingalgorithmchosen,printthemasgood
operations.However,sortingeacharrayindividuallycancauseexceedingM*(M1)/2
operationslimit.Anotherpossiblesolutionwouldbe,afteryoudidanoperationtoanarray,
toupdatetheoperationtoallarrays(youprintedit,soitcountstoM*(M1)/2
operationslimitmakingittoallarrayswillhelpsometimesandinworstcaseitwontchange
anything).However,youneedtocodeitverycarefulinordertomakethisalgorithmpass
thetimelimit.Doingthisinacontestisnotthebestidea,especiallywhenimplementation
couldbecomplicatedandyouhavenoguaranteeitwillpasstimelimit.
Sowhatelsecanwedo?Wecanthinkoutofbox.InsteadofsortingspecificNarrays,you
cansortallpossiblearraysoflengthM.Findasequenceofgoodoperationssuchas,
anyhowIdchooseanarrayofsizeM,itwillgetsortedascending/descending.
Illshowfirstlyhowtodoforascendingsorting.Atposition1itneedstobeminimalelement.
Canwebringminimalelementthereusinggoodoperations?Yes.Justdo121314...
1M.Itbasicallycompareselementfromposition1toanyotherelementfromarray.When
otherelementhassmallervalue,swapisdone.AftercomparingwithallMelements,
minimalvaluewillbeatposition1.BynowonIllignoreposition1andmovetoposition2.
Supposearraystartsfromposition2.Italsoneedsminimalvaluefromarray,exceptvalue
fromposition1(whichisnolongerinarray).Hencedoing232425...2Mis
enough,bysimilarreasons.Forapositioni,Ineedminimalvaluefromarray,except
positions1,2,...,i1.Isimplydoii+1ii+2...iM1iM.Byarrivingatpositioni,array
willbesortedascending.Thealgorithmissimply:
for(inti=1i<M++i)
for(intj=i+1j<=M++j)
cout<<i<<<<j<<\n
ThisalgorithmdoesexactlyM*(M1)/2moves.
Canyoufindouthowtosortarrayindescendingorder?Trytothinkyourself,thenifyou
dontgetitreadnext.Atfirstpositionofadescendingarrayitneedstobemaximalvalue.
Similarlytoascendingorder,wecando213141...M1.WhenImatapositioni
andIcompareitsvaluetovaluefromposition1,doingoperationi1checksifA[i]>A[1].If
so,itswapsA[i]andA[1],soposition1willcontainnowthemaximumvaluesofar.Similarly
tologicfromascendingorder,whenImatpositioni,Ineedmaximumvaluefromarray
exceptpositions1,2,...,i1,soIdoi+1ii+2i...Mi.Algorithmis:
for(inti=1i<M++i)
for(intj=i+1j<=M++j)
cout<<j<<<<i<<\n
Obviously,thisdoesaswellM*(M1)/2operationsworstcase.Allalgorithmisabout10
linesofcode,muchbetterthanothersolution,whichrequirestwomanuallysortsandalso
hasachancetoexceedTL.
Code:http://pastie.org/8651809
384C
Agoodstrategytoapproachthisproblemistothinkhowoptimalorderingshouldlooklike.
Forthis,letscalculateforeach2differentcowsiandjifcowineedstobemilkedbeforeor
aftercowj.Aswellshow,havingthisinformationwillbeenoughtobuildoptimalordering.It
isenoughtoconsideronlycaseswheni<j,casewheni>jisexactlytheoppositeofcasei
<j.Forformality,Illcalltheoptimalorderingpermutationandlostmilkthecostof
permutation.
So,foranoptimalpermutationPletstake2numbersi<jandseeinwhichcasesishould
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 9/30
appearbeforejinpermutation(iisbeforejifP[pos1]=i,P[pos2]=jandpos1<pos2
otherwisewellcalliisafterj).Wehave4possiblecases:
1/A[i]=0andA[j]=0
Ifweputibeforej,noadditionalcostwillbeadded.Sincejisinrightofiandionlyadds
costwhenitfindselementsinleftofi,jwontbeaffectedwhenprocessingi.When
processingj,iwillbealreadydeletedsoitwontaffectthecosteither.Hence,wecanputi
beforejandnocostwillbeadded.
2/A[i]=0andA[j]=1
Here,iandjcanappearinarbitraryorderinpermutation(icanbebeforeorafterj).No
matterhowwechoosethem,theywontaffecteachotherandcostwillremainthesame.
3/A[i]=1andA[j]=0
Aswell,hereiandjcanappearinarbitraryorder.Ifwechooseifirst,jwillbeinrightofit,so
costofpermutationwillincreasebyone.Ifwechoosejfirst,iwillbeinleftofitsocostof
permutationwillincreaseaswell.Nomatterwhatwedo,inthiscasecostofpermutation
increasesby1.
4/A[i]=1andA[j]=1
Here,ineedstobeafterj.Thisadds0cost.Takingibeforejwilladd1costtopermutation
(sincejisinrightofi).
Those4casesshowushowaminimalcostpermutationshouldlook.Inapermutationlike
this,onlycase3/contributestofinalcost,soweneedtocountnumberofindicesi,jsuchas
i<jandA[i]=1andA[j]=0(*).Ifweshowapermutationfollowingallrulesexists,task
reducesto(*).
Bycases2/and3/itfollowsthatinanoptimalpermutation,itonlymattersorderofelements
havingsamevalueinA[].Wecanputfirstlyallelementshavingvalue0inA[],thenall
elementshavingvalue1inA[].Wecanorderelementshavingvalue0bycase1/and
elementshavingvalue1bycase4/.Moreexactly,supposei1<i2<...<imand(A[i1]=
A[i2]=...=A[im]=0)andj1>j2>...>jn(A[j1]=A[j2]=...=A[jn]=1).Then,apermutation
followingallrulesis{i1,i2,...,im,j1,j2,...,jn}.Thispermutationcanalwaysbebuilt.
Hence,taskreducesto(*):countnumberofindicesi,jsuchasi<jandA[i]=1andA[j]=0.
WecanachieveeasilyanO(N)algorithmtodothis.Letsbuildanarraycnt[j]=numberof
0sinrange{j,j+1,...,N}fromarrayA.Wecaneasilyimplementitbygoingbackwards
fromNto1.Theresultissumofcnt[i],whenA[i]=1.
Code:http://pastie.org/8651813
384D
Ourfirstobservationisthatifthereisapathfrom(1,1)to(N,N),thenthelengthofpathis
2*N2.Sinceallpathshavelength2*N2,itfollowsthatifthereisatleastonepath,the
answeris2*N2andifthereisnt,theansweris1.Howtoproveit?Everypathfrom(1,
1)to(N,N)hasexactlyN1downdirectionsandexactlyN1rightdirections.So,total
lengthforeachpathisN1+N1=2*N2.
Sowereducedourproblemtodetermineifthereisatleastonepathfrom(1,1)to(N,N).
Thisisthechallengingpartofthistask,consideringthatN<=10^9.Howwouldyoudoit
foradecentlysmallN,letssayN<=10^3.Onepossibleapproachwouldbe,foreachrow,
keepasetofreachablecolumns.Wecouldeasilysolvethisonebydoingthis:if(i,j)
denoteselementfromithrowandjthcolumn,then(i,j)is(isnot)reachableif:
if(i,j)containsavolcano,then(i,j)isnotreachable.Otherwise,ifatleastoneof(i1,j)
and(i,j1)isreachable,then(i,j)isreachable.Otherwise,(i,j)isnotreachable.
Whatsthemainproblemofthisapproach?Itneedstokeeptrackof10^9linesandinworst
case,eachofthoselinescanhave10^9reachableelements.So,worstcaseweneed10^9
*10^9=10^18operationsandmemory.
Canweoptimizeit?Wecannoteforbeginningthatwedontneedtokeeptrackof10^9
lines,onlymlinesarereallynecessarily.Weneedonlylinescontainingatleastoneobstacle
(inworstcasewheneachlinecontainsonlyoneobstacle,weneedmlines).Howtosolveit
thisway?Supposelinenumberxcontainssomeobstaclesandlinesx+1,x+2,x+3do
notcontainanyobstacle.SupposewecalculatedsetS={y|cell(x,y)isreachable}.How
wouldlookS1,S2,S3correspondingtolinesx+1,x+2,x+3?ForS1,wecanreachcell
(x+1,ymin),whereyminisminimalvaluefromsetS.Then,wecanalsoreach{ymin+1,
ymin+2,...,N},bymovingrightfrom(x+1,ymin).SoS1={ymin,ymin+1,...,N}.Howdo
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 10/30
S2andS3look?Itseasytoseethattheyllbeaswell{ymin,ymin+1,...,N}.Soweget
followingoptimization:supposesetoflinescontainingatleastoneobstacleis{L1,L2,...,
Lk}.WeneedtorunalgorithmonlyforlinesL1,L1+1,L2,L2+1,L3,L3+1,...,Lk,Lk+1.
Itlookslikewedidntmakeanythingwiththisoptimization.Evenifwecalculateformlines,
eachlinecanstillhave10^9reachablepositions.Soworstcaseweperform10^14
operations.Weneedsomethingbetterformanaginginformationfromaline.Youcannote
thatforagivenliney,therearealotofpositionshavingconsecutivevalues.Therearealot
ofpositions(x,y)and(x,y+1)bothreachable.Thisshouldgiveusfollowingidea:whatif
insteadofkeepingreachablepositions,wekeepreachableranges?Thatis,foreachlinex
wekeepasetofrangesS={(a,b)|allcells(x,k)witha<=k<=barereachable}.
Howmanyrangescanitbeforaline?Ifthelinecontainsmobstacles,therearem+1
ranges.Supposeforlinexallcellsarereachable,butforlinex+1cells(x+1,3)(x+1,5)
(x+1,N1)areblocked.Then,therangesofreachablecellsare[1,2][4,4],[6,N2]
and[N,N].Bynow,wegetworstcasemlinesandworstcaseeachlinehavingmelements,
soinworstcasewedhavetohandlem*m=10^10events.Thismaystilllooktoomuch,
buthappilythisboundisoverestimated.Ifalinehasoobstacles,therecanbeatmosto+
1ranges.IflinesL1,L2,...,Lkhave{o1,o2,...,ok}obstacles,therellbeatmosto1+o2+
...+ok+kranges.Buto1+o2+...+ok=mandalsokisatmostm(provedabovewhy
wereinterestedinatmostmlines),soinworstcasewegetm+m=2*mranges.Yaay,
finallyadecentnumberofstatesforthisproblem:)
So,weiterateeachlinewereinterestedin.Letsfindsetofrangesforthisline,thinkingthat
allcellsfromlineabovearereachable.Thisiseasytodo.Afterwegetourrangeslikeall
cellsfromabovecanbevisited,letsthinkhowhavingobstaclesabovecaninfluencecurrent
ranges.Afteraddingrangesfromabove,currentrangescantincrease(obviously),theycan
onlydecrease,remainthesameorsomeofthemcanbecomeempty.So,letstakeeach
range[a,b]fromcurrentlineandseehowitwilltransformafteraddingrangesfrom
previousline.
Givenrange[a,b],itcantransformonlyin[a,b]witha>=a.Ifa>b,thenobviouslyrange
isempty.Whysecondnumberofrangekeepsconstant?Letasmallestreachablecolumn
fromcurrentlinewhichisinrange[a,b].Itsenoughtochecka>=a,asifa>b,rangewill
beempty.Itsobviouslywhyweneedtokeepasmallestvaluepossible>=a:were
interestedtokeeprangeasbigaspossibleandaslessaswecutfromleft,asbigitis.Once
wevefoundainrange[a,b](ora>bifrangeisempty)allcells{a+1,a+2,...,b}are
reachableaswellbygoingrightfroma,soifintervalisnotempty,thensecondnumber
definingitremainsb.
Nextquestionishowtofindafastenough.Inorderapointatobereachableoncurrent
range,italsoneedstoexistarangeonpreviouslinecontainingit.Iftherangefrom
previouslineis[pa,pb]thenaneedstofollow3conditions:
aminimalsuchas
pa<=a<=pb
a>=a
Whatifinsteadoffindingawefind[pa,pb]?Thenaismax(pa,a).Inorderatobeas
smallaspossible,sinceaisconstant,paneedstobeassmallaspossible.Sowereducedit
to:
paminimalpb>=a>=a<=>pb>=a
Intervalsfrompreviouslinearedisjoint,no2intervalscrosseachother.Itmeansthatifpb
isminimal,thanpaisminimaltoo(ifweincreasepb,thenpawillincreasetoo,soitwontbe
minimal).Hence,youneedtofindaninterval[pa,pb]suchaspbisminimalandpb>=a.
Then,aismax(a,pa).Thisiseasytodoifwesortallintervalsfrompreviouslineincreasing
bysecondvalue(pb),thenwebinarysearchforvaluea.
Finally,afterrunningalgorithmforalllines,lastrangefromlastlinehassecondnumberN
(assumingrangesaresortedincreasingbysecondvalue),thenthereexistapath,
otherwisetheredoesnotexist.ThisalgorithmshouldrunO(m*logm)worstcase,good
enoughtopass.
Code:http://pastie.org/8651817
384E
Thisiskindoftaskthatneedstobebreakintosmallersubproblemsthatyoucansolve
independently,thenputthemtogetherandgetsolution.
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 11/30
Letsdefinelevelofanodethenumberofedgesinthepathfromroottothenode.Root
(node1)isatlevel0,sonsofrootareatlevel1,sonsofsonsofrootareatlevel2andso
on.
Nowsupposeyouwanttodoanoperationoftype1toanodex.Whatnodesfromsubtree
ofxwillbeadded+val(apositivevalue)?Obviously,xwillbefirst,beinglocatedatlevelL.
Sonsofx,locatedatlevelL+1willbeaddedval.Sonsofsons,locatedatlevelL+2,will
beaddedvalue+valagain.So,nodesfromsubtreeofxlocatedatlevelsL,L+2,L+4,...
willbeaddeda+val,andnodeslocatedatlevelsL+1,L+3,L+5willbeaddedaval.
LetstakethosevaluesofLmodulo2.AllnodeshavingremainderLmodulo2willbeadded
a+val,andnodeshavingreminder(L+1)modulo2willbeaddedval.Inotherwords,fora
fixedx,atalevelL,letyanodefromsubtreeofx,atlevelL2.IfLandL2havesameparity,
+valwillbeaddedtoy.Otherwise,valwillbeaddedtoy.
Fromherewehavetheideatosplitnodesoftreein2setsthosebeinglocatedateven
levelandthosebeinglocatedatoddlevel.Whatstillmakestheproblemhardtosolve?The
factthatwehaveatree.Ifnodesfromasubtreewouldbeacontiguoussequenceinstead
ofsomenodesfromatree,problemwouldbesimpler:theproblemwouldreducetoadd/
subtractvaluestoallelementsofasubarrayandqueryaboutacurrentvalueofanelement
ofarray.So,howcanwetransformtreetoanarray,suchasforanodex,allnodesfrom
subtreeofxtobeasubarrayofarray?
Theanswerisyes.WecandothisbypropertiesofDFSsearch.Beforereadingon,make
surethatyouknowwhatisdiscoverytimeandfinishtimeinaDFSsearch.Letsbuild3
arraysnowdiscover[],representingnodesinorderoftheirdiscovertimes(anodeisas
beforeindiscoverasithasasmalldiscovertime),begin[]=foranode,inwhichtimeitwas
discoveredandend[]=whatslasttimeofadiscoverednodebeforethisnodefinishes.For
asubtreeofx,allnodesinthesubtreearenodesindiscoverfrompositionbegin[x]to
end[x].
Example:supposeyouhavetree151667644243
Discoveris{1,5,6,7,4,2,3}.
beginis{1,6,7,5,2,3,4}.
endis{7,6,7,7,2,7,4}.
Whatssubtreeofnode6?elementsofdiscoverfrompositionbegin[6]toend[6].Inthis
case,from3to7,soelements{6,7,4,2,3}.Youcanseeitscorrectandtakemore
examplesifyouwant:)
Now,wereducedproblemto:youregivenanarrayA.youcanperform2operations:
1/increaseallelementsfromarange[x,y]toavalueval(valcanbenegative,totreat
subtractions)
2/whatscurrentvalueofanelementfrompositionpos.
ThosewhosolvedIahubandXorsfrommylastround,CF198,shouldprobablysaythey
sawsomethingsimilarbefore.Ifyoudidntsolveproblembefore,Iencourageyoutodoit
afteryousolvethisone,itusesasimilarideatowhatwillfollownow.Also,ifyoudontknow
Fenwicktrees,pleasereadthembeforemovingon.Analternativewouldbeforthistask
usingsegmenttreeswithlazyupdate,butIseethisonemorecomplicatedthanneeded.
Illusenowanotsocommonapproachwhendealingwithdatastructures.Insteadof
keepinginanodetheresult,likeyouusuallydo,Illkeepjustanauxiliaryinformation.So
whatalgorithmproposeddoes:
LetAanarray,initiallywithallelements0.
Whenyouneedtoupdaterange[x,y]withvalueval,yousimplydoA[x]+=valandA[y+1]
=val.
Whenyouneedtoansweraqueryaboutpositionpos,yououtputA[1]+A[2]+...+A[pos].
Implementedbruteforce,yougetO(1)perupdateandO(N)perquery.However,these
bothareoperationssupportedbyaFenwicktree,soyoucangetO(logN)peroperation.
Itmaynotbeveryclearwhythisalgorithmworks.Letstakeacloserlook:anupdateneeds
toaddvaluevalonlytorange[x,y].Whenyouqueryapositionpos,letsseeifalgorithm
handlesitcorrectly:
1/pos<x.Inthiscase,resultmustnotbeaffectedbymyupdate.Sincepos<xandIonly
updated2valueswithindices>=x,whendoingA[1]+A[2]+...+A[pos]itwontmatteratall
Ididthatupdateatleastnotforthisquery.
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 12/30
2/x<=pos<=y.Here,forapos,Ineedtoaddvaluevalonlyonce.WeadditonlyatA[x]
inthiswayitwillbecountedonce,anditwillbeconsideredforeachelementsfromrange[x,
y](sinceanelementatpositionpfromrange[x,y]hasp>=x,inA[1]+A[2]+...+A[p]Ill
havetoconsiderA[x]).
3/pos>y.HereIdonthavetoconsiderthequery.Butitwouldbeconsideredwhen
processingA[x].ButifIaddtoA[y+1]valuevalIlljustcancelthevaluepreviouslyadded.
Code(actuallyweusejustoneFenwicktreeinsteadof2,canyouthinkwhyitworks?:)):
http://pastie.org/8651824
383D
Author'ssolution
Theproblemis:givenanarray,iterateallpossiblesubarrays(allpossibleelementssuchas
theirindexesareconsecutive).Now,forafixedsubarrayweneedtoknowinhowmany
wayswecancoloritselementsinblackandwhite,suchassumofblackelementsisequal
tosumofwhiteelements.Theresultissumofthisnumber,foreachsubarray.
Letssolveaneasierproblemfirst.Thiswontimmediatelysolvetheharderversion,butit
willbeusefullater.Supposeyouvefixedasubarray.Inhowmanywayscanyoucoloritwith
blackandwhite?SupposesubarrayhasNelementsandsumofthemisM.Also,suppose
foracoloring,sumofblacksissBandsumofwhitesissW.Forcoloringtobevalid,sB=
sW.ButwealsoknowthatsB+sW=M(becauseeachelementiscoloredbyexactlyone
color).Wegetthat2*sB=M,sosB=M/2.Theproblemisnow:inhowmanywayscan
wecolorelementsinblacksuchassumofblacksisM/2(afterwefixablackcoloring,we
colorwithwhitenoncoloredelementssumofwhitecoloredelementsisalsoM/2).Thisis
awellknownproblem:Knapsackproblem.Letways[i][j]=inhowmanywaysonecanobtain
sumjfromfirstielements.Whenadding(i+1)object,afterways[i]iscalculated,forafixed
sumjwecando2things:add(i+1)objecttosumjorskipit.Dependingofwhatwe
chosen,weaddvalueways[i][j]toways[i+1][j+value[i+1]]ortoways[i+1][j].Theresultis
inways[N][M/2].ThisworksinO(N*M)time.
Animmediatesolutioncanbeobtainednow:takeallsubarraysandapplyaboveapproach.
ThisleadstoanO(N^2*M^2)solution,whichistoomuch.Onecanreducecomplexityto
O(N^2*M)bynotingthatprocessingsubarray[i,j]canbedonewithalreadycalculated
valuesforsubarray[i,j1].Hence,insteadofaddingNelements,itsenoughtoadd1
elementtoalreadycalculatedvalues(elementfrompositionj).Sadly,O(N^2*M)isstilltoo
slow,soweneedtofindsomethingbetter.Thesolutionpresentedbelowwilllookforcedif
youdidntsolvesomeproblemswiththistechniquebefore.Itshardtocomewithan
approachwithoutpracticingthiskindoftasks.Butdontworry,asmuchasyoupractice
them,aseasilyyoullsolvethoseproblems.
Wellsolvetaskbydivideandconquer.ComplexityofthissolutionisO(N*M*logN).Let
f(left,right)afunctionthatcountsnumberofcoloringsforeachsubarray[i,j],suchas
subarray[i,j]isincludedinsubarray[left,right](left<=i<=j<=right).Answerisinf(1,N).
Thetrickistodefineavaluemed=(left+right)/2(veryfrequenttrickindivideandconquer
problems,calledusuallyamedian).Wecannextclassify[i,j]subarraysin3types:
1/i<=medj<=med
2/i>medj>med
3/i<=medj>med
Wecansolve1/and2/bycallingf(left,med)andf(med+1,right).Theremainedproblemis
wheni<=medandj>med.Ifwesolve3/inO((rightleft)*M)time,thiswillbeenoughto
overallachieveO(N*M*logN)(forthismomenttrustme,youllseelaterwhyitsso:)).
Letsdenotebyi1lasti1elementsfromsubarray[left,med].Also,letsnotebyi2firsti2
elementsfromsubarray[med+1,right].Forexample,letleft=1andright=5,witharray
{1,2,3,4,5}.medis3andfori1=2andi2=1,leftsubarrayis{2,3}andrightsubarray
is{4}.Byiteratingi1from1tomedleft+1andi2from1torightmedandthenunite
subarraysi1andi2,weobtainallsubarraysdescribedin3/.Letsdenotebyj1sumofa
possibleblackcoloringofi1.Similarly,j2issumofapossibleblackcoloringofi2.
Supposewefixedi1,i2,j1andj2.Whenitsthecoloringvalid?LetSsumofunited
subarraysi1andi2(S=value[medi1+1]+value[medi1+2]+...+value[med]+
value[med+1]+...+value[med+i21]+value[med+i2]).NowitstimetousewhatI
explainedatthebeginningofsolution.Thecoloringisgoodonlywhenj1+j2=S/2.We
canrewritetherelationas2*(j1+j2)=sum_of_elements_from_i1+
sum_of_elements_from_i2.Wecanrewriteitevenmore:
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 13/30
2*j1+2*j2sum_of_elements_from_i1sum_of_elements_from_i2=0
2*j1sum_of_elements_from_i1=sum_of_elements_from_i22*j2=
combination_value
Thisrelationisthekeyofsolvingproblem.Youcanseenowthatrelationisindependentin
leftandrightside.Wecalculateleft[i1][j1]andright[i2][j2]=inhowmanywayscanI
obtainsumofblacksj1(j2)fromfirsti1(i2)fromleft(right)side.Letscalculatealso
count[value]=inhowmanywayscanIobtaincombination_valueequaltovalueintheright
side.Forsomefixed(i2,j2)Iaddtocount[sum_of_elements_from_i22*j2]valueright[i2]
[j2].Inthiswaycount[]iscalculatedcorrectlyandcompletely.Now,letsfixasum(i1,j1)in
theleftside.Wereinterestedhowmanygoodcoloringsaresuchasthereexistacoloringof
j1ini1elements(theendpointofleftisfixedtobei1andIneedtocalculateendpointsi2
forright,thentomakecoloringsofi2).Acoloringisgoodifcombination_valueof(i1,j1)and
(i2,j2)isequal.Hence,IneedtoknowinhowmanywaysIcancolori1elementstoobtain
sumj1andalsoIneedtoknowinhowmanywaysIcancolorelementsfromrighttoobtain
samecombination_valueasitsintheleft.Itsnothardtoseethatanswerforafixed(i1,j1)
isleft[i1][j1]*count[2*j1sum_of_elements_from_i1].ThistakesO((rightleft)*M)time.
TheonlythingremainedintheproblemistoseewhycomplexityisO(N*M*logN).Wecan
assumeNisapowerof2(itnot,letsroundNtosmallestpowerof2biggerthanN
complexityforNisatleastasgoodascomplexityforthisnumber).Drawabinarycomplete
treewithNnodes.Eachnodecorrespondstoanappealoff().Foralevel,exactlyO(N*M)
operationsareperformed.Toseewhy:
Forlevel1,therellbe1nodeperformingN*Moperations.
Forlevel2,therellbe2nodesperforming(N/2)*Moperations.SummingupwegetO(N*
M).
Forlevel3,therellbe4nodesperforming(N/4)*Moperations.SummingupwegetO(N
*M)aswell.
andsoon.
SoforeachlevelweperformO(N*M)operations.Abinarycompletetreehasmaximum
O(logN)levels,sooverallcomplexityisO(N*M*logN).
Code:http://pastie.org/8651826
Solutionfountbycontestants
Thiswastotallyunexpectedtous:)Goodjobfindingit,youguysarereallysmart.
Weobservethatxunitsofantimatteristhesamethingasxunitsofmatter.Thenwecan
considerthatanelementproduceseitherxorxunitsofmatter.Avalidsubstringisonethat
canhavethesumoftheelements0.Theproblemisreducedtofindinghowmanydifferent
substringscanwehavewithsum0(asubstringisdifferentthananotheroneifithas
differentindices,orifatleastoneelementproducesmatterinoneandantimatterinthe
other).
Thisproblemcanbesolvedwithdynamicprogramming.WewillholdD[i][j]=thenumberof
substringsthatendinelementi,andhavesumj.It'seasytoseethatD[i+1][j]=D[i][jx]
+D[i][j+x],wherexisthevalueofthecurrentelement(wecanputeitherxorx).Afterwe
finishcomputingallthevaluesforcurrenti,weaddtothesolutionD[i][0](howmanyvalid
substringsdowehave).Afterthat,weadd1toD[i][0],meaningthatthereisanempty
substringstartingatpositioni(however,wedon'tneedtoaddittotheanswer).
Foracode,checkpassingsubmissionsduringcontest.
383E
Author'ssolution
Let'siterateoverallpossiblevowelsets.Foragivenset{x1,x2,...,xk}we'reinterestedin
numberofcorrectwordsfromdictionary.Afteraprecalculation,wecandoitinO(k).
Supposeourcurrentvowelsetis{x1,x2,...,xk}.Howmanywordsarecoveredbythe
currentvowels?Bydefinition,wesayawordiscoveredbyasetofvowelsifatleastoneof
3lettersofwordisinvowelset.Wecancalculatethisnumberusingprincipleofinclusion
andexclusion.Welldenoteby|v1,v2,v3,...|=numberofwordscontainingALLofvowels
v1,v2,v3,....Usingprincipleofinclusionandexclusionweget:
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 14/30
number_of_words_covered=|x1|+|x2|+..+|xk||x1,x2||x1,x3|....+|x1,x2,x3|
+|x1,x2,x4|+....+|xk2,xk1,xk|.Thisformulaissimplyareformulationofprincipleof
inclusionandexclusion.Youcaneasilyobservethat|v1,v2,...,vk|makessenseonlywhen
kisatmost3,asnowordfrominputcancontain4ormoreletters(andhencecantcontain
4ormorevowels).
Example:
Supposewordsareabc,abdandbcd.
|a|=2(first2wordsbothcontaincharactera).
|a,b|=2(aswell,first2wordscontaincharactersaandb).
|b|=3(all3wordscontaincharacterb).
|a,b,d|=1(onlysecondwordcontainsall3characters).
Also,notehowprincipleofinclusionandexclusionworks.numberofwordscoveredfor
vowels{a,b}is|a|+|b||a,b|=2+32.Indeed,answeris3.
Wedivideourproblemin3subproblems.Firstone,foravowelset,computesumof|a|,
whereaisaletterfromsubset.Second,computesumof|a,b|,wherebothaandbare
lettersfromset.Third,computesumof|a,b,c|,wherea,b,carelettersfromset.Asstated,
theanswerisnumber_from_1st_step+number_from_3rd_stepnumber_from_2nd_step.
Ifyoufollowedme,youllseethatwewanttocomputeresultsforeachsubproblemin
O(queryLetters).
FirstsubproblemcanbesolvedtriviallyinO(queryLetters).Letarraysingle[],withfollowing
meaning:single[c]ishowmanywordscontaincharacterc.Itcanbetriviallyprecomputedin
O(24*N).Notethatifawordcontainstwice/thirdtimesacharacterc,itneedstobe
countedonlyone(e.g.wordabawilladdonly1tosingle[a]).Forcomputeresultofthis
subproblemforagivensetofvowels,Illtakealllettersfromset.Ifletterbelongstoset,I
addtoresultsingle[letter].ThisstepcanbealsobesolvedinO(1),buttheresnoneed,
sinceothersubproblemsallowonlyanO(queryLetters)solution.
Forsecondandthirdsubproblemsitsalittlemoredifficult.Illpresentherehowtosolve
secondsubproblemandsomehintsforthirdone(ifyouunderstandsecond,withhintsyou
shouldbeabletosolvethirdonebyyourown).
Similarlytofirststep,Illdefineamatrixdouble[c1][c2]=howmanywordscontainboth
charactersc1andc2.Atriviallysolutionwouldbe,foragivenvowelset,takeall
combinationsoflettersc1andc2thatbelongtosetandaddtoresultvaluedouble[c1][c2].
However,thissolveseachqueryinO(queryLetters^2),whichistooslow.
Note,ifwedhave12letters,insteadof24,thisapproachwouldbefastenough.Fromhere
itcomesaprettyclassicalideainexponentialoptimization:meetinthemiddleattack.We
splitthose24lettersin2groups:first12lettersandlast12letters.Theanswerforasubset
issumofdouble[c1][c2](whenc1andc2belongtocurrentvowelset)when
1/c1andc2belongtofirst12letters
2/c1andc2belongtolast12letters
3/c1belongstofirst12lettersandc2belongstolast12letters
1/and2/canbeimmediatelyprecalculatedasstatedabove,inO(2^12*12^2).Well
rememberresultsforeachhalfusingbitmasksarrays.LetHalf1[mask]=sumover
double[c1][c2],whenc1andc2areinfirst12lettersandcorrespondto1bitsofmask.
Half2[mask]isdefinedsimilarly,butforlast12letters(e.g.subset{a,c,d}correspondsto
bitmask2^0+2^2+2^3=13infirsthalfandsubset{m,n,p}correspondstobitmask2^0+
2^1+2^3=11forsecondhalf).Now,foragivensubset,onecananswerfirst2partsin
O(queryCount)worstcase(readinputforaqueryandconvertittobitmasks).
Howtoanswer3?Withanotherprecalculation,ofcourse.Weknowc1letterneedstobein
first12lettersandc2needstobeinlast12letters.Theprecalculationwedohereis:
mixed_half[mask][i]=sumover|c1,c2|,whenc1belongstofirsthalfandisa1bitofmask
andc2isithcharacterofsecondhalf.Hence,foraquery,wecanfixcharacterfromsecond
half(c2,byiterationofquerylettersfromsecondhalf)andknowsumsof|c1,c2|betweenit
andallavailablecharactersfromfirsthalfafterwedothisprecalculation.Also,
precalculationisdonetriviallyinO(2^12*12^2):fixmask,fixiandtheniterateover1bits
frommaskandadddouble[c1][c2].
Thirdsubproblemisleft,butitcanbedonesimilarlytosecondone.Insteadofdouble[c1]
[c2],wellhavetriple[c1][c2][c3]=howmanywordscontainall3charactersc1,c2andc3?
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 15/30
Wealsodomeetinthemiddlehere,dividethose24lettersinto2setsof12letters.We
have4cases:
1/c1,c2,c3belongtofirsthalf
2/c1,c2,c3belongtosecondhalf
3/c1,c2belongtofirsthalfandc3tosecondhalf
4/c1belongstofirsthalfandc2,c3tosecondhalf
1/and2/aredonebruteforce,likeinsecondsubproblem(theonlydifferenceiswechoose
3charactersinsteadof2,havingcomplexityO(2^12*12^3)).For3/and4/wealso
precompute2matrixes:
mixed_two_one[mask][i]=c1andc2belongtomaskfromfirsthalfandc3isithcharacter
fromsecondhalf
and
mixed_one_two[mask][i]=c1isithcharacterfromfirsthalfandc2,c3belongtomaskfrom
secondhalf.
ThosecanalsobecalculatedinO(2^12*12^3).
SoprecalculationpartisO(2^12*12^3)=7077888operations.
Forcalculateansweringqueriescomplexity,takeallnumbersfrom0to2^241andsum
theirbitcount.Thisisawellknownproblem,thesumis0*C(24,0)+1*C(24,1)+...+24
*C(24,24)=201326592.Intotalweget208404480operations.C++sourcemakesthemin
2seconds.
Code:http://pastie.org/8651829
Solutionfountbycontestants
LikeinD1Dtask,officialsolutionwasovercomplicated.Thissolutionismoresimpleto
understand,codeandit'smoreelegant.Ifsomeonewantstocomplicatehislife,(s)hecan
codealsoofficialsolution:)
Let'sstartbyassigningabitmasktoeachwordinfollowingway:ithbitis1ifandonlyif
letter('a'+i)appearsinthecurrentword.Forexample,forwordacd,itsbitmaskis2^0+
2^2+2^3=13andforwordaabitsbitmaskis2^0+2^1=3.Afterreadingthewordsfrom
dictionary,westoreamatrixcnt[mask]=howmanywordsfromdictionarycorrespondto
mask?
Weiteratebitmasksfrom0to2^241,thistimecorrespondingtoeachpossiblequestion
ofIahubina.Let'sfocusonabitmaskX.Weneedtogetsumofcnt[mask],whenmaskand
Xshareatleastonecommonbithavingvalue1(formally(XANDmask)>0).Inordertodo
this,weneedareductionwhichmaybenotsoobvious.
Whatifinsteadofcountingallwordscontainingatleastoneofvowels{w1,w2,...,wk}we
countallwordswhichdon'tcontainANYofvowels{w1,w2,...,wk}?Supposethisnumberis
ret.Then,allwordscontainingatleastoneofvowelsisNret.Fromallwords,weerase
thosewordswhichdonotcontainanyvowelsfromset{w1,w2,...,wk}(andwhichobviously
arewrongwords).Obviously,it'sleftonlywordscontainingatleastonevowel,sogood
words.Now,forawordnottocontainanyofvowels{w1,w2,...,wk}itneedstocontains
ONLYvowelsfromset{"a","b","c",...,"x"}\{w1,w2,...,wk}(setofallowedlettersfrom
whichweerasedvowelsw1,w2,...,wk}.
Andthisisreductionweneeded.ForabitmaskXweneedtocalculatesumofcnt[mask],
wheremaskisasubsetofX(wecansetsomebitsfromXfrom1to0inordertoobtain
mask).Foramask,let'skeepthissuminres[mask].Wecancalculateresarrayusingdivide
andconquer.
Let'smakeafunctionsolve(left,right),whichcompletesarrayresinthewaydescribed
above,ifweconsideronlyelementscnt[k]withleft<=k<right(forsimplicity,I'llconsider
elementswhichdonotlieinthisrangetobeequalto0).Nowweneedtosolveforarange
[left,right].Let'shaveinres1[]=solve(left,med)andinres2[]=solve(med,right),where
med=(left+right)/2.Weneedtoputtogetherres1[]andres2[]inordertoobtainres[].
for(inti=lefti<med++i)res[i]=res1[i]
Numbersin[left,med]havemostsignificantbitequalto0.Wecanonlykeepit0andadd
whatwecalculatedbefore.Wecan'taddanyelementfromres2[],becausethoseelements
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 16/30
havemostsignificantbitequalto1andwe'renotallowedtochangebit0intobit1.
for(inti=medi<right++i)res[i]=res1[imed]+res2[i]
Here,mostsignificantbitis1.Addingres1[]correspondstochangingbitfrom1to0,adding
res2[]correspondstoleavingbit1.
Ofcourse,weneedtothreatthebasecasehere,too.Whenleft+1=right,res[left]=
cnt[left].Wecankeeponlyonearrayres[]insteadof3,Iexplaineditthiswayonlyfor
simplicity.Also,thereisnoneedforkeepingseparatearraysforres[]andcnt[],onecan
solvealltaskwithonlyonearray.Inordertogetres[],wesimplycallsolve(0,2^24).
ComplexityofsolutionisO(2^24*24).Ileavetheproofhomework,it'salmostidenticalto
complexityproofofD1D"Authorsolution"(thatwithbuildingabinarytree).
Forareferencesolution,checkEndagorion'sACsourceduringcontest.
Readmore
TutorialofCodeforcesRound#225(Div.2)
codeforces, 225, editorial
CodeforcesRound#225
Helloeveryone!
WeinviteyoutoparticipateatCodeforcesRound#225,scheduledMonday,20thJanuaryat
7:30PMMSK.ThisisthethirdroundIcoauthor,alongwithCodeforcesRound#198(Div.1)
(andofcourseDiv.2versionofcontest)andCodeforcesRound#191(Div.2).
Ifyourecallmyoldrounds,you'llseethatmaincharacterisIahub.Theotherwriterofthis
roundis...Iahub...therealpersoncorrespondingto"Iahub"character.Letmeintroduceyou
toRaresBuhai(rares.buhai).He'stheauthorofDiv.2C/Div.1A,Div.1DandDiv.1E.
Youcanexpectthoseproblemstobeinteresting,comingfroma2timesIOIgoldmedalist
(beingallowedtoparticipate2moretimes).Allotherproblemsarecreatedbyme.Ilike
them,butIwouldn'tbeobjectiveifIsaidthatthey'reinteresting.Let'sseeifsomeonewill
thinksoafterthecontest:)
Likelasttime,I'llgiveyoualittlespoileraboutthetasks.Wetriedtomaketheproblemset
asvariedaspossible.Inordertogetagoodrank,oneneedstobegoodat"adhoc"
problemsaswellashavegoodalgorithmicknowledge.
Asalways,thankstoMikeMirzayanovforCodeforcesplatform,toDelinurfortranslating
tasks,toGeraldforhelpinguspreparetheroundandtoDamianSandll931110fortesting
it.
Wewisheveryonehighratingandtohavefun!
UPDScoredistribution:
Division1:5001500150020002500
Division2:5001000150025002500
UPDContestisover!Thanksforeveryonewhoparticipated!Ineedtosaywe'reimpressed
ofyourcreativeandtotallyunexpectedsolutionsforDivision1D.
Div.1winners:
1. yeputons
2. Arcueid
3. Dmitry_Egorov
4. ACMonster
5. scott_wu
Div.2winners:
1. sick_coder
2. akaring
3. c0d3junki3
+418
elfus0 4monthsago 37


Byelfus0,5monthsago, ,
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 17/30
4. raihatneloy1992
5. sky0917
UPDEditorial
Readmore
AnnouncementofCodeforcesRound#225(Div.1)
AnnouncementofCodeforcesRound#225(Div.2)
codeforces, round, 225
CodeforcesRound#198Editorial
340A
Youaregivenarange[A,B].You'reaskedtocomputefasthowmanynumbersinthe
rangearedivisiblebybothxandy.I'llpresenthereanO(log(max(x,y))solution.We
madetestslowsoothernotoptimalsolutionstopassaswell.Thesolutionreferstothe
originalproblem,wherex,y10 .
Firstly,wecansimplifytheproblem.Supposewecancalculatehowmanynumbersare
divisibleinrange[1,X]bybothxandy.Canthissolveourtask?Theanswerisyes.All
numbersinrange[1,B]divisiblebybothnumbersshouldbecounted,exceptthenumbers
lowerthanA(1,2,...,A1).But,asyoucansee,numberslowerthanAdivisiblebyboth
numbersareactuallynumbersfromrange[1,A1].Sotheanswerofourtaskisf(B)
f(A1),wheref(X)ishowmanynumbersfrom1,2,...,Xaredivisiblebybothxandy.
ForcalculateinO(log(max(x,y))thef(X)weneedsomemath.Ifyoudon'tknowaboutit,
pleasereadfirstlyaboutleastcommonmultiple.Now,whatwillbethelowestnumber
divisiblebybothxandy.Theanswerisleastcommonmultipleofxandy.Let'snoteitby
M.ThesequenceofthenumbersdivisiblebybothxandyisM,2*M,3*Mandsoon.
Asaproof,supposeanumberzisdivisiblebybothxandy,butitisnotintheabove
sequence.Ifanumberisdivisiblebybothxandy,itwillbedivisiblebyMalso.Ifanumber
isdivisiblebyM,itwillbeintheabovesequence.Hence,theonlywayanumbertobe
divisiblebybothxandyistobeinsequenceM,2*M,3*M,...
Thef(X)calculationreducestofindingthenumberofnumbersfromsequenceM,2*M,3
*M,...lowerorequalthanX.It'sobviousthatifanumberh*MisgreaterthanX,sowillbe
(h+1)*M,(h+2)*Mandsoon.Weactuallyneedtofindthegreatestintegernumberh
suchash*MX.Thenumberswe'relookingforwillbe1*M,2*M,...,h*M(so
theircountwillbeh).Thenumberhisactually[X/M],where[number]denotestheinteger
partof[number].Takesomeexamplesonpaper,you'llseewhyit'strue.
TheonlythingnotdiscussedishowtocalculatethenumberMgiven2numberxandy.You
canusethisformulaM=x*y/gcd(x,y).Forcalculategcd(x,y)youcanuseEuclid's
algorithm.ItscomplexityisO(log(max(x,y)),sothisistherunningtimefortheentire
algorithm.
Officialsolution:4383403
340B

Iwanttoapologizefornotestimatingtherealdifficultyofthistask.Itturnsoutthatitwas
morecomplicatedthanwethoughtitmightbe.Let'sstartexplanation.
Beforereadingthis,youneedtoknowwhatissignedareaofatriangle(alsocalledcross
productorccwfunction).Withoutit,thisexplanationwillmakenosense.
Thefirstthingwenoteisthataquadrilateralselfintersectingwon'thavemaximumarea.I'll
showyouthisbyanimagemadebymy"talents"inPaint:)Asyoucansee,ifaquadrilateral
selfintersects,itcanbetransformedintoonewithgreaterarea.
+353
elfus0 5monthsago 137


Byelfus0,9monthsago, ,
9
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 18/30
Eachquadrilateralhas2diagonals:connecting1stand3rdpointandconnecting2ndand
4thpoint.Adiagonaldividesaplaneinto2subplanes.SupposediagonalisAB.ApointX
canbeinoneofthosetwosubplanes:thatmakingcrossproductpositiveandthatmaking
crossproductnegative.Apointisin"positive"subplaneifccw(X,A,B)>0andin"negative"
subplaneccw(X,A,B)<0.Notethataccordingtotheconstraintsofthetask,ccw(X,A,B)
willneverbe0.
Let'smakenowthekeyobservationofthetask.Wehaveaquadrilateral.SupposeABis
oneofdiagonalsandCandDtheotherpointsfromquadrilateraldifferentbyAandB.Ifthe
currentquadrilateralcouldhavemaximalarea,thenoneofpointsfromCandDneedstobe
in"positivesubplane"ofABandtheotheronein"negativesubplane".Whatwouldhappenif
CandDwillbeinthesamesubplaneofAB?Thequadrilateralwillselfintersect.Ifitwillself
intersect,itwon'thavemaximalarea."Apictureisworthathousandwords"thiscouldn't
fitbetterinthiscase:)NotethatthequadrilateralfromthebelowimageisACBDA.
Outtaskreducestofixadiagonal(thistakingO(N^2)time)andthenchooseonepoint
fromthepositiveandthenegativesubplaneofthediagonal.I'llsayherehowtochoosethe
pointfromthepositivesubplane.Thatfromnegativesubplanecanbechosenidentically.
Thediagonaland3rdpointchosenformatriangle.Aswewantquadrilateraltohave
maximalarea,weneedtochoose3rdpointsuchastrianglemakesthemaximalarea.As
thepositiveandnegativesubplanesaredisjoint,thechoosing3rdpointfromeachofthem
canbemadeindependently.HencewegetO(N^3)complexity.Atrickycaseiswhenyou
chooseadiagonalbutoneofthesubplanesisempty.Inthiscaseyouhavetodisregardthe
diagonalandmovetothenextone.
Officialsolution:4383413
340C
Despitethisisamathtask,theonlymathformulawe'lluseisthatnumberofpermutations
withnelementsisn!.Fromthisone,wecandeducethewholetask.
Theaverageformulaissum_of_all_routes/number_of_routes.Aseachrouteisa
permutationwithnelements,number_of_routesisn!.Nextsupposeyouhavea
permutationofa:p1,p2,,pn.Thesumforitwillbep1+|p2p1|++|pnpn1|.The
sumofrouteswillbethesumforeachpossiblepermutation.
Wecancalculatesum_of_allroutesintwosteps:firsttimewecalculatesumslikep1and
thenwecalculatesumslike|p2p1|++|pnpn1|foreveryexistingpermutation.
FirststepEachelementofa ,a ,,a canappearonthefirstpositionontheroutesand
needstobeaddedasmuchasitappears.SupposeIfixedanelementXforthefirst
position.Icanfillpositions2,3,..,n1in(n1)!ways.Why?Itisequivalenttopermuting
n1elements(allelementsexceptX).Sosum_of_all=a *(n1)!+a *(n1)!+*a
*(n1)!=(n1)!*(a +a ++a ).
SecondstepForeachpermutation,foreachpositionjbetween1andn1weneedto
compute|p p(j+1)|.Similarlytofirststep,weobservethatonlyelementsfromacan
appearonconsecutivepositions.Wefix2indicesiandj.Wereinterestedinhowmany
permutationsdoa appearbeforea .Wefixksuchasonapermutationp,a appearson
1 2 n
1 2 n
1 2 n
j
i j i
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 19/30
positionkanda appearsonapositionk+1.Inhowmanywayscanwefixthis?n1ways
(1,2,,n1).Whatsleft?Asequenceof(n2)elementswhichcanbepermuted
independently.Sothesumofsecondstepis|a a |*(n1)*(n2)!,foreachi!=j.IfI
note(a +a ++a )byS1and|a a |foreachi!=jbyS2,theansweris(N1)!*S1
+(N1)!*S2/N!.Byasimplification,theansweris(S1+S2)/N.
TheonlyproblemremainedishowtocalculateS2.Simpleiterationwontenterintimelimit.
Letsthinkdifferent.Foreachelement,Ineedtomakesumofdifferencesbetweenitandall
smallerelementsinthearraya.Aswell,Ineedtomakesumofalldifferentbetweenbigger
elementsthanitandit.Illfocusonthefirstpart.Isortincreasingarraya.SupposeImat
positioni.Iknowthat(i1)elementsaresmallerthana .Thedifferenceissimply(i1)*
a sum_of_elements_before_position_i.Sumofelementsbeforepositionicanbe
computedwheniteratingi.LetscalltheobtainedsumSleft.Ineedtocalculatenowsumof
alldifferencesbetweenanelementandbiggerelementsthanit.ThissumisequaltoSleft.
Asaproof,foranelementa ,calculatingthedifferencea a whena >a isequivalent
tocalculatingdifferencesbetweena andasmallerelementofit(inthiscasea ).Thatswhy
Sleft=Sright.
Asaconclusion,theansweris(S1+2*Sleft)/N.Formakefractionirreducible,youcan
useEuclid'salgorithm.ThecomplexityofthepresentedalgorithmisO(N*logN),
necessarydueofsorting.Sortingcanbeimplementedbycountsortaswell,havinga
complexityofO(maximalValue),butthisisnotnecessary.
Officialsolution:4383420
340D
Agoodwaytoapproachthisproblemistonoticethatyoucan'tbuildthegraph.Inworst
case,thegraphwillbebuiltinO(N )complexity,whichwilltimeout.Also,noticethat
"maximalindependentset"isaNPHardtask,soevenifyoucanbuildthegraphyoucan't
continuefromthere.So,thecorrectroutetostartistothinkofgraph'spropertiesinsteadof
buildingit.Aftersketchingalittleonthepaper,youshouldfindthisproperty:
Lemma1Supposewechoose2indicesiandj,suchasi<j.We'llhaveanedgeonthe
graphbetweenverticesa anda ifandonlyifa >a .We'llcallthatiandjforman
inversioninthepermutation.
ProofWeassumeweknowtheproofthatbubblesortdoessortcorrectlyanarray.Toproof
lemma1,weneedtoshowtwothings.
1. Everyinversionwillbeswappedbybubblesort.
2. Foreachi<jwhena <a ,bubblesortwillNOTswapthiselements.
Toproof1,ifbubblesortwouldn'tswapaninversion,thesequencewouldn'tbesorted.But
weknowthatbubblesortalwayssortsasequence,soallinversionswillbeswapped.
Proofing2istrivial,justbylookingatthecode.
Sofarwe'vegothowthegraphGisconstructed.Let'sapplyitinmaximalindependentset
problem.
Lemma2AmaximalindependentsetofgraphGisalongestincreasingsequencefor
permutationa.
Proof:Supposewehaveasetofindicesi1<i2<...iksuchasa ,a ,...,a forman
independentset.Then,anyhowwe'dchoosedande,therewon'texistanedgebetween
a anda .Accordingtoproof1,thisonlyhappenswhena <a .Hence,anindependent
setwillbeequivalenttoanincreasingsequenceofpermutationa.Themaximal
independentsetissimplythemaximalincreasingsequenceofpermutationa.
Thetaskreducestofindlongestincreasingsequenceforpermutationa.Thisisaclassical
problemwhichcanbesolvedinO(N*logN).Hereisaninterestingdiscussionabouthow
todoit.
340E
Inthistask,author'sintendedsolutionisanO(N^2)dp.However,duringtestingGerald
fountasolutionusingprincipleofinclusionandexclusion.We'vethoughttokeepboth
solutions.We'resorryifyousaytheproblemwaswellknown,butforbothmeandthe
authorofthetask,itwasfirsttimewesawit.
Dynamicprogrammingsolution
i j i
j
i j
1 2 n i j
i
i
i j i j i
j i
2
i j i j
i j
i1 i2 ik
id ie id ie
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 20/30
Afterreadingthesequence,wecanfindwhichelementsaredeleted.Supposewehaveina
setDalldeletedelements.I'lldefinefromnowona"freeposition"apositionwhichhas1
value,soitneedstobecompletedwithadeletedelement.
WeobservethatsomeelementsfromDcanappearonallfreepositionsofpermutation
withoutcreatingafixedpoint.TheotherelementsfromDcanappearinallfreepositions
exceptone,thatwillcreatethefixedpoint.It'sintuitivethatthosetwo"classes"don't
influenceinthesamewaytheresult,sotheyneedtobetreatedseparated.
Sofromherewecangetthedpstate.Letdp(n,k)=inhowmanywayscanIfill(n+k)free
positions,suchasnelementsfromDcanbeplacedanywhereinthefreepositionandthe
otherkelementscanbeplacedinallfreepositionsexceptone,whichwillcreatethefixed
point.Aswe'llprovebytherecurrences,wearenotinterestedofthevaluesfromelements
ofD.Instead,we'llinterestedintheirproperty:iftheycan(not)appearinallfreepositions.
Ifk=0,theproblembecomesstraightforward.Theanswerfordp(n,0)willben!,aseach
permutationof(n+0)=nnumbersisvalid,becauseallnumberscanappearonallfree
positions.Wecanalsocalculatedp(n,1).Thismeanswearenotallowedtoplacean
elementinapositionoutof(n+1)freepositions.However,wecanplaceitintheothern
positions.Fromnowwegetnelementswhichcanbeplacedanywhereinthenfree
positionsleft.Hence,dp(n,1)=n!*n.
Wewanttocalculatedp(n,k)now,k>1.Ourgoalistoreducethenumberk,untilfind
somethingweknowhowtocalculate.Thatis,whenkbecomes0or1problemissolved.
Otherwise,wewanttoreducetheproblemtoaproblemwhenkbecomes0or1.Ihavetwo
cases.Inafirstcase,Itakeanumberfromnumberswhichcanbeplacedanywherein
ordertoreducethenumberswhichcanformfixedpoints.Inthesecondcase,Itakea
numberfromthosewhichcanformfixedpointsinordertomakethesamegoalasinthe
firstcase.Let'sanalyzethem.
Case1.SupposeXisthefirstfreeposition,suchasinthesetofknumbersthereexistone
whichcannotbeplacedthere(becauseitwillmakeafixedpoint).Obviously,thisposition
exist,otherwisek=0.Alsoobviously,thispositionwillneedtobecompletedwithaterm
whenhavingasolution.Inthiscase,IcompletepositionXwithoneofnnumbers.Thiswill
makenumberequaltoXfromtheknumberssettobecomeanumberwhichcanbeplaced
anywhere.SoI"loose"onenumberwhichcanbeplacedanywhere,butIalso"gain"one.As
well,Ilooseonenumberwhichcanformafixedpoint.
Hencedp(n,k)+=n*dp(n,k1).
Case2.InthiscasepositionXwillbecompletedwithonenumberfromtheknumbersset.
Allnumberswhichcanformfixedpointscanappearthere,exceptnumberhavingvalue
equaltoX.Sotherearek1ofthem.IchooseanarbitrarynumberYfromthosek1to
placeonthepositionX.ThistimeI"loose"twonumberswhichcouldformfixedpoints:X
andY.Aswell,I"gain"onenumberwhichcanbeplacedanywhere:X.
Hencedp(n,k)+=(k1)*dp(n+1,k2).
TLDR
dp[N][0]=N!
dp[N][1]=N*dp[N][0]
dp[N][K]=N*dp[N][K1]+(K1)*dp[N+1][K2]forK>=2
Thisrecurrencescanbecomputedbyclassicaldporbymemoization.I'llpresent
DamianS'ssource,whichusedmemoization.Asyoucansee,it'sveryshortandeasyto
implement.Link
Inclusionandexclusionprinciple
I'llpresenthereanalternativetothedynamicprogrammingsolution.Let'scalculateintot
thenumberofdeletednumbers.Also,let'scalculateinfixedthemaximalnumberoffixed
pointsapermutationcanhave.Forcalculatefixed,let'siteratewithanindexieach
permutationposition.Wecanhaveafixedpointonpositioniifelementfrompositioniwas
deleted(a =1)andelementidoesnotexistinsequencea.Withotherwords,elementi
wasdeletedandnowIwanttoadditbackonpositionitoobtainmaximalnumberoffixed
points.
Weiteratenowanindexifromfixedto0.Letsol[i]=thenumberofpossiblepermutations
havingexactlyifixedpoints.Obviously,sol[0]istheanswertoourproblem.Let'sintroduce
acombination representinginhowmanywaysIcanchoosekobjectsoutofn.Ihavelist
ofpositionswhichcanbetransformedintofixpoints(theyarefixedpositions).Ineedto
i
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 21/30
chooseiofthem.Accordingtotheabovedefinition,Igetsol[i]= .Next,Ihavetofill
totipositionswithremainedelements.We'llconsiderforthismomentvalideach
permutationofnotusedvalues.So,sol[i]= .Whereistheproblemto
thisformula?
Theproblemisthatit'spossible,whenpermuting(toti)remainedelementstobeadded,
one(ormore)elementstoformmore(new)fixedpoints.ButifsomehowIcanexclude
(subtract)thewrongchoicesfromsol[i],sol[i]willbecalculatedcorrectly.Iiterateanother
indexjfromi+1tofixed.Foreachj,I'llcalculatehowmanypermutationsIconsideredin
sol[i]havingifixedpointsbutactuallytheyhavej.I'llsubtractfromsol[i]thisvalue
calculatedforeachj.IfIdothis,obviouslysol[i]willbecalculatedcorrectly.
Supposewefixedaj.Weknowthatexactlysol[j]permutationshavejfixedpoints(asj>i,
thisvalueiscalculatedcorrectly).SupposenowIfixapermutationhavingjfixedpoints.For
getthefullresult,Ineedtocalculateforallsol[j]permutations.Happily,Icanmultiplyresult
obtainedforasinglepermutationwithsol[j]andobtaintheresultforallpermutationshaving
jfixedpoints.Soyouhaveapermutationhavingjfixedpoints.Theproblemreducesto
choosingiobjectsfromatotalofj.Why?Thoseiobjectschosenareactuallythepositions
consideredinsol[i]tobeoneshavingexactlyifixedpoints.Butpermutationhasjfixed
points.Quotingforabove,"Foreachj,I'llcalculatehowmanypermutationsIconsideredin
sol[i]havingifixedpointsbutactuallytheyhavej".Thisisexactlywhatalgorithmdoes.
Tosumupina"LaTeX"way,
WecancomputebinomialcoefficientsusingPascal'striangle.Usinginclusionandexclusion
principle,wegetO(N ).PleasenotethatthereexistanO(N)solutionforthistask,using
inclusionandexclusionprinciple,butit'snotnecessarytogetAC.I'lluploadGerald'ssource
here.
341DXor'
Themotivationoftheproblemisthatx^x=0.x^x^x^x(eventimes)=0
Updateperrange,queryperelement
Whendealingwithcomplicatedproblems,it'ssometimesagoodideatotrysolvingeasier
versionsofthem.Supposeyoucanqueryonlyoneelementeachtime(x0=x1,y0=y1).
Toupdateasubmatrix(x0,y0,x1,y1),Illdofollowingoperations.A[x0][y0]^=val.A[x0][y1
+1]^=val.A[x1+1][y0]^=val.A[x1+1][y1+1]^=val.
Toqueryaboutanelement(X,Y),thatelementsvaluewillbethexorsumofsubmatrixA(1,
1,X,Y).Letstakeanexample.Ihavea6x6matrixandIwanttoxorallelementsfrom
submatrix(2,2,3,4)withavalue.Thebelowimageshouldbeexplanatoryhowthemethod
works:
Next,by(1,1,X,Y)Illdenotexorsumforthissubmatrix.
Whitecellsarenotinfluencedby(2,2,3,4)matrix,asmatrix(1,1,X,Y)with(X,Y)a
whitecellwillneverintersectit.Redcellsarefromthesubmatrix,theonesthatneedtobe
xored.Notethatforaredcell,(1,1,X,Y)willcontainthevalueweneedtoxor(asitwill
contain(2,2)).Next,bluecells.Forthisones(1,1,X,Y)willcontainthevaluewexorwith,
despitetheyshouldnthaveit.Thisiswhyboth(2,5)and(4,2)willbexoredagainbythat
value,tocancelthexorof(2,2).Nowitsokay,everybluecelldonotcontainthexorvalue
intheir(1,1,X,Y).Finally,thegreencells.Theseonesareintersectionbetweenthe2
bluerectangles.Thismeans,intheir(1,1,X,Y)thevaluewexorwithappears3times(this
meansitiscontained1time).Forcancelthis,wexor(4,5)withthevalue.Nowforevery
2
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 22/30
greencell(1,1,X,Y)contains4equalvalues,whichcanceleachother.
Youneedadatastructuredotothefollowing2operations:
Updateanelement(X,Y)(xoritwithavalue).
Queryaboutxorsumof(1,1,X,Y).
BothoperationscanbesupportedbyaFenwicktree2D.Ifyoudon'tknowthisdata
structure,learnitandcomebacktothisproblemafteryoudothis.
Comingbacktoourproblem
Now,insteadoffindinganelement,Iwantxorsumofasubmatrix.Youcannotethatxor
sumof(x0,y0,x1,y1)is(1,1,x1,y1)^(1,1,x01,y1)^(1,1,x1,y01)^(1,1,x01,
y01).Thisisaclassicalproblem,theansweris(1,1,x1,y1)fromwhichIexcludewhatis
notinthematrix:(1,1,x01,y1)and(1,1,x1,y01).RightnowIexcluded(1,1,x01,
y01)2times,soIneedtoadditonemoretime.
Howtogetthexorsumofsubmatrix(1,1,X,Y)?Inbruteforceapproach,Idtakeall
elements(x,y)with1<=x<=Xand1<=y<=Yandxortheirvalues.Recallthedefinitionof
thepreviousproblem,eachelement(x,y)isthexorsumofA(1,1,x,y).Sotheansweris
xorsumofallxorsumsofA(1,1,x,y),with1<=x<=Xand1<=y<=Y.
Wecanrewritethatlongxorsum.AnumberA[x][y]appearsinexactly(Xx+1)*(Yy+
1)termsofxorsum.If(Xx+1)*(Yy+1)isodd,thenthevalueA[x][y]shouldbexor
edtothefinalresultexactlyonce.If(Xx+1)*(Yy+1)iseven,itshouldbeignored.
Below,you'llfind4pictures.TheyarematrixeswithXlinesandYcolumns.Eachpicture
representsacase:(Xodd,Yodd)(Xeven,Yeven)(XevenYodd)(XoddYeven).Can
youobserveanicepattern?Elementscoloredrepresentthoseforwhich(Xx+1)*(Yy
+1)isodd.

Yep,that'sright!Thereare4cases,divingthematrixinto4disjointareas.Whenhavinga
queryofform(1,1,X,Y)youonlyneedspecificelementssharingsameparitywithXandY.
ThismethodworksinO(4*logN*logN)foreachoperationandistheindentedsolution.We
keep4Fenwicktrees2D.Wemadetestssuchassolutionshavingcomplexitygreaterthan
O(4*logN*logN)peroperationtofail.
Hereisourofficialsolution:4383473
341E
KeyobservationSupposeyouhave3boxescontainingA,B,Ccandies(A,B,Callgreater
than0).Then,therewillbealwayspossibletoemptyoneofboxesusingsomemoves.
ProofWecansupposethatA<=B<=C.Weneedsomemovessuchastheminimumfrom
A,B,Cwillbezero.IfwealwayskeepthenumbersinorderA<=B<=C,itsenoughsome
movessuchasA=0.Illcallthisnotation(A,B,C).
Howcanweprovethatalwaysexistsuchmoves?Wecanusereductioadabsurdumto
proveit.Letssuppose,startingfrom(A,B,C)wecangotoastate(A2,B2,C2).We
supposeA2(A2>0)isminimalfromeverystatewecanobtain.SinceA2isminimalnumber
ofcoinsthatcanbeobtainedandA2isnotzero,thestatementisequivalentwithwecant
emptyonechestfromconfiguration(A,B,C).Then,wecanprovethatfrom(A2,B2,C2)we
cangotoastate(A3,B3,C3),whereA3<A2.Obviously,thiscontradictsourassumption
thatA2isminimalofeverypossiblestates.IfA2wouldbeminimal,thentherewontbeany
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 23/30
seriesofmovestoemptyonechest.ButA2isntminimal,hencetherealwaysexistsome
movestoemptyonechest.
Ouralgorithmsofar:
voidemptyOneBox(intA,intB,intC){
ifAis0,thenexitfunction.
Makesomemovessuchastofindanotherstate(A2,B2,C2)withA2<A.
emptyOneBox(A2,B2,C2)
}
Theonlyproblemwhichneedstobeprovennowis:givenaconfiguration(A,B,C)withA>
0,canwefindanotherone(A2,B2,C2)suchasA2<A?Theanswerisalwaysyes,below
Illprovewhy.
Firstly,letsimaginewewanttoconstantlymovecandiesintoabox.Itdoesn'tmatteryet
fromwherecomethecandies,whatmattersiscandiesarriveintothebox.Theboxhas
initiallyXcandies.After1move,itwillhave2*Xcandies.After2moves,itwillhave2*(2*
X)candies=4*Xcandies.Generally,afterKmoves,theboxwillcontain2^K*Xcandies.
WehaveA<B<C(if2numbersareequal,wecanmakeamoveandempty1box).Ifwe
divideBbyA,wegetfrommaththatB=A*q+r.(obviously,alwaysr<A).Whatifwecan
moveexactlyA*qcandiesfromBtoA?Then,ournewstatewouldbe(r,B2,C2).Wehave
nowanumberA2=r,suchasA2<A.
HowcanwemoveexactlyA*qcoins?Letswriteqinbase2.Makingthat,qwillbewritten
asasumofpowersof2.Supposelimisthemaximumnumbersuchas2^lim<=q.Weget
everynumberkfrom0tolim.Foreachk,Ipushintothefirstbox(theboxcontaininginitially
Acandies)acertainnumberofcandies.Asprovenbefore,I'llneedtopush(2^k)*A
candies.Let'stakealookatthekthbitfrombinaryrepresentationofq.Ifkthbitis1,Bwill
bewrittenasfollowing:B=A*(2^k+2^(other_power_1)+2^(other_power_2)+...)+r.
Hence,I'llbeabletomoveA*(2^k)candiesfrom"Bbox"to"Abox".Otherwise,I'llmove
from"Cbox"to"Abox".Itwillbealwayspossibletodothismove,asC>BandIcoulddo
thatmovefromB,too.
Theproposedalgorithmmaylookabstract,solet'stakeanexample.
SupposeA=3,B=905andC=1024.Canwegetlessthan3forthisstate?
B=3*301+2.B=3*(100101101)2+2.
K=0:weneedtomove(2^0)*3coinsintoA.0thbitofqis1,sowecanmovefromBtoA.
A=6,B=3*(100101100)2+2C=1024
K=1:weneedtomove(2^1)*3coinsintoA.Since1thbitofqisalready0,wehaveto
movefromC.
A=12,B=3*(100101100)2+2C=1018
K=2:weneedtomove(2^2)*3coinsintoA.2ndbitofqis1,sowecanmovefromB.
A=24,B=3*(100101000)2+2C=1018
K=3:weneedtomove(2^3)*3coinsintoA.3ndbitofqis1,sowecanmovefromB.
A=48,B=3*(100100000)2+2C=1018
K=4.weneedtomove(2^4)*3coinsintoA.4thbitofqis0,weneedtomovefromC.
A=96,B=3*(100100000)2+2C=970
K=5.weneedtomove(2^5)*3coinsintoA.5thbitofqis1,soweneedtomovefromB.
A=192,B=3*(100000000)2+2C=970
K=6weneedtomove(2^6)*3coinsintoA.WemvethemfromC.
A=384B=3*(100000000)2+2C=778
K=7weneedtomove(2^7)*3coinsintoA.WemovethemfromC
A=768B=3*(100000000)2+2C=394
K=8Finally,wecanmoveourlast1bitfromBtoA.
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 24/30
A=1536B=3*(000000000)2+2C=394
A=1536B=(3*0+2)C=394
Intheexample,from(3,905,1024)wecanarriveto(2,394,1536).Then,withsamelogic,
wecangofrom(2,394,1536)to(0,X,Y),because394=2*197+0.
ThisishowyoucouldwriteemptyOneBox()procedure.Theremainedproblemisstraight
forward:ifinitiallytherearezerooroneboxeshavingcandies,theansweris"1".
Otherwise,untiltherearemorethan2boxeshavingcandies,pick3boxesarbitraryand
applyemptyOneBox().
Hereisasourceimplementingthealgorithm.4383485
BONUS
Insteadofaconclusion,I'llposthererelatedproblemstotheonesusedintheround.:)
Pleasenotethatsomeofthemmightbemoreeasier/complicatedthanlevelofdifficulty
usedintheround.Feelfreetothinkofthem/askhelp/discusstheminthecomment
section:)
Div2ASupposex,y,A,B10 .Insteadofbeingaskedhowmanybricksarecolored
withbothredandpinkinrange[A,B],you'reaskedhowmanybricksarecoloredwithat
leastonecolor.Afteryousolvethisone,solvethesameproblem,butinsteadofhaving2
personspainting,youhavekpersons(k20).SolutionbyEnchom
Div2BGivenaverylonglistofspecialpoints,canyoufindquicklyaconvexspecial
quadrilateral?Canyoufindveryveryquickly?:)Also,canyoufindmaximalareaofa
specialconvexquadrilateralintimebetterthanO(N )?Solutionsforfirstproblemand
secondproblemprovidedbyXellosandEnchom
Div2D/Div1BSupposethereverseproblem.YouaregivenabubblesortgraphhavingN
verticesandMedges.Finditsindependentmaximalset.CanyouachieveO(N )todo
this?DoesasolutioninO((N+M)+N*logN)exist?Solutionby[user:CNT0,201309
04]
Div2E/Div1CFindasolutionrunninginliniartime.Solution(dynamicprogramming)by
ivan100sic.Solution(inclusionexclusionprinciple)byeduardische
Div1DSupposethe3Dversionofthisproblem.Youhavea3Dmatrixandyouperform
sameQUERY/UPDATEoperations,butusing6parameters(asubmatrixisdefinednowall
elementsa[i][j][k]forwhichx0<=i<=x1,y0<=j<=y1,z0<=k<=z1).Canyougeta
solutionusingO(log *N)perquery,havingconstant8?Butforddimensions,doesan
O(2 *(log )n)algorithmperqueryexist?:)SolutionbyDwylkz.
Div1EInouralgorithm,wepickarbitrary3boxes.Canyoufindsomeheuristicsofpicking3
boxestoreducenumberofmoves?
Readmore
codeforces, 198, editorial
CodeforcesRound#198
Helloeveryone!
WeinviteyoutoparticipateatCodeforcesRound#198,scheduledFriday,30Augustat
7:30PMMSK.TheauthorsoftheproblemsaremeandLinh(ll931110).Wearealsothe
authorsoftheCodeforcesRound#191(Div.2).Lasttime,wereceivedpositivefeedbackfor
theround.Wehopethisroundwillbeatleastasgoodasthepreviousone.
LinhbroughttoyouD2C/D1AandD2E/D1C.Iwrotetherestofthetasks.Wehopeyou'll
spendmoretimewritingonthepaperandthinkingthantypingonthePC.Inaddition,all
tasksdon'trequiretoocomplicatedalgorithms.Instead,allrequiresomecreativity,hard
workingandpatience.BTWs,themaincharacteroftheroundwillbeIahub,asinthe
previousone.
I'dliketothanktoDamianS,GeraldandAksenov239fortestingtheround.Withoutthem,
9
4
2
3
d d
+130
elfus0 9monthsago 71


Byelfus0,9monthsago, ,
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 25/30
myjobwouldhavebeencertainlyharder.Also,thankstoDelinurfortranslatingthetasks
andtoMikeMirzayanovfortheamazingCodeforcesplatformandPolygonsystem.
Wewisheveryonehighratingandtohavefun!
UPD1Thescoredistributionwillbedynamicinbothdivisions.Formoreinformationplease
lookhere.Theproblemsaresortedinourexpectedorderofdifficulty.
UPD2Thanksforeveryonewhoparticipated.Ihopeyoufountproblemsinteresting.Also,I
thinkmyprevisionthatyou'llthinkmorethanwritewascorrect:)
Congratulationstothewinners.
Division1
1. yeputons
2. KADR
3. ftiasch
4. Myth5
5. huzecong
6. R_R_
7. Gabaum
8. James
9. ifsmirnov
10. niyaznigmatul
Specialcongratulationsto[user:KudryashovIA,20130830],theonlypersonwhosolvedD1
E!
Division2
1. Azat_Yusupov
2. angel_of_monkey
3. cki86201
4. jyamy
5. Mato_No1
6. silver__bullet
7. TheDude
8. Nero
9. beo_chay_so
10. [user:_MAMU_,20130830]
UPD3Theeditorialhasbeenfinished.I'mwaitingforyourfeedback/questions.
Readmore
AnnouncementofCodeforcesRound#198(Div.2)
AnnouncementofCodeforcesRound#198(Div.1)
codeforces, 198, div1+div2
CodeforcesRound#191Tutorial
327A
IllpresentheretheO(N^3)algorithm,whichisenoughtosolvethistask.Then,forthose
interested,IllshowamethodtoachieveO(N)complexity.
O(N^3)method:Thefirstthingtoobserveisthatconstrainsareslowenoughtoallowa
bruteforcealgorithm.Usingbruteforce,Icancalculateforeachpossiblesinglemovethe
numberof1sresultingafterapplyingitandtakemaximum.Forconsidereachmove,Ican
justgeneratewith2FORloopsallindicesi,jsuchasi<=j.SofarwehaveO(N^2)
complexity.SupposeIhavenow2fixedvaIuesiandj.Ineedtocalculatevariablecnt
(initially0)representingthenumberofonesifIdothemove.Fordothis,Ichooseanother
indicektogoina[]array(takingO(N)time,makingthetotalofO(N^3)complexity).We
havetwocases:eitherkisinrange[i,j](thismeansi<=kANDk<=j)ornot(ifthat
conditionisnotmet).Ifitsinrange,thenitgetsflipped,soweaddtocountvariable1a[k]
(observethatitmakes0to1and1to0).Ifitsnotinrange,wesimplyaddtocntvariable
+207
elfus0 9monthsago 109


Byelfus0,11monthsago, ,
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 26/30
a[k].Theanswerismaximumofallcntobtained.
O(N)method:Forachievethiscomplexity,weneedtomakeanobservation.SupposeIflip
aninterval(itdoesnotmatterwhatinterval,itcanbeanyinterval).AlsosupposethatSis
thenumberofonesbeforeflipiingit.Whathappens?EverytimeIflipa0value,Sincreases
by1(Igetanew1value).EverytimeIflipa1value,Sdecreasesby1(Iloosea1value).
Whatwouldbethegainfromaflip?Iconsiderwinning+1whenIgeta0valueand1
whenIgeta1value.Thegainwouldbesimplyasumof+1and1.Thisgivesusideato
makeanothervectorb[].B[i]is1ifA[i]is0andB[i]is1ifA[i]is1.WewanttomaximizeS+
gain_after_one_movesum.AsSisconstant,Iwanttomaximizegain_after_one_move.In
otherwords,Iwanttofindasubsequenceinb[]whichgivesthemaximalsum.IfIflipit,Iget
maximalnumberof1stoo.ThiscanbefoundedtriviallyinO(N^2).HowtogetO(N)?A
relativeexperiencedprogrammerindynamicprogrammingwillimmediatelyrecognizeitas
aclassicalproblemsubsequenceofmaximalsum.Ifyouneverheardaboutit,comeback
tothisapproachafteryoulearnit.
327B
Wellpresenttwodifferentsolutionsforthistask.
Solution1.Whatifwesolveamoregeneraltask?Whatifeachhungrynumberfromthe
solutionisntallowedtobedividedbyanynumbersmallerthanit(except1,whichisdivides
everynaturalnumber).Ifthismoregeneralconditionwouldbemet,thenthehungry
conditionwouldbemet,too(asa[i]wontbedividedbyanumbersmallerthanit(except1),
itwontbedividedbya[j],too,withj<i,assumingthata[j]isdifferentfrom1).Nowhowto
findnumbersforthismoregeneralcondition?Wecanrephraseitas:eachnumberfrom
moregeneralconditionhas2divisors:1anditself.SoifweprintNnumberswith2divisors
inincreasingorder,thatwouldbeagoodsolution.Asyouprobablyknow,numberswith2
divisorsarecalledprimenumbers.ThetaskreducestofindingfirstNprimenumbers.This
canbedoneviabruteforce,orviaSieveofEratosthenes(however,notnecessarilytoget
anACsolution).
Solution2.SupposewearegiventhenumberN.Wecanobservethatforbigenough
consecutivenumbers,thearrayisalwayshungry.Forexample,wecanprint3*N+0,3*N
+1,3*N+2,,3*N+(N1).Magic,isntit?Whydoesitworknow?Pickanarbitrary
a[i].Thesolutionwouldbebadifoneofnumbers2*a[i],3*a[i],4*a[i]andsoonwouldbe
ina[]array.However,itwillneverhappen.Thesmallestmultiplefromthatoneswillbe2*3
*N=6*N.Thereisnotpossibletoobtainasmallestmultiplethanthatone.Ontheother
hand,thebiggestnumberfroma[]arraywouldbe3*N+N1=4*N1.Sincesmallest
multipleisbiggerthanbiggesttermofthearray,it(andofcourseothermultiplesbigger
thanit)willneverexistina[]array.Sotheabovesolutioniscorrectalso.
327C
Property:Anumberisdivisibleby5ifandonlyifitslastdigitiseither0or5.
Afirstsolution:SupposeyouregivenaplateS,notsobig,sowecaniterateallits
elements.Canwegettheanswer?Ibuildanewarraysol[].Inexplanation,bothSandsol
willbe1based.DenoteN=sizeofS.Also,denotesol[i]=thenumberofwaystodelete
digitsfromplateSsuchasweobtainamagicnumberwhichhasthelastdigitonpositioni.
Theanswerissol[1]+sol[2]++sol[N].Letsfocusnowoncalculatingsol[i].IfS[i](digitof
theplatecorrespondingtoithposition)isdifferentthan0or5,thensol[i]is0(see
property).Otherwisewehavetoaskourself:inhowmanywaysIcandeletedigitsinleft
andinrightofpositioni.Intheright,wehaveonlyoneway:deletealldigits(ifonedigit
fromrightstillstands,thenthenumberisntendingatpositioni).Nowintheleft:thereare
digitsonpositions1,2,,i1.Wecaneitherdeleteadigitorkeepitanyhowheddowe
stillgetamagicnumber.Soonposition1Ihave2ways(deleteorkeepit),onposition2I
havealso2ways,,onpositioni1Ihavealso2ways.Next,weapplywhatmathematics
callruleofproductandweget2*2*2*2(i1times)=2^(i1).Applyingruleof
productonbothleftandrightIget2^(i1)*1=2^(i1).Tosumitup:IfS[i]is0or
5weaddtotheanswer2^(i1).Otherwise,weaddnothing.Theonlyproblemremained
forthissimpleversionishowwecalculateA^Bmoduloonenumber.Thisisawellknown
problemaswell,calledExponentiationbysquaring.
Comingbacktoourproblem:Sowhatsdifferentinourproblem?Itsthefactthatwecant
iterateallelementsofplate.However,wecanuseconcatenationproperty.Weknowthatif
anelementisapositioniinthefirstcopy,itwillalsobeonpositionsi+n,i+2*n,i+3*n,
,i+(k1)*n(wedontcallhereabouttrivialcasewhenk=1).Whatifiterateonlyone
copyandcalculateforallKcopies.Ifinthefirstcopy,atthepositioniiseither0or5,we
havetocalculatethesum2^i+2^(i+n)+2^(i+2*n)++2^(i+(k1)*n).Bynow
on,incalculusI'lldenoteiasi1(it'sasimplemathematicalsubstitution).Afirstidea
wouldbejusttoiterateeachtermandcalculateitwithexponentiationbysquaring.However,
ittakesintheworstcasethesamecomplexityasiteratingallplate.Weneedtofind
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 27/30
somethingsmarter.
2^i+2^(i+n)+2^(i+2*n)++2^(i+(k1)*n)=
=2^i*1+2^i*2^n+2^i*2^(2*n)++2^i*2^((k1)*N)=
=2^i*(2^0+2^n+2^(2*n)++2^((k1)*n)
WereducedtheproblemtocalculatesumS=2^0+2^n+2^(2*n)++2^(X*n).
Whatsthevalueof2^n*S?Itis2^n+2^(2*n)+2^(3*n)++2^((X+1)*n).
Andwhatyougetbymaking2^n*SS?
2^n*SS=2^((X+1)*n)1
S*(2^n1)=2^((X+1)*n)1
S=(2^((X+1)*n)1)/(2^n1).
Wecancalculateboth2^iandSwithexponentiationbysquaringandtheproblemisdone.
For"/"operator,wecanusemultiplicativeinverse(youcanreadaboutthatandabout
FermatLittle'stheorem,takingcarethat10^9+7isaprimenumber).Thetimecomplexity
isO(N*logK).Note:thatkindofreductionofpowersiscalledpowerseriesinmath.
Alternativesolution:Forthisalternativesolution,wedon'tneedtouseanyspecial
propertiesof5.Infact,wecanreplace5byanyintegerpandstillhavethesamesolution.
Sofornow,Ishallwritepinplaceof5.
Thissuggestsadynamicprogrammingsolution:denotedp(x,y)bethenumberofwaysof
deletingsomedigitsinthefirstxdigitstoformanumberthathasremaindery(modulop).
Forsimplicity,weacceptemptyplatebeanumberthatisdivisiblebyp.WritingtheDP
formulaisnotdifficult.Westartwithdp(0,0)=1,andsupposewealreadyhavethevalue
dp(x,y).Weshallusedp(x,y)toupdatefordp(x+1,*),whichhastwopossiblecases:either
keepingthe(x+1)thdigitorbydeletingit.Iwon'tgointomuchdetailhere.Theansweris
thereforedp(N,0).
Clearly,applyingthisDPdirectlywouldtimeout.Forabetteralgorithm,weresortonthe
periodicityoftheactualplate.Thekeyideaisthat,weimagineeachdigitintheplateasa
lineartransformationfrom(x0,x1,..,x(p1))to(y0,y1,y(p1)).Obviously,(x0,x1,..,x(p
1))correspondstosomedp(i,0),dp(i,1)..dp(i,p1)and(y0,y1,y(p1))corresponds
tosome(dp(i+1,0)),dp((i+1),1),...,dp(i+1,p1).SowecanwriteX*M(d)=Y,
whereXandYarevectorsoflengthp,andM(d)isthematrixofsizep*prepresentingdigit
d(notethatM(d)isindependentfromXandY).Bymultiplyingall|a|.Ksuchmatrices
together,weobtainatransformationfrom(1,0,0,..,0)to(T0,T1,..,T(p1))whereT0is
actuallyouranswer(includingtheemptyplate).
What'sthedifference?Wecangroupthematricesingroupsoflength|a|,andlifttothe
exponentK.ThatleadstoanalgorithmwithtimecomplexityO(p^3(|a|+logK)),whichcould
berisky.Toimprove,weshouldgobacktoouroriginalDPfunctionandobservethatitis
actuallyalineartransformationfrom(1,0,0,..,0)to(R0,R1,,R(p1)),ifwerestrict
ourselvesinthefirstfragmentoflength|a|.Soinsteadofmultiplying|a|matricestogether,
wecanrunDPptimeswithinitialconditions(0,0,..,0,1,0,..,0)toobtainthematrix
transformation.TheoveralltimecomplexitybecomesO(|a|*p^2+p^3logK).
327D
Incaseyouwanttotrysomeexamplesonyourown,youmayplaythisgame,whichisthe
originofthisproblem:http://en.wikipedia.org/wiki/Tower_Bloxx
Nowbacktotheanalysis:)
TherestrictiongivenintheproblemposesyoutothinkofbuildingasmanyRedTowersas
possible,andfilltherestwithBlueTowers(sincethereisnoprofitoflettingcellsempty,
suchcellscanbefilledbyBlueTowers).Also,it'squiteobvioustoseethateachconnected
component(containingemptycellsonly)isindependentfromeachother,soweshalliterate
thecomponentonebyone.DenotethecurrentcomponentbeS.
Lemma1isimpossibletobuildSsothatitcontainsallRedTowersonly.
ProofSupposethereexistssuchaway.Lookupthelastcellthatisbuilt(denotebyx).
ClearlyxisaRedTower,soatthemomentitisbuilt,xmustbeadjacenttoacellthan
containsaBlueTower.However,it'sobviousthatthere'snosuchcell(ifthereis,itmust
belongtoS,whichisimpossible).
Asit'simpossibletohaveallRedTowers,it'snaturaltolookupatthenextbestsolution:the
onewithexactlyoneBlueTower,andamongthem,weneedtofindtheleastlexicographic
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 28/30
solution.Fortunately,wecanprovethatsuchaconfigurationisalwayspossible.Suchproof
isquitetricky,indeed:
Lemma2PickanycellbinS.ItispossibletobuildaconfigurationthathasallbutbbeRed
Towers,andbisaBlueTower.
ProofConstructagraphwhoseverticescorrespondtothecellsofS,andtheedges
correspondtocellsthatareadjacent.SinceSisconnected,itispossibletobuildatreethat
spanstoallverticesofS.Pickbastherootanddothefollowing:
1. BuildallcellsofSblue
2. Movefromtheleaftotheroot.Ateachcell(excepttheroot),destroytheBlueTower
andrebuildwiththeRedTower.Tobeprecise,ucanbedestroyed(andrebuilt)ifall
verticesinthesubtreerootedatuhavealreadybeenrebuilt.
Howcanitbethevalidsolution?Takeanyvertexuwhichisabouttoberebuilt.Clearlyuis
notb,anduhasitsparenttobeblue,sotheconditionforrebuildingcanbemet.Whenthe
buildingiscompleted,onlybremainsintact,whileothershavebeentransformedintoRed
Towers.
Sowegetthefollowingalgorithm:doaBFS/DFSsearchtofindconnectedcomponents.
Then,applyLemma2tobuildavalidconfiguration.
327E
Usuallywhendealingwithcomplicatedproblems,agoodideaistosolvethemforsmall
cases.Letstrythishere.
Firstcase:K=0.TheanswerisobviouslyN!(eachpermutationofp1,p2,,pnwouldbe
good).
Nextcase:K=1.TheanswerofthisoneisN!|L1|.ByL1Idenoteallroutesforwhicha
prefixsumisequaltofirstluckynumber.Obviously,iffromallroutesIexcludethewrong
ones,Igetmyanswer.Ifwecanfindanalgorithmtoprovide|L1|ingoodtime,then
problemissolvedforK=1.
1. WecanjusttryallN!permutations.Despitethismethodissimple,ithascomplexity
O(N!),toomuchfortheconstraints.
2. Supposewevefoundedasetofpositionsp1,p2,..,pksuchasa[p1]+a[p2]+..+a[pk]
=U1(firstunluckynumber).Howmanypermutationscanwemake?Thefirstk
positionsneedtobep1,p2,..,pk,butinanyorder.Hencewegetk!.Thenotused
positionscanalsoappearedinanyorder,startingfromk+1position.Astheyarenk,
wecanpermutethemin(nk)!ways.Hence,theanswerisk!*(nk)!Insteadof
permuting{1,2,..,n},nowweneedtofindsubsetsofit.Hence,therunningtime
becomesO(2^n).Thisisstilltoomuch.
3. Meetinthemiddle.Wemakeallsubsetsforfirsthalfofpositions(from1toN/2)and
themforsecondhalf(fromN/2+1toN).Foreachsubsetwekeep2information:
(sum,cnt)representingthatthereisasubsetofsumsumcontainingcntelements.
Foreach(X,Y)fromleftweiterateintheright.Afterchoosingoneelementfromtheleft
andonefromtherightwejustsplitthem.Tosplit2states(A,B)and(C,D),thenew
statebecomes(A+C,B+D).ButweknowthatA+C=U1.Thiscomesustotheidea:
foreach(X,Y)intheleft,Icheck(U1X,1),(U1X,2),,(U1X,K)fromtheright.
Foreachofthem,theanswerwouldbe(Y+K)!*(NYK)!.Icanstore(usingany
datastructurethatallowsthisoperations,Isuggestahash)how(C,D)=howmany
timesdoesstate(C,D)appearintheright.So,forastate(A,B)theanswerbecomesa
sumofhow(U1A,K)*(B+K)!*(NBK)!.Doingthesumforallstates(A,B),we
getouranswer.ThecomplexityofthismethodisO(2^(N/2)*N).
FinalCase:K=2Thewhole"meetinthemiddle"explanationworthed.Wewilldo
somethingverysimilartosolvethiscase.SupposeU1andU2aretheunluckynumbers.
Withoutloosingthegenerality,let'sassumeU1<=U2.
Following"Principleofinclusionandexclusion"paradigm(googleaboutitifyouneverheard
before)wecanwriteoursolutionasN!|L1||L2|+|intersectionbetweenL1andL2|.
Again,byL1,2Idenotethenumberofrouteswhichhaveaprefixsumequaltonumber
U1,2.The|X|isagainthecardinalofthisset.Basicallywecancalculate|X|asforK=1.
Theonlyproblemremainediscalculating|intersectionbetweenL1andL2|.
The|intersectionbetweenL1andL2|isthenumberofpermutationswhichhaveaprefix
sumequaltoU1andaprefixsumequaltoU2.SinceU1<=U2,wecansplitapermutation
fromthissetin3parts:
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 29/30
1/p1,p2,...pksuchasa[p1]+a[p2]+...+a[pk]=U1.
2/pk+1,pk+2,...,pmsuchasa[pk+1],a[pk+2],...,a[pm]=U2U1.Notethata[p1]+a[p2]
+...+a[pm]=U2.
3/Therestofelementsuntilpositionn.
ByaperfectlyidenticallogicfromK=1case,thenumberofpermutationsgiventhosep[]
wouldbek!*(mk)!*(nm)!.
Sotheproblemreducesto:findallindicessetp1,p2,...andq1,q2,..suchasa[p1]+a[p2]
+...+a[pn1]=U1anda[q1]+a[q2]+...+a[qn2]=U2U1.Then,wecanapplyformula
usingn1andn2describedabove.
ThefirstideawouldbeO(3^N)foreachpositionfrom{1,2,..,n}atributeall
combinationsof{0,1,2}.0meansthatpositioniis1/,1meansthatpositioniisin2/and2
meansthatpositioniisin3/.Thiswouldtimeout.
Happily,wecanimproveitwithmeetinthemiddleprinciple.Thesolutionisverysimilarwith
K=1case.Iwon'tfullyexplainithere,ifyouunderstoodprinciplefromK=1thisshouldn't
beaproblem.Thebaseideaistokeep(S1,S2,cnt1,cnt2)forboth"left"and"right".(S1,
S2,cnt1,cnt2)representsasubsetwhichhassumofelementsfrom1/equaltoS1,sumof
elementsfrom2/equaltoS2,in1/wehavecnt1elementandin2/wegetcnt2elements.
Fora(S1,S2,cnt1,cnt2)statefrom"left"wearelookingintherightforsomethinglike(U1
S1,U2U1S2,i,j).WegetO(3^(N/2)*N^2)complexity.
UnexpectedsolutionDuringtheround,wesawalotofO(2^N*N)solutionspassing.
Thiswastotallyoutofexpectations.Ibelieveifwouldmaketestsstronger,thissolution
won'tpassandroundwouldbemorechallenging.That'sit,nothingisperfect.Asrequested,
I'llexplainthatsolutionhere.
Beforeexplainingthesolution,Iassumeyouhavesomeexperiencewith"bitmaskdp"
technique.Ifyoudon't,pleasereadbefore:
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=bitManipulation
http://codeforces.com/blog/entry/337
Inthisproblemwe'llassumethatais0based.Foramask,considerbitsfromrighttoleft,
notingthembit0,bit1andsoon.Bitiis1ifandonlyifa[i]isinthesubsetwhichisina
bijectivereplationwiththemask.Forexample,formask100011101thesubsetis{a0,a2,
a3,a4,a8}.I'llcallfromnowonthesubset"subsetofmask".Also,thesumofallelements
inasubsetwillbecalled"sumofmask"(i.e.a0+a2+a3+a4+a8).We'llexplainthe
solutionbasedbywatashi'ssubmission.4017915
Firststepofthealgorithmistocalculatesumofeachmask.Letdp[i]thesumofmaski.
Removeexactlyoneelementfromthesubsetofmask.Supposethenewmaskobtainedisk
andremovedelementisj.Then,dp[i]=dp[k]+a[j].dp[k]isalwayscalculatedbeforedp[i]
(toproof,writebothkandiinbase10.kisalwayssmallerthani).Havingjanelementfrom
subsetofmaski,wecancomputemaskkbydoingi^(1<<j).Bitjis1,andbyxoringit
withanother1bit,itbecomes0.Otherbitsareunchangedbybeingxoredby0.This
methodworksveryfasttocomputesumofeachmask.
Fromnowon,let'sdenoteanewarraydp2[i]=howmanygoodroutescanIobtainwith
elementsfromsubsetofmaski.Watashiusessamedp[]array,butformakingitclear,in
editorialI'lluse2separatearrays.SupposethatCNT(i)isnumberofelementsfromsubset
ofmaski.Weareinterestedinhowmanywayswecanfillpositions{1,2,...,CNT(i)}with
elementsfromsubsetofmaskisuchaseachprefixsumisdifferentbyeachunlucky
number.
Nextstepofthealgorithmistoseewhichsumofmasksareequaltooneofunlucky
numbers.Wemarkthemas"1"indp2[].Supposewefoundedasubset{a1,a2,...,ax}for
whicha1+a2+...+ax=oneofunluckynumbers.Then,nonepermutationof{a1,a2,...,
ax}isallowedtoappearonfirstxpositions.Whenwearrivetoa"1"state,weknowthatthe
numberofgoodroutesforitssubsetofmaskis0.
Now,finallythemaindprecurrence.Ifforthecurrentmaski,dp2[i]=1,thendp2[i]=0and
continue(wediscardthestateasexplainedabove).Otherwise,weknowthattherecould
existatleastonewaytocompletepositions{1,2,...CNT(i)}withelementsofsubsetof
maski.Buthowtocalculateit?Wefixthelastelement(theelementfromtheposition
CNT(I))withsomejfromsubsetofmaski.Theproblemreducesnowwithhowmanygood
routescanIfillinpositions{1,2,...,CNT(i)1}withelementsfromsubsetofmaski,from
whichweerasedelementj.Withsameexplanationofsumofmaskcalculations,thisis
alreadycalculatedindp2[i^(1<<j)].
6/5/2014 Blog entries - Codeforces
http://codeforces.com/blog/elfus0 30/30
Codeforces(c)Copyright20102014MikeMirzayanov
TheonlyprogrammingcontestsWeb2.0platform
Servertime:2014060511:37:05(c4).
Theresultisdp2[(1<<N)1](numberofgoodroutescontainingallpositions).
Editorialhasbeenmadebymeandll931110.
Theauthorsoftheproblems:
Div.2A&Div.2Bme
Div.2C&Div.2D&Div.2Ell931110
Readmore
TutorialofCodeforcesRound#191(Div.2)
tutorial, 191, codeforces191
+86
elfus0 11monthsago 51

You might also like