来源:POJ
标签:数据结构,线段树,区间修改
参考资料:
相似题目:
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.
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.
You need to answer all Q commands in order. One answer in a line.
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
4
55
9
15
#include
#include
#define MAXN 100005
using namespace std;
struct SegTreeNode{
long long val;
long long addMark;
}segTree[MAXN*4];
void build(int root, int arr[], int begin, int end){
segTree[root].addMark=0;
if(begin==end){
segTree[root].val=arr[begin];
}
else{
int mid=(begin+end)/2;
build(root*2+1,arr,begin,mid);
build(root*2+2,arr,mid+1,end);
segTree[root].val=segTree[root*2+1].val+segTree[root*2+2].val;
}
}
void pushDown(int root,int begin,int end){
if(segTree[root].addMark!=0){
segTree[root*2+1].addMark+=segTree[root].addMark;
segTree[root*2+2].addMark+=segTree[root].addMark;
segTree[root*2+1].val+=((begin+end)/2-begin+1)*segTree[root].addMark;
segTree[root*2+2].val+=(end-(begin+end)/2)*segTree[root].addMark;
segTree[root].addMark=0;
}
}
long long query(int root, int begin, int end, int L, int R){
if(L>end || R<begin) return 0;
if(L<=begin && R>=end) return segTree[root].val;
pushDown(root,begin,end);
int mid=(begin+end)/2;
return query(root*2+1, begin, mid, L, R)+query(root*2+2, mid+1, end, L, R);
}
void update(int root, int begin, int end, int L, int R, int addVal){
if(L>end || R<begin){
return;
}
if(L<=begin && R>=end){
segTree[root].addMark+=addVal;
segTree[root].val+=(end-begin+1)*addVal;
return;
}
pushDown(root,begin,end);
int mid=(begin+end)/2;
update(root*2+1, begin, mid, L, R, addVal);
update(root*2+2, mid+1, end, L, R, addVal);
segTree[root].val=segTree[root*2+1].val+segTree[root*2+2].val;
}
int main(){
int N,Q;
while(scanf("%d%d",&N,&Q)!=EOF){
int arr[MAXN];
for(int i=0;i<N;i++){
scanf("%d",&arr[i]);
}
build(0,arr,0,N-1);
int a,b,c;
char s[5];
for(int i=0;i<Q;i++){
scanf("%s",s);
if(s[0]=='Q'){
scanf("%d%d",&a,&b);
printf("%lld\n",query(0,0,N-1,a-1,b-1));
}
else{
scanf("%d%d%d",&a,&b,&c);
update(0,0,N-1,a-1,b-1,c);
}
}
}
return 0;
}