#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
struct node
{
int l;
int r;
long long sum;
}tree[4000005];
long long add[4000005];
void build(int x,int r,int rt)
{
tree[rt].l=x;
tree[rt].r=r;
if(x==r)
{
scanf("%lld", &tree[rt].sum);
return ;
}
int mid=(x+r)/2;
build(x,mid,rt*2+1);
build(mid+1,r,rt*2+2);
tree[rt].sum=tree[rt*2+1].sum +tree[rt*2+2].sum;
}
void pushdown(int rt)
{ if(add[rt])
{
//tree[rt].sum=(tree[rt].r-tree[rt].l+1)*add[rt];
add[rt*2+1]+=add[rt];
add[rt*2+2]+=add[rt];
tree[rt*2+2].sum+=(tree[rt*2+2].r-tree[rt*2+2].l+1)*add[rt];
tree[rt*2+1].sum+=(tree[rt*2+1].r-tree[rt*2+1].l+1)*add[rt];
add[rt]=0;
}
}
void update(int l,int r,int z,int rt)
{
if(tree[rt].l>=l&&tree[rt].r<=r)
{
tree[rt].sum+=(tree[rt].r-tree[rt].l+1)*z;
add[rt]+=z;
return ;
}
pushdown(rt);
int mid=(tree[rt].r+tree[rt].l)/2;
if(l<=mid)
{
update(l,r,z,rt*2+1);
}
if(r>mid){
update(l,r,z,rt*2+2);
}
tree[rt].sum=tree[rt*2+2].sum+tree[rt*2+1].sum;
}
long long que(int l,int r,int rt)
{
if(tree[rt].l==l&&tree[rt].r==r)
{
return tree[rt].sum;
}
pushdown(rt);
long long res=0;
int mid=(tree[rt].l+tree[rt].r)/2;
if(r<=mid)
{
res+=que(l,r,rt*2+1);
}
else if(l>mid)
{
res+=que(l,r,rt*2+2);
}
else
{
res+=que(l,mid,rt*2+1);
res+=que(mid+1,r,rt*2+2);
}
return res;
}
int main()
{
int n,q;
while(~scanf("%d%d", &n,&q))
{
memset(tree,0,sizeof(tree));
build(1,n,0);
/*for(int i=0;i<=n;i++)
{
printf("%d\n", tree[i].l);
}*/
char ch[5];
long long x,y,z;
while(q--)
{
scanf("%s", ch);
if(ch[0]=='C')
{
scanf("%lld%lld%lld", &x,&y,&z);
update(x,y,z,0);
}
else
{
scanf("%lld%lld", &x,&y);
long long f=que(x,y,0);
printf("%lld\n", f);
}
}
}
}
线段树区间求和模板
最新推荐文章于 2021-04-17 17:24:53 发布