其他分享
首页 > 其他分享> > SPOJ - HORRIBLE 区间加+区间求和

SPOJ - HORRIBLE 区间加+区间求和

作者:互联网

一、思路

二、代码

#include <cstdio>
#include <cstring>
typedef long long ll;
const int maxn = 1e5 +5;
int t, n, q, code, x, y;
ll sum[maxn << 2], lazy[maxn << 2], add;
void pushdown(int id, int l, int r) {
	if (lazy[id] == 0) return;
	int mid = (l + r) >> 1;
	lazy[id << 1] += lazy[id];
	lazy[id << 1 | 1] += lazy[id];
	sum[id << 1] += lazy[id] * (mid - l + 1);
	sum[id << 1 | 1] += lazy[id] * (r - mid);
	lazy[id] = 0;
}
void update(int id, int l, int r, int x, int y, ll add) {
	if (x <= l && r <= y) {
		sum[id] += (r - l + 1) * add;
		lazy[id] += add;
		return;
	}
	pushdown(id, l, r);
	int mid = (l + r) >> 1;
	if (x <= mid) update(id << 1, l, mid, x, y, add);
	if (y > mid) update(id << 1 | 1, mid + 1, r, x, y, add);
	sum[id] = sum[id << 1] + sum[id << 1 | 1];
}
ll query(int id, int l, int r, int x, int y) {
	if (x <= l && r <= y) {
		return sum[id];
	}
	pushdown(id, l, r);
	int mid = (l + r) >> 1;
	ll ans = 0;
	if (x <= mid) ans += query(id << 1, l, mid, x, y);
	if (y > mid) ans += query(id << 1 | 1, mid + 1, r, x, y);
	return ans;
}
int main() {
	scanf("%d", &t);
	for (int cas = 1;  cas <= t; cas++) {
		memset(sum, 0, sizeof(sum));
		memset(lazy, 0, sizeof(lazy));
		scanf("%d%d", &n, &q);
		for (int i = 1; i <= q; i++) {
			scanf("%d", &code);
			if (code == 0) {
				scanf("%d%d%lld", &x, &y, &add);
				update(1, 1, n, x, y, add);
			} else {
				scanf("%d%d", &x, &y);
				printf("%lld\n", query(1, 1, n, x, y));
			}
		}
	}
	return 0;
} 

标签:int,ll,ans,mid,SPOJ,HORRIBLE,区间,id
来源: https://blog.csdn.net/qq_41280600/article/details/101053561