典型的线段树题目,插线问线,求区间和。注意中间会超int范围
题目:
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 29416 | Accepted: 8241 | |
Case Time Limit: 2000MS |
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 15ac代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int N=100010;
struct tree{
int left,right;
long long add,sum;
}tt[N*4];
int num[N];
void built_tree(int lp,int rp,int pos){
tt[pos].left=lp;
tt[pos].right=rp;
tt[pos].add=0;
if(lp==rp){
tt[pos].sum=num[lp];
return;
}
int mid=(tt[pos].left+tt[pos].right)/2;
built_tree(lp,mid,pos*2);
built_tree(mid+1,rp,pos*2+1);
tt[pos].sum=tt[pos*2].sum+tt[pos*2+1].sum;
}
void update(int lp,int rp,int add,int pos){
if(lp<=tt[pos].left&&rp>=tt[pos].right){
tt[pos].add+=add;
tt[pos].sum+=(tt[pos].right-tt[pos].left+1)*add;
return;
}
if(tt[pos].add){
tt[pos*2].sum+=(tt[pos*2].right-tt[pos*2].left+1)*tt[pos].add;
tt[pos*2+1].sum+=(tt[pos*2+1].right-tt[pos*2+1].left+1)*tt[pos].add;
tt[pos*2].add+=tt[pos].add;
tt[pos*2+1].add+=tt[pos].add;
tt[pos].add=0;
}
int mid=(tt[pos].right+tt[pos].left)/2;
if(lp<=mid)
update(lp,rp,add,pos*2);
if(rp>mid)
update(lp,rp,add,pos*2+1);
tt[pos].sum=tt[pos*2].sum+tt[pos*2+1].sum;
}
long long find(int lp,int rp,int pos){
if(lp==tt[pos].left&&rp==tt[pos].right)
return tt[pos].sum;
if(tt[pos].add){
tt[pos*2].sum+=(tt[pos*2].right-tt[pos*2].left+1)*tt[pos].add;
tt[pos*2+1].sum+=(tt[pos*2+1].right-tt[pos*2+1].left+1)*tt[pos].add;
tt[pos*2].add+=tt[pos].add;
tt[pos*2+1].add+=tt[pos].add;
tt[pos].add=0;
}
int mid=(tt[pos].left+tt[pos].right)/2;
if(lp>mid)
return find(lp,rp,pos*2+1);
else if(rp<=mid)
return find(lp,rp,pos*2);
else
return find(lp,mid,pos*2)+find(mid+1,rp,pos*2+1);
}
int main(){
int n,m;
while(~scanf("%d%d",&n,&m)){
for(int i=1;i<=n;++i)
scanf("%d",&num[i]);
built_tree(1,n,1);
char ss[2];
int x,y,z;
while(m--){
scanf("%s",ss);
if(ss[0]=='C'){
scanf("%d%d%d",&x,&y,&z);
update(x,y,z,1);
}
else{
scanf("%d%d",&x,&y);
long long total=find(x,y,1);
printf("%lld\n",total);
}
}
}
return 0;
}