解题思路:线段树裸题。但有个地方苦恼了一下。最后这个ans必须得长整型才行。
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
struct node
{
int l,r;
ll w,sum;
}s[400009];
int p[100009];
int n,m;
ll ans;
void build(int t,int l,int r)
{
s[t].l=l;s[t].r=r;s[t].w=0;
if(s[t].l==s[t].r)
{
s[t].sum=p[l];
return;
}
build(2*t,l,(l+r)/2);
build(2*t+1,(l+r)/2+1,r);
s[t].sum=s[2*t].sum+s[2*t+1].sum;
}
void query(int t,int l,int r)
{
if(s[t].l==l&&s[t].r==r)
{
ans+=s[t].sum;
return;
}
int mid=(s[t].l+s[t].r)/2;
if(s[t].w)
{
s[2*t].sum+=s[t].w*(s[2*t].r-s[2*t].l+1);
s[2*t+1].sum+=s[t].w*(s[2*t+1].r-s[2*t+1].l+1);
s[2*t].w+=s[t].w;
s[2*t+1].w+=s[t].w;
s[t].w=0;
}
if(r<=mid)
{
query(2*t,l,r);
}else
if(l>mid)
{
query(2*t+1,l,r);
}else
{
query(2*t,l,mid);
query(2*t+1,mid+1,r);
}
}
void update(int t,int l,int r,int w)
{
if(s[t].l==l&&s[t].r==r)
{
s[t].sum+=w*(s[t].r-s[t].l+1);
s[t].w+=w;
return;
}
if(s[t].w)
{
s[2*t].sum+=s[t].w*(s[2*t].r-s[2*t].l+1);
s[2*t+1].sum+=s[t].w*(s[2*t+1].r-s[2*t+1].l+1);
s[2*t].w+=s[t].w;
s[2*t+1].w+=s[t].w;
s[t].w=0;
}
int mid=(s[t].l+s[t].r)/2;
if(r<=mid)
update(2*t,l,r,w);
else
if(l>mid)
update(2*t+1,l,r,w);
else
{
update(2*t,l,mid,w);
update(2*t+1,mid+1,r,w);
}
s[t].sum=s[2*t].sum+s[2*t+1].sum;
}
int main()
{
//freopen("t.txt","r",stdin);
char tp;
int a,b,c;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&p[i]);
}
build(1,1,n);
while(m--)
{
getchar();
scanf("%c",&tp);
if(tp=='Q')
{
scanf("%d%d",&a,&b);
ans=0;
query(1,a,b);
printf("%lld\n",ans);
}else
if(tp=='C')
{
scanf("%d%d%d",&a,&b,&c);
update(1,a,b,c);
}
}
}
return 0;
}