栈溢出求调
查看原帖
栈溢出求调
776799
GODTREE楼主2024/4/21 18:57
#include <bits/stdc++.h>
using namespace std;
#define N 10000005
int n,m,a[N];
struct tree
{
	int val,laz,l,r;
}sg[N*4];
void build(int s,int t,int p)//对[s,p]区间建立线段树,p为编号
{
	sg[p].l=s;
	sg[p].r=t;
	if (s==t)
	{
		sg[p].val=a[s];
		return ;
	}
	int mid=s+((t-s)/2);//(t+s)/2会炸int
	build(s,mid,p*2);
	build(mid+1,s,p*2);
	//左右建树
	sg[p].val=sg[p*2].val+sg[(p*2)+1].val;
}
void add(int l,int r,int k,int p)
{
	if(sg[p].l>=l&&sg[p].r<=r)
	{
		sg[p].val+=(l-r+1)*k,sg[p].laz+=k;
		return ;
	}
	int mid=sg[p].l+((sg[p].l+sg[p].r)/2);
	if (sg[p].laz!=0&&l!=r)
	{
		sg[p*2].val+=sg[p].laz*(mid-l+1);
		sg[p*2+1].val+=sg[p].laz*(r-mid);
		sg[p].laz=0;
	}
	if (sg[p].l<=mid)
	{
		add(l,r,k,p*2);
	}
	else
	{
		add(l,r,k,p*2+1);
	}
	sg[p].val=sg[p*2].val+sg[p*2+1].val;
}
int query(int l,int r,int p)
{
	if (l>=sg[p].l||r<=sg[p].r)
	{
		return sg[p].val;
	}
	int mid=sg[p].l+((sg[p].r-sg[p].l)/2);
	if (sg[p].laz!=0)
	{
		sg[p*2].val+=sg[p].laz*(mid-l+1);
		sg[p*2+1].val+=sg[p].laz*(r-mid);
		sg[p].laz=0;
	}
	int sum=0;
	if (l<=mid)
	{
		sum+=query(l,r,p*2);
	}
	if (r>m)
	{
		sum+=query(l,r,p*2+1);
	}
	return sum;
}
int main()
{
	cin>>n>>m;
	for (int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	build(1,n,1);
	for (int i=1;i<=m;i++)
	{
		int opt;
		cin>>opt;
		if (opt==1)
		{
			int x,y,k;
			cin>>x>>y>>k;
			add(x,y,k,1);
		}
		else
		{
			int x,y;
			cout<<query(x,y,1)<<"\n";
		}
	}
	return 0;
}
2024/4/21 18:57
加载中...