I’m learning about segment tree and lazy propagation, and I’m not sure if there something wrong in my implementation or codechef is not fear enough for python.
I have attached my code so please if someone can help and tell me how improve it, would it be great!!
Thanks…
PYTHON3
def build(st,node,start,end):
if start == end:
st[node] = [1,0,0]
else:
mid = (start+end)//2
build(st,2*node+1,start,mid)
build(st,2*node+2,mid+1,end)
st[node] = [st[2*node+1][0] + st[2*node+2][0],st[2*node+1][1] + st[2*node+2][1],st[2*node+1][2] + st[2*node+2][2]]
def query(st,node,start,end,l,r):
if lazy[node] != 0:
st[node][0],st[node][1],st[node][2] = st[node][2],st[node][0],st[node][1]
if start != end:
lazy[2*n+1] = 1
lazy[2*n+2] = 1
lazy[n] = 0
if start > r or end < l:
return 0
if start >= l and end <= r:
return st[node][0]
mid = (start+end)//2
left = query(st,2*node+1,start,mid,l,r)
right = query(st,2*node+2,mid+1,end,l,r)
return left+right
def update(st,node,start,end,l,r):
if lazy[node] != 0:
st[node][0],st[node][1],st[node][2] = st[node][2],st[node][0],st[node][1]
if start != end:
lazy[2*n+1] = 1
lazy[2*n+2] = 1
lazy[n] = 0
if start > r or end < l:
return
if start >= l and end <= r:
st[node][0],st[node][1],st[node][2] = st[node][2],st[node][0],st[node][1]
#st[node] = [st[node][2],st[node][0],st[node][1]]
if start != end:
lazy[2*node+1] = 1
lazy[2*node+2] = 1
return
else:
mid = (start+end)//2
update(st,2*node+1,start,mid,l,r)
update(st,2*node+2,mid+1,end,l,r)
st[node] = [st[2*node+1][0]+st[2*node+2][0],st[2*node+1][1]+st[2*node+2][1],st[2*node+1][2]+st[2*node+2][2]]
return
n,q = map(int,input().split())
st = [None for _ in range(4*n)]
lazy = [0 for _ in range(4*n)]
build(st,0,0,n-1)
while q:
entry = [int(i) for i in input().split()]
if entry[0] == 1:
print(query(st,0,0,n-1,entry[1],entry[2]))
else:
update(st,0,0,n-1,entry[1],entry[2])
q-=1