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.
fromcollectionsimportdefaultdictSTART=2FINAL=3SPLIT=4DANGLING=0MOD=1000000007classState(object):def__init__(self,c,out=None,out1=None):self.c=c#0:'a',1:'b':,2:start,3:final,4:splitself.out=out#NoneforNULL,0fordanglingself.out1=out1#NoneforNULL,0fordanglingclassFrag(object):def__init__(self,start,outs):self.start=startself.outs=outsdefpatch(self,s):forxinself.outs:ifx.out==DANGLING:x.out=sifx.out1==DANGLING:x.out1=sdefappend(self,a):self.outs.extend(a)returnself.outsclassRegex(object):def__init__(self,s):self.s=sself.cur=0self.trans=defaultdict(list)self.mapping={}self.finals=[]defsingle(self,c):s=State(c,DANGLING)returnFrag(s,[s])defcat(self,a,b):a.patch(b.start)returnFrag(a.start,b.outs)defalt(self,a,b):s=State(SPLIT,a.start,b.start)returnFrag(s,a.append(b.outs))defstar(self,a):s=State(SPLIT,a.start,DANGLING)a.patch(s)returnFrag(s,[s])defparse(self):c=self.s[self.cur]self.cur+=1ifc=='(':a=self.parse()c=self.s[self.cur]ifc=='*':#starself.cur+=2#"*)"returnself.star(a)elifc=='|':#alternativeself.cur+=1#'|'b=self.parse()self.cur+=1#')'returnself.alt(a,b)else:#catb=self.parse()self.cur+=1#')'returnself.cat(a,b)else:#'a'or'b':ifc=='a':returnself.single(0)else:returnself.single(1)defmove(self,ss,s,checked):ifsinchecked:returnchecked.add(s)ss.add(s)ifs.c==SPLIT:ss.remove(s)ifs.outisnotNone:self.move(ss,s.out,checked)ifs.out1isnotNone:self.move(ss,s.out1,checked)defdfa(self,ss,parent=-1):# move forward if possiblesave=list(ss)checked=set()forsinsave:self.move(ss,s,checked)key=tuple(ss)# check if computedifkeyinself.mapping:ifparent>=0:self.trans[parent].append(self.mapping[key])return# record final statesgid=len(self.mapping)self.mapping[key]=gidforxinkey:ifx.c==FINAL:self.finals.append(gid)breakifparent>=0:self.trans[parent].append(gid)# go subto=[set(),set()]forsinss:ifs.c<=1:ifs.outisnotNone:to[s.c].add(s.out)ifs.out1isnotNone:to[s.c].add(s.out1)fortinto:iflen(t)>0:self.dfa(t,gid)defgraph(self):n=len(self.mapping)ret=[[0]*nforxinrange(n)]visited=[False]*ndefdfs(now):ifvisited[now]ornownotinself.trans:returnvisited[now]=Trueforvinself.trans[now]:ret[now][v]+=1dfs(v)forxinself.trans:dfs(x)returnretdefmul(a,b):n=len(a)c=[[0]*nforxinrange(n)]foriinrange(n):forjinrange(n):forkinrange(n):c[i][j]+=a[i][k]*b[k][j]c[i][j]%=MODreturncdefpower(a,n):ifn==1:returnaret=power(a,n// 2)ret=mul(ret,ret)ifn&1:ret=mul(ret,a)returnretn=int(input())forxinrange(n):r,l=input().strip().split()l=int(l)reg=Regex(r)frag=reg.parse()frag.patch(State(FINAL))reg.dfa(set([frag.start]))graph=reg.graph()graph=power(graph,l)ans=0forfinreg.finals:ans+=graph[0][f]print(ans%MOD)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Count Strings
You are viewing a single comment's thread. Return to all comments →