We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
# Enter your code here. Read input from STDIN. Print output to STDOUT'''Overallpossiblerootedtreesofnvertices,howmanypossibleoutputscantheDFS()functionyieldthatmatcharrayS?(IrenamedAtoSinstead)Theoutputarraydelineatesthedepthsofthenodesasittraversesdepth-first.ForexampleoDepth0/ \
ooDepth1/\ \
oooDepth2/ \
ooDepth3/|\ \
ooooDepth4yieldsorder[0,1,2,2,1,2,3,4,4,4,3,4]Necessaryconditions:1.Clearly,thereisonlyonerootnode,anditsdepthis0,so0mustbeatthestartofS,eitherintheformofa"?"ora0.2.0cannotbepresentanywhereinSotherthantheveryfront.3.Ifthesearchtraversesfromparenttochild,thedepthincreasesby1.4.Ifwehoptoanotherchildorsubtreeinstead,itsdepthcanonlybelessthanorequaltocurrentdepthInotherwords,wearecountingthenumberofsequences(thatmatchS)suchthatavaluecanincreasebyatmost1,ordropdowntoanypositiveinteger.So:1.output[0]=02.output[i]-1<=output[i-1]SowhenlookingatS,let'slookatsequencesof?charactersbetweenfixedelements.Forexample:[...,5,?,?,?,?,?,?,?,?,?,?,8,...]Leta=5andb=8.Letn=10,thenumberof"?"betweenaandb.Thefirst?muststartwithsomenumberintherange[1toa+1]=>[1to6]inclusive.Thelast?mustbeintherange[max(1,b-1)to(a+n)]=>[7to15]inclusive.Howmanyvalidsequencesarethere?Ingeneral,comb(2*n+a-b+1,n)-comb(2*n+a-b+1,n-b)'''importsysMOD=10**9+7MAXN=10**5MAXAI=200factLim=2*MAXN+MAXAIfact=[1]+[0]*(factLim)foriinrange(1,factLim+1):fact[i]=fact[i-1]*i%MODdefcomb(n,k):ifk<0orn<0ork>n:return0ifk==0ork==n:return1returnfact[n]*pow(fact[k]*fact[n-k],MOD-2,MOD)%MODdefpreliminaryCheck_isInvalid(S,N):#if first char isn't a 0 or '?', it's some other number. Invalid!ifS[0]!="?"andS[0]!=0:returnTrueforiinrange(1,N):#if S[i] could not possibly be as high as it is. Invalid!ifS[i]!="?"andS[i]>i:returnTrue#if there's a 0 anywhere else other than the start. Invalid!ifS[i]==0:returnTrue#Cannot make a depth jump like this. Invalid!if(S[i]!="?"andS[i-1]!="?")andS[i]-1>S[i-1]:returnTrue#basic checks OKreturnFalse#number of valid sequences to fill a section of L "?"s between two numbers a and b#such that S[i] takes on any number from 1 to S[i-1]+1defnumQuestionSeq(a,b,n):returncomb(2*n+a-b+1,n)-comb(2*n+a-b+1,n-b)defnumSuitable(S,N):ifpreliminaryCheck_isInvalid(S,N):return0S[0]=0#the extra 1 gives bIndex a sentinel val to use later. N will not count this.S+=[1]aIndex=0bIndex=1ans=1whileaIndex<NandbIndex<N:whilebIndex<NandS[bIndex]=="?":bIndex+=1n=bIndex-aIndex-1a,b=S[aIndex],S[bIndex]ifn>0:ans=ans*numQuestionSeq(a,b,n)%MODaIndex=bIndexbIndex+=1returnansN=int(sys.stdin.readline())S=[int(k)ifk.isdigit()elsekforkinsys.stdin.readline().split()]print(numSuitable(S,N))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insane DFS
You are viewing a single comment's thread. Return to all comments →
Python3 solution