#include
#include
#define MaxSize 1000
using namespace std;
struct node{
int l;
int r;
int data;
int lz;
}tree[MaxSize];
void build_tree(int arr[],node tree[],int i,int start,int end){
tree[i].l = start;
tree[i].r = end;
if(start == end){
tree[i].data = arr[start];
return ;
}
int mid = (start + end) / 2;
int left_node = 2 * i;
int right_node = 2 * i + 1;
build_tree(arr,tree,left_node, start,mid);
build_tree(arr,tree,right_node,mid+1,end);
tree[i].data = tree[left_node].data + tree[right_node].data;
return ;
}
void add(int arr[],node tree[],int i,int idx,int val){
if(tree[i].l == tree[i].r){
tree[i].data += val;
arr[idx] += val;
return ;
}
int mid = (tree[i].l + tree[i].r) / 2;
int left_node = 2 * i;
int right_node = 2* i + 1;
if(idx <= mid)
add(arr,tree,left_node, idx,val);
else
add(arr,tree,right_node,idx,val);
tree[i].data = tree[left_node].data + tree[right_node].data;
return ;
}
void push_down(int i){
if(tree[i].lz != 0){
int left_node = 2 * i;
int right_node = 2 * i + 1;
tree[left_node].lz += tree[i].lz;
tree[right_node].lz += tree[i].lz;
tree[left_node].data += (tree[left_node].r - tree[left_node].l + 1) * tree[i].lz;
tree[right_node].data += (tree[right_node].r - tree[right_node].l + 1) * tree[i].lz;
tree[i].lz = 0;
return ;
}
}
void add(int arr[],node tree[],int i,int L,int R,int k){
if(tree[i].l >= L && tree[i].r <= R){
tree[i].data += (tree[i].r - tree[i].l + 1) * k;
tree[i].lz += k;
return ;
}
push_down(i);
int mid = (tree[i].l + tree[i].r ) / 2;
int left_node = 2 * i;
int right_node = 2 * i + 1;
if(L <= mid){
add(arr,tree,left_node, L,R,k);
}
if(R >= mid+1){
add(arr,tree,right_node,L,R,k);
}
tree[i].data = tree[left_node].data + tree[i].data;
return ;
}
int search(int arr[],node tree[],int i,int L,int R){
if(tree[i].l >= L && tree[i].r <= R){
return tree[i].data;
}
if(tree[i].r < L || tree[i].l > R) return 0;
push_down(i);
int s = 0;
int mid = (tree[i].l + tree[i].r ) / 2;
int left_node = 2 * i;
int right_node = 2 * i + 1;
if(L <= mid){
s += search(arr,tree,left_node,L,R);
}
if(mid+1 <= R){
s += search(arr,tree,right_node,L,R);
}
return s;
}
int main(){
int arr[] = {0,1,2,3,4,5};
const int size = (sizeof(arr)/sizeof(*arr));
build_tree(arr,tree,1,1,5);
for(int i =1;i<=3*size;++i){
printf("tree[%d] = %d\n",i,tree[i].data);
}
printf("\n");
add(arr,tree,1,5,1);
for(int i =1;i<=3*size;++i){
printf("tree[%d] = %d\n",i,tree[i].data);
}
printf("\n");
printf("sum[%d-%d] = %d\n",1,5,search(arr,tree,1,1,5));
for(int i =1;i<=size;++i){
printf("arr[%d] = %d\n",i,search(arr,tree,1,i,i));
}
return 0;
}