全裸线段树。
写此篇主要是太久没写线段树,贴个模板备忘。
#include <iostream>
#include <cstdio>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N=100005;
typedef long long LL;
LL Sum[N<<2],Add[N<<2];
void pushUp(int rt)
{
Sum[rt]=Sum[rt<<1]+Sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
Add[rt]=0;
if(l==r)
{
scanf("%lld",&Sum[rt]);
return ;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushUp(rt);
}
void pushDown(int rt,int len)
{
if(Add[rt])
{
Add[rt<<1]+=Add[rt];
Add[rt<<1|1]+=Add[rt];
Sum[rt<<1]+=((len+1)>>1)*Add[rt];
Sum[rt<<1|1]+=(len>>1)*Add[rt];
Add[rt]=0;
}
}
LL query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
return Sum[rt];
pushDown(rt,r-l+1);
int m=(l+r)>>1;
LL ret=0;
if(R<=m)
ret=query(L,R,lson);
else if(L>m)
ret=query(L,R,rson);
else
ret=query(L,R,lson)+query(L,R,rson);
return ret;
}
void update(int L,int R,LL add,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
Sum[rt]+=(r-l+1)*add;
Add[rt]+=add;
return ;
}
int m=(l+r)>>1;
pushDown(rt,r-l+1);
if(L<=m)
update(L,R,add,lson);
if(m<R)
update(L,R,add,rson);
pushUp(rt);
}
int main()
{
// freopen("in","r",stdin);
int n,q;
scanf("%d%d",&n,&q);
build(1,n,1);
char op[5];
int a,b;
LL c;
while(q--)
{
scanf("%s",op);
if(op[0]=='Q')
{
scanf("%d%d",&a,&b);
printf("%lld\n",query(a,b,1,n,1));
}
else
{
scanf("%d%d%lld",&a,&b,&c);
update(a,b,c,1,n,1);
}
}
return 0;
}