ZTL — 数据结构 — 线段树
区间加区间求和
class SegmentTree{
private:
#define lson (x<<1)
#define rson ((x<<1)|1)
ll t[maxn<<2], tag[maxn<<2] /*lazy tag*/, cnt;
inline void pushup(int x){
t[x] = (t[lson] + t[rson]);
}
inline void pushdown(int x, int l, int r){
if(tag[x]){
int mid = (l+r)>>1;
t[lson] = (t[lson] + tag[x] * (mid-l+1));
t[rson] = (t[rson] + tag[x] * (r-mid));
tag[lson] = (tag[lson] + tag[x]);
tag[rson] = (tag[rson] + tag[x]);
tag[x] = 0;
pushup(x);
}
}
public:
void build(int x, int l, int r, int *a){
if(l == r){
t[x] = a[++cnt];
}else{
int mid = (l+r) >> 1;
build(lson, l, mid, a);
build(rson, mid+1, r, a);
pushup(x);
}
}
void update(int x, int l, int r, int ql, int qr, ll k){
if(ql <= l && r <= qr){
t[x] = (t[x] + (r-l+1)*k);
tag[x] = (tag[x] + k);
}else{
pushdown(x,l,r);
int mid = (l+r) >> 1;
if(ql <= mid) update(lson, l, mid, ql, qr, k);
if(qr > mid) update(rson, mid+1, r, ql, qr, k);
pushup(x);
}
}
ll query(int x, int l, int r, int ql, int qr){
if(ql <= l && r <= qr){
return t[x];
}else{
pushdown(x, l, r);
int mid = (l+r) >> 1; ll ret = 0;
if(ql <= mid) ret = (ret + query(lson, l, mid, ql, qr));
if(qr > mid) ret = (ret + query(rson, mid+1, r, ql, qr));
return ret;
}
}
#undef lson
#undef rson
}