线段树区间更新求和
#include <map>
#include <set>
#include <list>
#include <cmath>
#include<cctype>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define PI 3.1415926535897932626
using namespace std;
int gcd(int a, int b)
{
return a % b == 0 ? b : gcd(b, a % b);
}
#define MAXN 100003
struct node
{
int l,r;
LL sum;
LL mark;//延时标记
}tree[MAXN*4];
LL src[MAXN];
void buildtree(int id,int l ,int r)
{
tree[id].l=l;tree[id].r=r;
tree[id].mark=0;
if (l==r)
{
tree[id].sum=src[l];
return ;
}
int m=(l+r)/2;
buildtree(id*2,l,m);
buildtree(id*2+1,m+1,r);
tree[id].sum=tree[id*2].sum+tree[id*2+1].sum;
}
void update(int id ,int l ,int r,LL val)
{
if (tree[id].l==l && tree[id].r==r)
{
tree[id].mark+=val;
return ;
}
tree[id].sum+=(r-l+1)*val;
int m=(tree[id].l+tree[id].r)/2;
if (l>m)
update(id*2+1,l,r,val);
else if (r<=m)
update(id*2,l,r,val);
else
{
update(id*2,l,m,val);
update(id*2+1,m+1,r,val);
}
}
LL query(int id ,int l ,int r)
{
if (tree[id].l==l && tree[id].r==r)
{
return tree[id].sum+tree[id].mark*(r-l+1);//这里不更新这个节点的sum,延时标记也不变
}
if (tree[id].mark!=0)
{
tree[id*2].mark+=tree[id].mark;
tree[id*2+1].mark+=tree[id].mark;
tree[id].sum+=tree[id].mark*(tree[id].r-tree[id].l+1);
tree[id].mark=0;//清空延时标记,
}
int m=(tree[id].l+tree[id].r)/2;
if (l>m)
return query(id*2+1,l,r);
else if (r<=m)
return query(id*2,l,r);
else
return query(id*2,l,m)+query(id*2+1,m+1,r);
}
int main()
{
int N,M;
scanf("%d%d",&N,&M);
for (int i=1;i<=N;i++)
scanf("%lld",&src[i]);
buildtree(1,1,N);
char input[3];int a,b;LL c;
for (int i=0;i<M;i++)
{
scanf("%s",input);
if (input[0]=='Q')
{
scanf("%d%d%*c",&a,&b);
//printf("%d %d\n",a,b);
printf("%lld\n",query(1,a,b));
}
else
{
scanf("%d%d%lld%*c",&a,&b,&c);
update(1,a,b,c);
}
}
return 0;
}