POJ 3468 A Simple Problem with Integers(线段树区间修改)

#include<iostream>
#include<cstdio>
#define ll long long
#include<cstring>
using namespace std;
const int mx=1e5+10;
ll sum [mx*4];
ll la [mx*4];
void pushdown(int rt,int L,int R)
{	if(la[rt])
	{
		int m=(L+R)/2;
		la[2*rt]+=la[rt];
		la[2*rt+1]+=la[rt];
		sum[2*rt]+=1ll*(m-L+1)*la[rt];
		sum[2*rt+1]+=1ll*(R-m)*la[rt];
		la[rt]=0;
	}
}
void build(int L,int R,int rt)
{
	if(L==R)
	{
		scanf("%I64d",&sum[rt]);
		return ;
		
	}
	int m=(L+R)/2;
	build(L,m,rt*2);
	build(m+1,R,rt*2+1);
	sum[rt]=sum[rt*2]+sum[rt*2+1];
 } 
void update(int a,int b,int co,int L,int R,int rt)
{
	if(a<=L&&b>=R)
	{
		sum[rt]+=1ll*(R-L+1)*co;
		la[rt]+=co;
		return ;
	}
	pushdown(rt,L,R);
	int m=(L+R)/2;
	if(a<=m)update(a,b,co,L,m,rt*2);
	if(b>m) update(a,b,co,m+1,R,rt*2+1);
	sum[rt]=sum[rt*2]+sum[rt*2+1];
}

ll sea(int l,int r,int L,int R,int rt)
{
	if(l<=L&&R<=r)
		return sum[rt];
	int m=(L+R)/2;
	
	ll ans=0;pushdown(rt,L,R);
	if(l<=m) ans+=sea(l,r,L,m,rt*2);
	if(r>m) ans+=sea(l,r,m+1,R,rt*2+1);
	return ans; 

}
int main()
{
	int n,t,a,b;
	int c;
	char p[3];
 	while(scanf("%d%d",&n,&t)!=EOF)
 	{
 		build(1,n,1);
 		memset(la,0,sizeof(la));
 		while(t--)
 		{
 			scanf("%s",p);
 			if(p[0]=='Q')
 			{
 				scanf("%d%d",&a,&b);
 				printf("%I64d\n",sea(a,b,1,n,1));
			}
			else
			{
	
				scanf("%d%d%d",&a,&b,&c);
				update(a,b,c,1,n,1);
			}
		}
	}
	return 0;
}









猜你喜欢

转载自blog.csdn.net/qq_41568836/article/details/80290400