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
The sums may exceed the range of 32-bit integers.
这道题是一个线段树,要求区间加和区间求和,注意HINT是说答案可能超过int,下面是程序:
#include<stdio.h>
#include<iostream>
#define ll long long
#define ci const int
using namespace std;
const int N=100005;
struct treenode{
int lc,rc;
ll w,c;
treenode(){
w=c=lc=rc=0;
}
};
struct Segment_tree{
treenode t[N<<2];
int k;
Segment_tree(){
k=1;
}
void build(ci rt,ci l,ci r){
if(l==r){
scanf("%lld",&t[rt].w);
return;
}
ci m=l+r>>1;
build(t[rt].lc=++k,l,m);
build(t[rt].rc=++k,m+1,r);
t[rt].w=t[t[rt].lc].w+t[t[rt].rc].w;
}
void add(ci rt,ci l,ci r,ci a,ci b,ci w){
t[rt].w+=(b-a+1)*w;
if(l==a&&r==b){
t[rt].c+=w;
return;
}
ci m=l+r>>1;
if(b<=m){
add(t[rt].lc,l,m,a,b,w);
}
else{
if(a>m){
add(t[rt].rc,m+1,r,a,b,w);
}
else{
add(t[rt].lc,l,m,a,m,w);
add(t[rt].rc,m+1,r,m+1,b,w);
}
}
}
ll ask(ci rt,ci l,ci r,ci a,ci b,const ll c){
if(l==a&&r==b){
return t[rt].w+c*(r-l+1);
}
ci m=l+r>>1;
if(b<=m){
return ask(t[rt].lc,l,m,a,b,c+t[rt].c);
}
if(a>m){
return ask(t[rt].rc,m+1,r,a,b,c+t[rt].c);
}
return ask(t[rt].lc,l,m,a,m,c+t[rt].c)+ask(t[rt].rc,m+1,r,m+1,b,c+t[rt].c);
}
}t;
inline char ch(){
char c=getchar();
while(c!='Q'&&c!='C'){
c=getchar();
}
return c;
}
int main(){
int n,q,l,r;
ll w;
scanf("%d%d",&n,&q);
t.build(1,1,n);
while(q--){
if(ch()=='C'){
scanf("%d%d%lld",&l,&r,&w);
t.add(1,1,n,l,r,w);
}
else{
scanf("%d%d",&l,&r);
printf("%lld\n",t.ask(1,1,n,l,r,0));
}
}
return 0;
}