【模板】线段树 1(区间加,区间和)

题目链接 https://www.luogu.com.cn/problem/P3372
代码
#include<iostream>
#include<cstdio>
#include<vector>
#define int long long 
using namespace std;
const int maxn=1e5+10;
int n,m,a[maxn];
struct node
{
	int l;
	int r;
	int data;
	int lazy;
}t[maxn<<2];
void pushup(int p)
{
	t[p].data=t[p<<1].data+t[p<<1|1].data;
}
void pushdown(int p)
{
	if(t[p].lazy)
	{
		t[p<<1].data+=t[p].lazy*(t[p<<1].r-t[p<<1].l+1);
		t[p<<1|1].data+=t[p].lazy*(t[p<<1|1].r-t[p<<1|1].l+1);
		t[p<<1].lazy+=t[p].lazy;
		t[p<<1|1].lazy+=t[p].lazy;
		t[p].lazy=0;
	}
} 
void build(int p,int l,int r)
{
	t[p].l=l,t[p].r=r,t[p].lazy=0;
	if(l==r)
	{
		t[p].data=a[l];
		return ;
	}
	int mid=(l+r)>>1;
	build(p<<1,l,mid);
	build(p<<1|1,mid+1,r);
	pushup(p);
}
void change(int p,int l,int r,int d)
{
	if(l<=t[p].l&&t[p].r<=r)
	{
		t[p].data+=d*(t[p].r-t[p].l+1);
		t[p].lazy+=d;
		return ;
	}
	pushdown(p);
	int mid=(t[p].l+t[p].r)>>1;
	if(l<=mid) change(p<<1,l,r,d);
	if(r>mid) change(p<<1|1,l,r,d);
	pushup(p); 
}
int ask(int p,int l,int r)
{
	if(l<=t[p].l&&t[p].r<=r)
		return t[p].data;
	pushdown(p);
	int mid=(t[p].l+t[p].r)>>1,ans=0;
	if(l<=mid)ans+=ask(p<<1,l,r);
	if(r>mid) ans+=ask(p<<1|1,l,r);
	return ans;
}
signed main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++) cin>>a[i];
	build(1,1,n);
	while(m--)
	{
		int op,x,y,k;
		cin>>op>>x>>y;
		if(op==1)
		{
			cin>>k;
			change(1,x,y,k);
		}
		else
			cout<<ask(1,x,y)<<endl;
	}
	return 0;
}  
posted @ 2020-09-05 19:06  我找木鱼  阅读(63)  评论(0)    收藏  举报