模板自用,可读性较低
maybe 以后开文章讲(咕咕)
1.单点修改,区间查询
最经典的树状数组
int lowbit(int x) {
return x & (-x);
}
void Add(int index, int val) {
while (index <= n) {
C[index] += val;
index += lowbit(index);
}
return;
}
int Sum(int r) {
if (r == 0)
return 0;
int ret = 0;
while (r) {
ret += C[r];
r -= lowbit(r);
}
return ret;
}
int main() {
return 0;
}
2.区间修改,单点查询
利用到差分的思想,区间[l,r]增加v相当于 差分数组Tree[l]+=v,Tree[r+1]+=-v;
单点查询则是[1,index]的区间和
int lowbit(int x) {
return x & -x;
}
void Add(int index, int val) {
for (; index <= n; index += lowbit(index))
Tree[index] += val;
return;
}
int Sum(int index) {
int ret = 0;
while (index > 0) {
ret += Tree[index];
index -= lowbit(index);
}
return ret;
}
int main() {
Add(x,v);
Add(y+1,-v);
// 区间修改 x,y 增加v
Sum(x);
// 单点查询x
return 0;
}