这题做了我一整天,要好好记录一下!!
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.
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAXN 100000
__int64 num[MAXN];
struct node
{
int l,r;
__int64 sum,add;
}sum[MAXN*4+5];
void build(int L,int R,int rt)
{
sum[rt].l=L;
sum[rt].r=R;
sum[rt].add=0; //记录区间的增量,如果没有增量则为0
if(L==R)
{
sum[rt].sum=num[L];
return ;
}
int m=(sum[rt].l+sum[rt].r)/2;
build(L,m,rt*2);
build(m+1,R,rt*2+1);
sum[rt].sum=sum[rt*2].sum+sum[rt*2+1].sum;
}
__int64 quary(int l,int r,int rt)
{
if(sum[rt].l>=l&&sum[rt].r<=r)
{
return sum[rt].sum;
}
int m=(sum[rt].l+sum[rt].r)/2;
if(sum[rt].add!=0) //对有增量的区间进行处理,将增量传递给自己孩子的两个节点并对两个孩子的sum进行增加,把add传递
{
sum[rt*2].sum+=(m-sum[rt].l+1)*sum[rt].add;
sum[rt*2+1].sum+=(sum[rt].r-m)*sum[rt].add;
sum[rt*2].add+=sum[rt].add;
sum[rt*2+1].add+=sum[rt].add;
sum[rt].add=0;
}
__int64 k1=0,k2=0;
if(l<=m)
k1=quary(l,r,rt*2);
if(r>m)
k2=quary(l,r,rt*2+1);
return k1+k2;
}
void updata(int l,int r,__int64 v,int rt)
{
if(sum[rt].l>=l&&sum[rt].r<=r) //对符合条件的区间进行增加,并标记增加的量
{
sum[rt].add+=v;
sum[rt].sum+=(sum[rt].r-sum[rt].l+1)*v;
return ;
}
int m=(sum[rt].l+sum[rt].r)/2;
if(sum[rt].add!=0)
{
sum[rt*2].sum+=(m-sum[rt].l+1)*sum[rt].add;
sum[rt*2+1].sum+=(sum[rt].r-m)*sum[rt].add;
sum[rt*2].add+=sum[rt].add;
sum[rt*2+1].add+=sum[rt].add;
sum[rt].add=0;
}
if(l<=m)
updata(l,r,v,rt*2);
if(r>m)
updata(l,r,v,rt*2+1);
sum[rt].sum=sum[rt*2].sum+sum[rt*2+1].sum;
}
int main(){
int i,j,k,n,m;
int a,b;
__int64 c;
char cc[2];
while( scanf("%d%d",&n,&m) != EOF)
{
for(i=1;i<=n;i++)
{
scanf("%I64d",&num[i]);
}
build(1,n,1);
while(m--){
scanf("%s",cc);
switch(cc[0])
{
case 'Q':
scanf("%d%d",&a,&b);
getchar();
printf("%I64d\n",quary(a,b,1));
break;
case 'C':
scanf("%d%d%I64d",&a,&b,&c);
getchar();
updata(a,b,c,1);
break;
}
}
}
return 0;
}