1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
| struct Segment_tree{
#define fa tree[p]
#define lson tree[p<<1]
#define rson tree[p<<1|1]
struct node{
int l,r;
LL add;//懒标记
LL sum;
int len(){return r-l+1;}
}tree[M<<2];
void up(int p){
fa.sum=lson.sum+rson.sum;
}
void down(int p){
if(fa.add==0)return;
lson.add+=fa.add;
lson.sum+=fa.add*lson.len();
rson.add+=fa.add;
rson.sum+=fa.add*rson.len();
fa.add=0;
}
void build(int l,int r,int p){
fa.l=l;fa.r=r;fa.sum=fa.add=0;
if(l==r){fa.sum=A[l];return;}
int mid=(l+r)>>1;
build(l,mid,p<<1);
build(mid+1,r,p<<1|1);
up(p);
}
void update(int l,int r,LL d,int p){
if(fa.l==l&&fa.r==r){
fa.sum+=1LL*fa.len()*d;
fa.add+=d;
return;
}
int mid=(fa.l+fa.r)>>1;
down(p);
if(r<=mid)update(l,r,d,p<<1);
else if(l>mid)update(l,r,d,p<<1|1);
else {
update(l,mid,d,p<<1);
update(mid+1,r,d,p<<1|1);
}
up(p);
}
LL query(int l,int r,int p){
if(fa.l==l&&fa.r==r)return fa.sum;
down(p);
int mid=(fa.l+fa.r)>>1;
if(r<=mid)return query(l,r,p<<1);
else if(l>mid)return query(l,r,p<<1|1);
return query(l,mid,p<<1)+query(mid+1,r,p<<1|1);
}
}T;
//区间加减,区间查询和,单次操作复杂度均为O(logn)
//可实现的变种:区间乘积,区间染色问题等等。
|