Iam_Sandeep

Fenwick Tree or Binary Index Tree

Jul 10th, 2022 (edited)
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. class NumArray:
  2.     global n,A,lsb
  3.     n=None
  4.     A=None
  5.    
  6.     #following func caluculates LSB left most significant bit
  7.     lsb=lambda y:y&-y
  8.     nums=None
  9.     def __init__(self, x: List[int]):
  10.         global lsb,A,n,nums
  11.         nums=x
  12.         n=len(x)
  13.         A=[0]*(n+1)
  14.     #since fenwick tree starts with index 1  when we refer to corresponding numbs will be i-1(0 base indexed)
  15.         #Add nums[i-1] to  A[i]
  16.         for i in range(1,n+1):
  17.             A[i]=A[i]+x[i-1]
  18.  
  19.             #find child using parent
  20.             j=i+lsb(i)
  21.  
  22.         #update child or propagate to child
  23.             if j<n+1:
  24.                 A[j]=A[j]+A[i]        
  25.     #update index i to val
  26.     def update(self, i: int, val: int) -> None:
  27.         #since we have to update ith element of nums array.
  28.         #It corresponds to branch with i+1 th element of fen tree
  29.         #Before you update nums array,find out delta(change)
  30.         global lsb,A,n,nums
  31.        
  32.         inc=val-nums[i]
  33.         nums[i]=val
  34.  
  35.         #j is pointer to corresponding of i in fen tree
  36.         j=i+1
  37.  
  38.         #while no more child
  39.         while j<n+1:
  40.             #update
  41.             A[j]=A[j]+inc
  42.  
  43.             #find next child
  44.             j=j+lsb(j)
  45.        # print(nums)
  46.         #print(A)
  47.        
  48.     #caluculte sum between i and j indexes including i,j
  49.     def sumRange(self, i: int, j: int) -> int:
  50.         global lsb,A,n
  51.         def prefix(i):
  52.             #pointer to fen tree
  53.             j=i+1
  54.             ans=0
  55.             #If no more  parent
  56.             while j>0:
  57.                 ans=ans+A[j]
  58.                 #find next parent
  59.                 j=j-lsb(j)
  60.             return ans
  61.         return prefix(j)-prefix(i-1)          
  62.  
  63.  
  64. # Your NumArray object will be instantiated and called as such:
  65. # obj = NumArray(nums)
  66. # obj.update(index,val)
  67. # param_2 = obj.sumRange(left,right)
Advertisement
Add Comment
Please, Sign In to add comment