分块技巧

分块优化树状数组操作.

$O(1)$单点修改, $O(\sqrt{n})$区间查询.

const int N = 1e6+10, S = 400;
int s1[N], s2[N];
void add(int x, int v) {
	s1[x] += v;
	s2[x/S] += v;
}
int qry(int x) {
	int ans = 0;
	for (int i=x/S*S; i<=x; ++i) ans+=s1[i];
	for (int i=x/S-1; i>=0; --i) ans+=s2[i];
	return ans;
}

$O(1)$单点查询, $O(\sqrt{n})$区间修改.

void add(int x, int v) {
	for (int i=x/S*S; i<=x; ++i) s1[i]+=v;
	for (int i=x/S-1; i>=0; --i) s2[i]+=v;
}
int qry(int x) {
	return s1[x]+s2[x/S];
}

 

posted @ 2019-07-28 22:06  uid001  阅读(138)  评论(0编辑  收藏  举报