Line segment tree for interval sum (template 2, lazy array)

Line segment tree for interval sum (template 2, lazy array)

​ Given an n-bit array and two operations:

  • Operation 1: Add a value to all the numbers in a certain interval in the array
  • Operation 2: Query the sum of all numbers in a certain interval in the array

Template question

struct SegmentTree{
    
    
	int l,r;
	LL sum,add;
	#define l(x) tree[x].l
    #define r(x) tree[x].r
    #define sum(x) tree[x].sum
    #define add(x) tree[x].add
}tree[maxn*4];
int a[maxn],n,m;

void build(int p,int l,int r){
    
    
	l(p)=l,r(p)=r;
	if(l==r) {
    
     sum(p)=a[l];return;}
	int mid=(l+r)/2;
	build(p*2,l,mid);
	build(p*2+1,mid+1,r);
	sum(p)=sum(p*2)+sum(p*2+1);
}

void lazy(int p){
    
    
	if(add(p)){
    
    
		sum(p*2)+=add(p)*(r(p*2)-l(p*2)+1);
		sum(p*2+1)+=add(p)*(r(p*2+1)-l(p*2+1)+1);
		add(p*2)+=add(p);
		add(p*2+1)+=add(p);
		add(p)=0;
	}
}

void change(int p,int l,int r,int z){
    
    
	if(l<=l(p)&&r>=r(p)){
    
    
		sum(p)+=(LL)z*(r(p)-l(p)+1);
		add(p)+=z;
		return;
	}
	lazy(p);
	int mid=(l(p)+r(p))/2;
	if(l<=mid) change(p*2,l,r,z);
    if(r>mid) change(p*2+1,l,r,z);
	sum(p)=sum(p*2)+sum(p*2+1);
}

LL ask(int p,int l,int r)
{
    
    
	if(l<=l(p)&&r>=r(p)) return sum(p);
	lazy(p);
    int mid=(l(p)+r(p))/2;
	LL ans=0;
    if(l<=mid) ans+=ask(p*2,l,r);
    if(r>mid) ans+=ask(p*2+1,l,r);
    return ans;
}

int main()
{
    
    
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	build(1,1,n);
	while(m--)
	{
    
    
        int op,x,y,z;
		scanf("%d%d%d",&op,&x,&y);
		if(x>y)swap(x,y);
		if(op==1)
		{
    
    
			scanf("%d",&z);
			change(1,x,y,z);
		}
		else printf("%lld\n",ask(1,x,y));
	}
}

Guess you like

Origin blog.csdn.net/weixin_44986601/article/details/105759383