#include <stdio.h>
struct node
{
int L,R; __int64 sum,inc;
};
node tree[500000];
void build(int k,int left, int right)
{
tree[k].L=left; tree[k].R=right; tree[k].sum=0; tree[k].inc=0;
if (left==right) return ;
int mid=(left+right) >> 1;
build(k << 1,left,mid); build((k << 1)+1,mid+1,right);
}
void insert(int k, int i, int v)
{
if (tree[k].L==i && tree[k].R==i)
{
tree[k].sum=v; return ;
}
tree[k].sum+=v;
int mid=(tree[k].L+tree[k].R) >> 1;
if (i<=mid)
insert(k << 1,i,v);
else
insert((k << 1)+1,i,v);
}
void add(int k, int a, int b, int c)
{
if (tree[k].L==a && tree[k].R==b)
{
tree[k].inc+=c; return ;
}
tree[k].sum+=(b-a+1)*c;
int mid=(tree[k].L+tree[k].R) >> 1;
if (b<=mid)
add(k << 1,a,b,c);
else
if (a>mid)
add((k << 1)+1,a,b,c);
else
{
add(k << 1,a,mid,c); add((k << 1)+1,mid+1,b,c);
}
}
__int64 query(int k, int a, int b)
{
if (tree[k].L==a && tree[k].R==b)
return tree[k].sum+(tree[k].R-tree[k].L+1)*tree[k].inc;
int mid=(tree[k].L+tree[k].R) >> 1;
tree[k].sum+=(tree[k].R-tree[k].L+1)*tree[k].inc;
add(k << 1,tree[k].L,mid,tree[k].inc);
add((k << 1)+1,mid+1,tree[k].R,tree[k].inc);
tree[k].inc=0;
if (b<=mid)
return query(k << 1,a,b);
else
if (a>mid)
return query((k << 1)+1,a,b);
else
return query(k << 1,a,mid)+query((k << 1)+1,mid+1,b);
}
int main()
{
int n,Q;
scanf("%d%d",&n,&Q);
build(1,1,n);
for (int i=1; i<=n; i++)
{
int tmp;
scanf("%d",&tmp);
insert(1,i,tmp);
}
for (int i=1; i<=Q; i++)
{
char q[10];
scanf("%s",&q);
if (q[0]=='Q')
{
int a,b;
scanf("%d%d",&a,&b);
printf("%I64d\n",query(1,a,b));
}
else
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(1,a,b,c);
}
}
return 0;
}
3468 A Simple Problem with Integers 线段树
最新推荐文章于 2020-05-15 23:49:15 发布