Advertisement
istinishat

Segment Tree

Nov 12th, 2016
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int arr[1000],tree[4000];
  2.  
  3. void build(int node,int l,int r)
  4. {
  5.     if(l==r)
  6.         tree[node]=arr[l];
  7.     else{
  8.         int mid=(l+r)/2;
  9.         build(node*2,l,mid);
  10.         build(node*2+1,mid+1,r);
  11.         tree[node]=tree[node*2]+tree[node*2+1];
  12.     }
  13. }
  14.  
  15. int sum(int node,int tl,int tr,int l,int r)
  16. {
  17.     if(l>r)
  18.         return 0;
  19.     if(l==tl && r==tr)
  20.         return tree[node];
  21.     int mid=(tl+tr)/2;
  22.  
  23.     return sum(node*2,tl,mid,l,min(r,mid))
  24.         + sum(node*2+1,mid+1,tr,max(l,mid+1),r);
  25. }
  26.  
  27. void update(int node,int l,int r,int pos,int val)
  28. {
  29.     if(l==r)
  30.         tree[node]=val;
  31.     else{
  32.         int mid=(l+r)/2;
  33.         if(pos<=mid)
  34.             update(node*2,l,mid,pos,val);
  35.         else
  36.             update(node*2+1,mid+1,r,pos,val);
  37.         tree[node]=tree[node*2]+tree[node*2+1];
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement