跳到正文

算法·理论

树状数组快速清空

__xzm__约 1 分钟
原文
文章信息与版本

文章信息

发布
2023年10月5日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 1 分钟
获赞
1

版本

  1. v1当前

1.1.不要每次memsetmemset oror clearclear,这样O(logn)O(logn)变成O(n)O(n)

2.2.不要把所有操作重新反过来做一遍,这样时间变成两倍


正确方法:记录每个节点的时间戳,表示这个节点最后一次修改的版本

代码:

C++
int c[N], ts[N], tim;

int lowbit(int x) {
	return (x & (-x));
}

void add(int x, int v) {
	for (; x <= n; x += lowbit(x)) {
		if (ts[x] != tim) ts[x] = tim, c[x] = 0;
		c[x] += v;
	}
}

int query(int x) {
	int res = 0;
	for (; x; x -= lowbit(x)) {
		if (ts[x] == tim) res += c[x];
	}
	return res;
}

void clear() {
	tim++;
}
原文