社区讨论

95分求调

P3372【模板】线段树 1参与者 3已保存回复 3

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
3 条
当前快照
1 份
快照标识符
@mhjif1bm
此快照首次捕获于
2025/11/04 03:05
4 个月前
此快照最后确认于
2025/11/04 03:05
4 个月前
查看原帖
写的线段树代码,打了2000多字节,结果最后一个数据被卡了((⊙﹏⊙)),求助谢啦!!☆⌒(*^-゜)v!!
CPP
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const LL MAXN = 1000000 + 10;
LL n, m;
LL a[MAXN], tree[MAXN * 4];
LL lazy[MAXN * 4];

void push_down(LL pos, LL left, LL right) {
	if (lazy[pos] != 0) {
		LL mid = left + (right - left) / 2;
		tree[pos + pos] += lazy[pos] * (mid - left + 1);
		lazy[pos + pos] += lazy[pos];
		tree[pos + pos + 1] += lazy[pos] * (right - mid);
		lazy[pos + pos + 1] += lazy[pos];
		lazy[pos] = 0;
	}
}

void build(LL pos, LL left, LL right) {
	if (left == right) {
		tree[pos] = a[left];
		return ;
	}
	
	LL mid = left + (right - left) / 2;
	build(pos + pos, left, mid);	
	build(pos + pos + 1, mid + 1, right);
	tree[pos] = tree[pos + pos + 1] + tree[pos + pos];
}

void updateRange(LL pos, LL left, LL right, LL uleft, LL uright, LL val) {
	if (uright < left || uleft > right) return ;
	if (uleft <= left && uright >= right) {
		tree[pos] += val * (right - left + 1);
		lazy[pos] += val;
		return ;
	}
	push_down(pos, left, right);
	LL mid = left + (right - left) / 2;
	updateRange(pos + pos, left, mid, uleft, uright, val);
	updateRange(pos + pos + 1, mid + 1, right, uleft, uright, val);
	tree[pos] = tree[pos + pos] + tree[pos + pos + 1];
}

LL queryRange(LL pos, LL left, LL right, LL uleft, LL uright) {
	if (uright < left || uleft > right) return 0;
	if (uleft <= left && right <= uright) return tree[pos];
	push_down(pos, left, right);
	LL mid = left + (right - left) / 2;
	return queryRange(pos + pos, left, mid, uleft, uright) + queryRange(pos + pos + 1, mid + 1, right, uleft, uright);
}

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	cin >> n >> m;
	for (LL i = 1; i <= n; ++ i) {
		cin >> a[i];
	}
	build(1, 1, n);
	
	LL op, x, y, k;
	for (LL i = 1; i <= m; ++ i) {
		cin >> op;
		if (op == 1) {
			cin >> x >> y >> k;
			updateRange(1, 1, n, x, y, k);
		} else
		if (op == 2) {
			cin >> x >> y;
			cout << queryRange(1, 1, n, x, y) << "\n";
		}
	}
	
	return 0;
}

回复

3 条回复,欢迎继续交流。

正在加载回复...