线段树是一种维护区间和等功能的数据结构
struct SegTree{
struct node{
int l,r,sum,len,laz;
}tree[N<<2];
inline void pushdown(int u){
int lson=u<<1,rson=lson|1;
tree[lson].laz+=tree[u].laz;
tree[rson].laz+=tree[u].laz;
tree[lson].sum+=tree[lson].len*tree[u].laz;
tree[rson].sum+=tree[rson].len*tree[u].laz;
tree[lson].sum%=mod;
tree[rson].sum%=mod;
tree[u].laz=0;
}
void build(int u,int l,int r,int w[]){
tree[u].l=l,tree[u].r=r,tree[u].len=r-l+1,tree[u].sum=tree[u].laz=0;
if(l==r){
tree[u].sum=w[u];
if(tree[u].sum>=mod)tree[u].sum%=mod;
return;
}
int mid=(l+r)>>1,lson=u<<1,rson=lson|1;
build(lson,l,mid,w);
build(rson,mid+1,r,w);
tree[u].sum=(tree[lson].sum+tree[rson].sum)%mod;
}
void update(int u,int l,int r,int k){
if(l<=tree[u].l&&tree[u].r<=r){
tree[u].laz+=k;
tree[u].sum+=k*tree[u].len;
}
else{
if(tree[u].laz)pushdown(u);
int mid=(tree[u].l+tree[u].r)>>1,lson=u<<1,rson=lson|1;
if(l<=mid)update(lson,l,r,k);
if(r>mid)update(rson,l,r,k);
tree[u].sum=(tree[lson].sum+tree[rson].sum)%mod;
}
}
int query(int u,int l,int r){
if(l<=tree[u].l && r<=tree[u].r){
return tree[u].sum;
}
else{
int res=0,mid=(tree[u].l+tree[u].r)>>1,lson=u<<1,rson=lson|1;
if(tree[u].laz)pushdown(u);
if(l<=mid)res=(res+query(lson,l,r))%mod;
if(r>mid)res=(res+query(rson,l,r))%mod;
}
}
}tr;
标签:树结构,int,线段,tree,lson,rson,sum,模板,mod
From: https://www.cnblogs.com/wanxue/p/18213690