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.
#!/bin/python3importmathimportosimportrandomimportreimportsys# returns d, x, y so that gcd(a, b) = d and ax + by = ddefextended_euclidean_alg(a,b):# starts out as p[0] = P_{-1}, p[1] = P_0 and same for q# in general it's the previous 2 terms, P_{i-1}, P_{i-2}p=[0,1]q=[1,0]counter=1whileb!=0:quo=a//brem=a%bnewP=quo*p[1]+p[0]newQ=quo*q[1]+q[0]p[0]=p[1]p[1]=newPq[0]=q[1]q[1]=newQa=bb=remcounter=(counter+1)%2minusOne=(counter-1)%2returna,q[0]*((-1)**minusOne),p[0]*((-1)**(counter))defleastSigBit(num):return(num&-num)# implementation of a Fenwick treeclassPrefixSumTree(object):def__init__(self,array):l=len(array)self.sums=[0]*lforiinrange(1,l):cl=i-leastSigBit(i)forjinrange(cl+1,i+1):self.sums[i]=(self.sums[i]+array[j])%pdefsum(self,i):sum=0whilei>0:sum=(sum+self.sums[i])%pi-=leastSigBit(i)returnsum# adds toAdd to the ith element of arraydefadd(self,i,toAdd):whilei<=len(self.sums)-1:self.sums[i]=(self.sums[i]+toAdd)%pi+=leastSigBit(i)p=10**9+7defpolynomialDivision(a,b,c,queries):res=[]a_inv=extended_euclidean_alg(p,a)[2]x=-b*a_inv%p# if x != 0 then we have to build the sum treeifx!=0:l=len(c)# polyArray[i+1] = c[i]*x^i % p and polyArray[0] = 0polyArray=[0]*(l+1)polyArray[1]=c[0]# powsOfX[i] = x^i % ppowsOfX=[1]*lforiinrange(1,l):newPow=(powsOfX[i-1]*x)%ppowsOfX[i]=newPowpolyArray[i+1]=(c[i]*newPow)%psumTree=PrefixSumTree(polyArray)forqinqueries:ifq[0]==1:# compute how much we need to add for the sumtoAdd=q[2]-c[q[1]]# update the array c with our new entry q[2]c[q[1]]=q[2]ifx!=0:# then we add the appropriate amount to our prefix sums.# since sumTree keeps track of sum c_i * x^i we multiply by the # appropriate power of xsumTree.add(q[1]+1,(toAdd*(powsOfX[q[1]]))%p)else:# remember c is zero indexed but sumTree is one indexed# so we do sum(q[2]+1) - sum(q[1]) instead of sum(q[2]) - sum(q[1]-1)pOfX=c[q[1]]ifx==0else(sumTree.sum(q[2]+1)-sumTree.sum(q[1]))%pifpOfX==0:res.append("Yes")else:res.append("No")returnresif__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')nabq=input().split()n=int(nabq[0])a=int(nabq[1])b=int(nabq[2])q=int(nabq[3])c=[int(t)fortininput().rstrip().split()]queries=[]for_inrange(q):queries.append([int(t)fortininput().rstrip().split()])result=polynomialDivision(a,b,c,queries)fptr.write('\n'.join(result))fptr.write('\n')fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Polynomial Division
You are viewing a single comment's thread. Return to all comments →
This is my python Solution