Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Online Python compiler (interpreter) to run Python online.
- # Write Python 3 code in this online editor and run it.
- from math import log2, ceil
- #st is segment tree
- #if no of nodes is perfect squre then size of seg tree array=2N-1
- #if no of nodes is not perfect sqaure then we should take nearest greater perfect square (lets say x). then segment tree size=2x-1
- def make(arr):
- n=len(arr)
- h=ceil(log2(n))
- size=2*2**h-1
- st=[None]*size
- print(arr)
- #l--->left pointer
- #r---->right pointer
- #i----->index to store the sum in seg tree array
- #child 1--> stores at 2*i+1
- #child 2 stores at 2*i+2
- def build(i,l,r):
- if l>r:
- return
- elif l==r:#like merge sort base condtions
- st[i]=arr[l]
- else:
- mid=(l+r)//2
- build(2*i+1,l,mid)
- build(2*i+2,mid+1,r)
- st[i]=st[2*i+1]+st[2*i+2]
- #l,r---->constants
- # we have to compute the sum of elements from index l to r including them
- #so these are fixed
- #s---->left pointer
- #r---->right pointer
- def findsum(i,l,r,s,e):
- #complete over lap
- if l<=s and e<=r:
- return st[i]
- #no overlap
- elif e<l or s>r:
- return 0
- #partial overlap
- else:
- mid=(s+e)//2
- one=findsum(2*i+1,l,r,s,mid)
- two=findsum(2*i+2,l,r,mid+1,e)
- return one+two
- build(0,0,n-1)
- print(st)#print segment tree
- print(findsum(0,1,3,0,n-1))
- #now we shall perform updates on segment tree --->O(log n)
- ci=1#index where we have to change value
- cv=2#value stores at the index that we have to change
- diff=arr[ci]-cv#difference that we have to updated in segment tree
- #make change in array first
- arr[ci]=cv
- def update(i,start,end):
- #if the node at index i holds the cv variable in its range.Lets substract
- if start<=ci<=end:
- #some leaves might be None if the size(arr) is not perfect square
- #lets donnt disturb it
- if st[i]==None:
- return
- st[i]-=diff
- mid=(start+end)//2
- if start==end:
- return
- update(2*i+1,start,mid)
- update(2*i+2,mid+1,end)
- #update functon
- update(0,0,n-1)
- print(findsum(0,1,3,0,n-1))
- print(st)
- make([1,3,5,7,9,11])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement