Revision of Lazy Operations

Basic Method

The basic method of Lazy Operations is to decrease the necessary recursing depth of update and query.
Evidently, when we query or update a whole section, we do not care about the specific changes happening inside of it. We just need the general data status reflected on the father node representing this whole section.

Specific Realization

For additional lazy marks:

// 20211211 Luogu P2357
void pushdown(int u, int l, int r){
	if(!lazy[u])
		return;
	int mid = l + r >> 1;
	t[u << 1] += (mid - l + 1) * lazy[u];
	t[u << 1 | 1] += (r - mid) * lazy[u];
	lazy[u << 1] += lazy[u]; // Caution: additional mark adds
	lazy[u << 1 | 1] += lazy[u];
	lazy[u] = 0;
}
void update(int u, int l, int r, int a, int b, int x){
	if(a <= l && r <= b){
		t[u] += (r - l + 1) * x;
		lazy[u] += x; // Caution: additional mark adds
		return;
	}
	pushdown(u, l, r);
	int mid = l + r >> 1;
	if(a <= mid)
		update(u << 1, l, mid, a, b, x);
	if(b > mid)
		update(u << 1 | 1, mid + 1, r, a, b, x);
	t[u] = t[u << 1] + t[u << 1 | 1];
}
ll query(int u, int l, int r, int a, int b){
	if(a <= l && r <= b)
		return t[u];
	pushdown(u, l, r);
	int mid = l + r >> 1;
	ll res = 0;
	if(a <= mid)
		res += query(u << 1, l, mid, a, b);
	if(b > mid)
		res += query(u << 1 | 1, mid + 1, r, a, b);
	return res;
}
posted @ 2021-12-11 22:37  Divinitist  阅读(27)  评论(0)    收藏  举报