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
注意:sum数组以及ans都需要使用__int64型。
AC代码:
#include<stdio.h>
#include<iostream>
using namespace std;
typedef __int64 ll;
const int maxn=1e5+5;
int s[maxn];
ll sum[4*maxn]; //最好设置4倍的大小,具体为什么可以根据树深及书的节点个数大致求得
ll lazy[maxn*4];
void pushup(int id){
sum[id]=sum[id*2]+sum[id*2+1]; //更新节点的值
}
void pushdown(int id,int len){ //将lazy向下推
if(lazy[id]){ //如果该节点是被标记过的,才可以向下改变其它节点
lazy[id*2]+=lazy[id]; //标记左孩子
lazy[id*2+1]+=lazy[id]; //标记右孩子
sum[id*2]+=lazy[id]*(len-(len/2)); //更新左孩子节点的值
sum[id*2+1]+=lazy[id]*(len/2); //更新右孩子节点的值
lazy[id]=0; //将其lazy标记取消
}
}
ll query(int L,int R,int l,int r,int id){ //区间查询
if(l<=L&&r>=R)
return sum[id];
pushdown(id,R-L+1);
int m=(L+R)/2;
ll ans=0; //注意ans的大小
if(l<=m)
ans+=query(L,m,l,r,id*2);
if(r>=m+1)
ans+=query(m+1,R,l,r,id*2+1);
return ans;
}
void update(int L,int R,int c,int l,int r,int id){ //更新区间的各个节点
if(l<=L&&r>=R){ //若该节点被需要修改区间完全覆盖
lazy[id]+=c; //设置lazy标记
sum[id]+=c*(R-L+1); //并且更新节点的值,为区间内数的个数乘以要加的大小
return ;
}
int m=(L+R)/2;
pushdown(id,R-L+1);
if(l<=m)
update(L,m,c,l,r,id*2);
if(r>=m+1)
update(m+1,R,c,l,r,id*2+1);
pushup(id);
}
void build(int L,int R,int id){ //建立树
lazy[id]=0; //将所有lazy标记初始化为0
if(L==R){
sum[id]=s[L];
return ;
}
int m=(L+R)/2;
build(L,m,id*2);
build(m+1,R,id*2+1);
pushup(id); //求节点的值
}
int main()
{
int n,q;
char w;
int a,b,c;
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%d",&s[i]);
build(1,n,1);
while(q--){
scanf("\n"); //消除换行带来的影响
scanf("%c",&w);
if(w=='Q'){
scanf("%d%d",&a,&b);
printf("%I64d\n",query(1,n,a,b,1));
}
else if(w=='C'){
scanf("%d%d%d",&a,&b,&c);
update(1,n,c,a,b,1);
}
}
return 0;
}