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.
题解
Change:对更新区间标记add,对他们的父亲节点加上儿子的增量和
Query :返回查询区间的sum+(r-l+1)*add
区间乘也可以类似这样写
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#define INF 0x3f3f3f3f
#define MAX_N 100002
using namespace std;
typedef long long LL;
struct LazyTag{int add;};
struct node{LL sum,add;};
node dat[MAX_N*3];
int res[MAX_N];
void PutTag(int k,LazyTag x){dat[k].add+=x.add;};
LL init(int k,int l,int r){
if(l==r) return dat[k].sum=res[l];
int mid=l+r>>1;
return dat[k].sum=init(k*2,l,mid)+init(k*2+1,mid+1,r);
}
void Change(int k,int l,int r,int ql,int qr,LazyTag x){
if(ql>r||qr<l) return ;
if(ql<=l&&qr>=r){
PutTag(k,x); return ;
}
int mid=l+r>>1;
Change(k*2,l,mid,ql,qr,x);
Change(k*2+1,mid+1,r,ql,qr,x);
dat[k].sum+=(min(r,qr)-max(l,ql)+1)*x.add;
}
LL Query(int k,int l,int r,int ql,int qr){
if(ql>r||qr<l) return 0;
if(ql<=l&&qr>=r) return dat[k].sum+dat[k].add*(r-l+1);
int mid=l+r>>1;
return Query(k*2,l,mid,ql,qr)+Query(k*2+1,mid+1,r,ql,qr)+dat[k].add*(min(r,qr)-max(l,ql)+1);
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&res[i]);
init(1,1,n);
int r,l;LazyTag t;char op;
while(m--){
getchar();
scanf("%c%d%d",&op,&r,&l);
if(op=='Q') printf("%lld\n",Query(1,1,n,r,l));
else{
scanf("%d",&t.add);
Change(1,1,n,r,l,t);
}
}
return 0;
}