线段树模板
向上回溯
void pushup(int rt){
t[rt].sum = t[lc].sum + t[rc].sum;
t[rt].mx = max(t[lc].mx, t[rc].mx);
}
建树
void build(int rt, int l, int r){
t[rt].l = l;
t[rt].r = r;
if(l == r){
t[rt].mx = t[rt].sum = a[l];
return;
}
int mid = (l + r) >> 1;
build(lc, l, mid);
build(rc, mid+1, r);
pushup(rt);
}
单点更新
void update(int rt, int pos, int w){
if(t[rt].l == t[rt].r){
t[rt].mx = t[rt].sum = w;
return;
}
int mid = (t[rt].l + t[rt].r) >> 1;
if(pos <= mid) update(lc, pos, w);
else update(rc, pos, w);
pushup(rt);
}
区间查询
int query(int rt, int l, int r){
if(l <= t[rt].l and t[rt].r <= r){
return t[rt].sum;
}
int mid = (t[rt].l + t[rt].r) >> 1;
int val = 0;
if(l <= mid) val += query(lc, l, r);
if(r > mid) val += query(rc, l, r);
return val;
}
延迟标记
void pushdown(int rt){
if(t[rt].lz){
int la = t[rt].lz;
t[rt].lz = 0;
t[lc].lz += la;
t[rc].lz += la;
t[lc].sum += la * (t[lc].r - t[lc].l + 1);
t[rc].sum += la * (t[rc].r - t[rc].l + 1);
}
}
区间更新
void update(int rt, int l, int r, int w){
if(l <= t[rt].l and t[rt].r <= r){
t[rt].lz += w;
t[rt].sum += w * (t[rt].r - t[rt].l + 1);
return;
}
pushdown(rt);
int mid = (t[rt].l + t[rt].r) >> 1;
if(l <= mid) update(lc, l, r, w);
if(r >= mid) update(rc, l, r, w);
pushup(rt);
}
带延迟标记区间查询
int query(int rt, int l, int r){
if(l <= t[rt].l and t[rt].r <= r){
return t[rt].sum;
}
pushdown(rt);
int mid = (t[rt].l + t[rt].r) >> 1;
int val = 0;
if(l <= mid) val += query(lc, l, r);
if(r > mid) val += query(rc, l, r);
return val;
}