树状数组是一种支持高效前缀查询的数据结构,基本构造如下:
每个节点存在一个数组里,对应一个固定的编号,并且有固定的区间长度,节点长度与lowbit有关。
以下为树状数组基础应用:单点修改+高效前缀和查询。
基础建树(和单点修改是同一个函数):
const int maxn=1e5+7;
int tr[maxn];//树状数组
int n;
int lowbit(int x){
return x&(-x);
}
void update(int x,int d){
while(x<=n){
tr[x]+=d;
x+=lowbit(x);
}
}
区间查询:
int query(int d){
int res=0;
while(d){
res+=tr[d];
d-=lowbit(d);
}
return res;
}