Description
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
#include <iostream>
#include <cstdio>
using namespace std;
#define LL long long
#define lson rt<<1,first,mid
#define rson rt<<1 | 1,mid+1,end
const int maxn=;
LL tree[maxn<<];
LL add[maxn<<];
void push_up(int rt)
{
tree[rt]=tree[rt<<]+tree[rt<< | ];
}
void push_down(int rt,int m) //更新子节点的数值
{
if(add[rt])
{
add[rt<<]+=add[rt];
add[rt<<|]+=add[rt];
tree[rt<<]+=add[rt]*(m-(m>>));
tree[rt<<|]+=add[rt]*(m>>);
add[rt]=; //更新后需要还原
}
}
void build(int rt,int first,int end)
{
add[rt]=;
if(first==end)
{
scanf("%lld",&tree[rt]);
//cin>>tree[rt];
return ;
}
int mid=(first+end)>>;
build(lson);
build(rson);
push_up(rt);
return ;
}
LL query(int rt,int first,int end,int a,int b) //求区间和
{
if(first>=a&&end<=b)
return tree[rt];
push_down(rt,end-first+);
LL sum=;
int mid=(first+end)>>;
if(a<=mid)
sum+=query(lson,a,b);
if(b>mid)
sum+=query(rson,a,b);
return sum;
}
void update(int rt,int first,int end,int a,int b,int c)
{
if(first>=a&&end<=b)
{
add[rt]+=c;
tree[rt]+=(LL)c*(end-first+);
return ;
}
push_down(rt,end-first+);
int mid=(first+end)>>;
if(a<=mid)
update(lson,a,b,c);
if(b>mid)
update(rson,a,b,c);
push_up(rt);
return ;
}
int main()
{
int n,q;
char ch[];
int a,b,c;
scanf("%d%d",&n,&q);
//cin>>n>>q;
build(,,n);
while(q--)
{
scanf("%s",ch);
//cin>>ch;
if(ch[]=='Q')
{
scanf("%d%d",&a,&b);
printf("%lld\n",query(,,n,a,b));
//cin>>a>>b;
//cout<<query(1,1,n,a,b)<<endl;
}
if(ch[]=='C')
{
scanf("%d%d%d",&a,&b,&c);
//cin>>a>>b>>c;
update(,,n,a,b,c);
}
}
return ;
}