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
Hint
Source
经典的线段树题,在节点中增加一个add变量,记录该区间内所有点都增加的值,即可做到在O( log n ) 内做到区间更新。
#include <iostream>
#include <cstdio>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define INF 0x3f3f3f3f
#define LL __int64
LL v;
int a,b;
struct node{
int l,r;
LL sum,add;
int mid(){
return (l+r)/2;
}
};
node tree[400005];
void buildtree(int root,int l,int r)
{
tree[root].l=l;
tree[root].r=r;
tree[root].sum=tree[root].add=0;
if(l!=r){
buildtree(2*root+1,l,(l+r)/2);
buildtree(2*root+2,(l+r)/2+1,r);
}
}
void vinsert(int root,int i,LL v)
{
if(tree[root].l==tree[root].r){
tree[root].sum=v;
return;
}
tree[root].sum+=v;
if(i<=tree[root].mid()){
vinsert(2*root+1,i,v);
}else{
vinsert(2*root+2,i,v);
}
}
void update(int root,int a,int b,LL v)
{
if(tree[root].l==a&&tree[root].r==b){
tree[root].add+=v;
return;
}
tree[root].sum+=v*(b-a+1);
if(b<=tree[root].mid()){
update(2*root+1,a,b,v);
}else if(a>tree[root].mid()){
update(2*root+2,a,b,v);
}else{
update(2*root+1,a,tree[root].mid(),v);
update(2*root+2,tree[root].mid()+1,b,v);
}
}
LL answersearch(int root,int a,int b)
{
LL answer=0;
if(tree[root].l==a&&tree[root].r==b){
return tree[root].sum+tree[root].add*(b-a+1);
}
tree[root].sum+=tree[root].add*(tree[root].r-tree[root].l+1);
update(2*root+1,tree[root].l,tree[root].mid(),tree[root].add);
update(2*root+2,tree[root].mid()+1,tree[root].r,tree[root].add);
tree[root].add=0;
if(b<=tree[root].mid()){
return answersearch(2*root+1,a,b);
}else if(a>tree[root].mid()){
return answersearch(2*root+2,a,b);
}else{
return answersearch(2*root+1,a,tree[root].mid())+
answersearch(2*root+2,tree[root].mid()+1,b);
}
return answer;
}
int main()
{
int n,m;
char ch;
while(~scanf("%d%d",&n,&m)){
buildtree(0,1,n);
for(int i=1;i<=n;i++){
scanf("%I64d",&v);
vinsert(0,i,v);
}
while(m--){
getchar();
scanf("%c",&ch);
if(ch=='C'){
scanf("%d%d%I64d",&a,&b,&v);
update(0,a,b,v);
}else{
scanf("%d%d",&a,&b);
printf("%I64d\n",answersearch(0,a,b));
}
}
}
return 0;
}