数据结构-线段树(区修区查)
前置知识
思路
因为修改变为了区间修改,所以显然多次单点修改会达到
n
2
log
n
n^2\log n
n2logn 的复杂度,TLE。
考虑类似区间查询 ,仅仅对一定节点进行修改,修改后为了使得子节点也获得修改的信息,考虑对该节点打一个
tag
\text{tag}
tag,查询时需要向子节点传递(
pushdown
\text{pushdown}
pushdown)。
对于最小值线段树,记录区间加的值,因为区间加相当于最小值加。
数据结构参数
- 时间复杂度: O ( n log n ) O(n\log n) O(nlogn)
- 空间复杂度: O ( n ) O(n) O(n)
实现代码
int t[MAXN*4],tag[MAXN*4];
#define ls p<<1
#define rs p<<1|1
void pushup(int p){
t[p]=min(t[ls],t[rs]);
}
void pushdown(int p){
if (tag[p]){
tag[ls]+=tag[p];
t[ls]+=tag[p];
tag[rs]+=tag[p];
t[rs]+=tag[p];
tag[p]=0;
}
}
void build(int p,int l,int r){
if (l==r){
t[p]=a[l];
return;
}
int mid=l+r>>1;
build(ls,l,mid);
build(rs,mid+1,r);
pushup(p);
}
void update(int p,int l,int r,int x,int y,int z){
if (x<=l&&r<=y){
tag[p]+=z;
t[p]+=z;
return;
}
pushdown(p);
int mid=l+r>>1;
if (x<=mid) update(ls,l,mid,x,y);
if (y>mid) update(rs,mid+1,r,x,y);
pushup(p);
}
int query(int p,int l,int r,int x,int y){
if (x<=l&&r<=y) return t[p];
pushdown(p);
int mid=l+r>>1,ans=0x3f3f3f3f;
if (x<=l) ans=min(ans,query(ls,l,mid,x,y));
else ans=min(ans,query(rs,mid+1,r,x,y));
return ans;
}