You have N integers, A1, A2, … , AN. You need to deal with two kinds of operations.One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
日常做水题,调养身心(手动滑稽)。这道题我感觉难点在于看懂题面,如果你懂了,就会明白其实这道题就是一道线段树裸题。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
struct node
{
int l,r,lc,rc;
long long c,add;
}tr[210000];int trlen;
long long a[110000];
void bt(int l,int r)
{
trlen++;int now=trlen;
tr[now].l=l;tr[now].r=r;
tr[now].lc=tr[now].rc=-1;
tr[now].add=tr[now].c=0;
if(l==r)tr[now].c=a[l];
else
{
int mid=(l+r)/2;
tr[now].lc=trlen+1;bt(l,mid);
tr[now].rc=trlen+1;bt(mid+1,r);
tr[now].c=tr[tr[now].lc].c+tr[tr[now].rc].c;
}
}
void update(int now)
{
int lc=tr[now].lc,rc=tr[now].rc;
tr[lc].c+=(tr[lc].r-tr[lc].l+1)*tr[now].add;
tr[rc].c+=(tr[rc].r-tr[rc].l+1)*tr[now].add;
tr[lc].add+=tr[now].add;
tr[rc].add+=tr[now].add;
tr[now].add=0;
}
void add(int now,int l,int r,int k)
{
if(tr[now].l==l && tr[now].r==r){tr[now].c+=(tr[now].r-tr[now].l+1)*k;tr[now].add+=k;return ;}
int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2;
if(tr[now].add!=0)update(now);
if(r<=mid)add(lc,l,r,k);
else if(mid+1<=l)add(rc,l,r,k);
else add(lc,l,mid,k),add(rc,mid+1,r,k);
tr[now].c=tr[lc].c+tr[rc].c;
}
long long getsum(int now,int l,int r)
{
if(tr[now].l==l && tr[now].r==r)return tr[now].c;
int lc=tr[now].lc,rc=tr[now].rc,mid=(tr[now].l+tr[now].r)/2;
if(tr[now].add!=0)update(now);
if(r<=mid)return getsum(lc,l,r);
else if(mid+1<=l)return getsum(rc,l,r);
else return getsum(lc,l,mid)+getsum(rc,mid+1,r);
}
char s[5];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
trlen=0;bt(1,n);
while(m--)
{
int x,y,c;
scanf("%s%d%d",s+1,&x,&y);
if(s[1]=='Q')printf("%lld\n",getsum(1,x,y));
else{scanf("%d",&c);add(1,x,y,c);}
}
return 0;
}