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;
}
本文介绍了一种使用懒惰传播的方法来高效处理区间加法及区间求和查询的问题。通过构建区间树并应用懒惰标记技术,可以实现O(log N)的时间复杂度下完成更新和查询操作。文章提供了完整的代码实现,并解释了关键步骤。

被折叠的 条评论
为什么被折叠?



