?。?玄学求调
查看原帖
?。?玄学求调
335094
Lucifero楼主2021/2/24 13:40
#include <bits/stdc++.h>
using namespace std;
class SegmentTree
{
public:
	int v,l,r;
	int lazy;
}tree[800001];
int a[100001],n;
void build(int p,int l,int r)
{
	tree[p].l=l,tree[p].r=r;
	if (l==r)
	{
		tree[p].v=a[l];
		return;
	}
	int mid=(l+r)>>1;
	build(p<<1,l,mid);
	build((p<<1)+1,mid+1,r);
	tree[p].v=tree[p<<1].v+tree[(p<<1)+1].v;
}
void pushdown(int p)
{
	tree[p<<1].v+=tree[p].lazy;
	tree[p<<1].lazy+=tree[p].lazy;
	tree[(p<<1)+1].v+=tree[p].lazy;
	tree[(p<<1)+1].lazy+=tree[p].lazy;
	tree[p].lazy=0;
}
void modify(int p,int l,int r,int d)
{
	if (tree[p].lazy!=0) pushdown(p);
	if (tree[p].l>=l && tree[p].r<=r)
	{
		tree[p].v+=d;
		tree[p].lazy+=d;
		return;
	}
	int mid=(tree[p].l+tree[p].r)>>1;
	if (mid>=l && tree[p<<1].l<=r)
		modify(p<<1,l,r,d);
	if (mid<r && tree[(p<<1)+1].r>=l)
		modify((p<<1)+1,l,r,d);
	tree[p].v=tree[p<<1].v+tree[(p<<1)+1].v;
}
int sum(int p,int l,int r)
{
	if (tree[p].lazy!=0) pushdown(p);
	if (tree[p].l>=l && tree[p].r<=r)
		return tree[p].v;
	int mid=(tree[p].l+tree[p].r)>>1,tot=0;
	if (mid>=l && tree[p].l<=r)
		tot+=sum(p<<1,l,r);
	if (mid<r && tree[p].r>=l)
		tot+=sum((p<<1)+1,l,r);
	return tot;
}
int main()
{
	//【模板】线段树 1
	int m,opt,x,y,k,i;
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;i++) scanf("%d",&a[i]);
	build(1,1,n);
	while(m--)
	{
		scanf("%d%d%d",&opt,&x,&y);
		if (opt==1)
		{
			scanf("%d",&k);
			modify(1,x,y,k);
		}
		else if (opt==2)
			printf("%d\n",sum(1,x,y));
	}
}
2021/2/24 13:40
加载中...