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.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4
Sample Output
4 55 9 15
Hint
The sums may exceed the range of 32-bit integers.
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
struct node
{
int l,r;
__int64 sum;
}tree[100000000];
__int64 add[1000090];
void pushdown(int rate,int m)//lazy区间向下更新,m是区间范围,rate是当前节点
{
if(add[rate])
{
add[rate<<1]+=add[rate];
add[rate<<1|1]+=add[rate];
tree[rate<<1].sum+=add[rate]*(m-(m>>1));
tree[rate<<1|1].sum+=add[rate]*(m>>1);
add[rate]=0;
}
}
void update(int l,int r,int w,int rate)//lazy区间更新,l为左端点r为右端点,w为区间内每个元素增加的值,rate为当前节点
{
if(tree[rate].l==l&&tree[rate].r==r)//lazy思想
{
add[rate]+=w;
tree[rate].sum+=(__int64)w*(r-l+1);
return ;
}
if(tree[rate].l==tree[rate].r) return ;
pushdown(rate,tree[rate].r-tree[rate].l+1);
int mid=((tree[rate].l+tree[rate].r)>>1);
if(r<=mid)update(l,r,w,rate<<1);
else if(l>mid)update(l,r,w,rate<<1|1);
else
{
update(l,mid,w,rate<<1);
update(mid+1,r,w,rate<<1|1);
}
tree[rate].sum=tree[rate<<1].sum+tree[rate<<1|1].sum;
}
__int64 Sum(int l,int r,int rate)//区间求和
{
if(l==tree[rate].l&&r==tree[rate].r)
{
return tree[rate].sum;
}
pushdown(rate,tree[rate].r-tree[rate].l+1);
int mid=(tree[rate].l+tree[rate].r)>>1;
__int64 ans=0;
if(r<=mid) ans+=Sum(l,r,rate<<1);
else if(l>mid)ans+=Sum(l,r,rate<<1|1);
else
{
ans+=Sum(l,mid,rate<<1);
ans+=Sum(mid+1,r,rate<<1|1);
}
return ans;
}
void build(int rate,int l,int r)
{
tree[rate].l=l;
tree[rate].r=r;
if(l==r)
{
scanf("%I64d",&tree[rate].sum);
return ;
}
int mid=(l+r)>>1;
build(rate<<1,l,mid);
build(rate<<1|1,mid+1,r);
tree[rate].sum=tree[rate<<1].sum+tree[rate<<1|1].sum;
}
int main()
{
int n,q,j,l,r,w;
char c;
scanf("%d %d",&n,&q);
build(1,1,n);
for(j=1;j<=q;j++)
{
getchar();
scanf("%c %d %d",&c,&l,&r);
if(c=='C')
{
scanf("%d",&w);
update(l,r,w,1);
}
else
{
printf("%I64d\n",Sum(l,r,1));
}
}
return 0;
}