I am currently solving a problem on segment tree. I think the problem needs lazy propagation concept to be solved. As I'm very new to this concept, i'm having trouble with my code.
The problem in a nutshell is as follows:
initially, all array elements are 0 and they are indexed 0 to N-1
command 1. 0 x y v - updates value of each array indexes between x and y by v
command 2. 1 x y - output the sum of all numbers between array index x & y.
Input starts with an integer T (≤ 5), denoting the number of test cases.
Each case contains two integers n (1 ≤ n ≤ 105) and q (1 ≤ q ≤ 50000). Each of the next q lines contains a task in one of the following form:
0 x y v (0 ≤ x ≤ y < n, 1 ≤ v ≤ 1000)
1 x y (0 ≤ x ≤ y < n) For each case, print the case number first. Then for each query '1 x y', print the sum of all the array elements between x and y. Here is my attempt:
template<class T>
class SegmentTree
{
T *tree,*update_tree;
long size;
public:
SegmentTree(long N)
{
long x= (long)ceil(log2(N))+1;
long size = 2*(long)pow(2,x);
tree = new T[size];
update_tree = new T[size];
memset(tree,0,sizeof(tree));
memset(update_tree,0,sizeof(update_tree));
}
void update(long node, long start, long end, long i, long j, long val)
{
if(start>j || end<i) return;
if(start>=i && end<=j){
if(start==end){
tree[node]+=val;
return;
}
tree[node]+=val;
update_tree[2*node] += val;
update_tree[2*node+1]+=val;
return;
}
long mid = (start+end)/2;
update(2*node,start,mid,i,j,val);
update(2*node+1,mid+1,end,i,j,val);
}
T query(long node, long start, long end, long i, long j, long val)
{
if(start>j || end<i) return -1;
if(start>=i && end<=j)
return ((tree[node]+val)*(end-start+1));
long a,b;
a = update_tree[2*node];
b = update_tree[2*node+1];
long mid = (start+end)/2;
long val1 = query(2*node,start,mid,i,j,val+a);
long val2 = query(2*node+1,mid+1,end,i,j,val+b);
if(val1==-1)
return val2;
if(val2==-1)
return val1;
return val1+val2;
}
};
int main()
{
long N,q,x,y,res;
int tc=1, T,v,d;
scanf("%d",&T);
while(tc<=T)
{
scanf("%ld %ld",&N,&q);
SegmentTree<long>s(N);
printf("Case %d:\n",tc++);
while(q--){
scanf("%d",&d);
if(!d){
scanf("%ld %ld %d",&x,&y,&v);
s.update(1,0,N-1,x,y,v);
}
else{
scanf("%ld %ld",&x,&y);
res = s.query(1,0,N-1,x,y,0);
printf("%ld\n",res);
}
}
}
return 0;
}