社区讨论

在上课,全WA,求救

P3373【模板】线段树 2参与者 3已保存回复 4

讨论操作

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

当前回复
4 条
当前快照
1 份
快照标识符
@mhjlhfcc
此快照首次捕获于
2025/11/04 04:30
4 个月前
此快照最后确认于
2025/11/04 04:30
4 个月前
查看原帖
CPP
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn = 1e6 + 5;
ll a[maxn], b[maxn],d[maxn], f[maxn] = {1};
ll n, m;
void build(ll s, ll t, ll p){
	if (s == t){
		d[p] = a[s];
		return;
	}
	ll m = (s + t) >> 1;
	build(s, m, p * 2), build(m + 1, t, p * 2 + 1);
	d[p] = d[p * 2] + d[(p * 2) + 1];
}
void pushdown(ll p, ll s, ll t) {
	if (f[p] == 1 && b[p] == 0) return;
	ll m = (s + t) >> 1;
	ll lson = p * 2, rson = p * 2 + 1;
	d[lson] = d[lson] * f[p] + b[p] * (m - s + 1);
	f[lson] = f[lson] * f[p];
	
	b[lson] = b[lson] * f[p] + b[p];
	d[rson] = d[rson] * f[p] + b[p] * (t - m);
	
	f[rson] = f[rson] * f[p];
	b[rson] = b[rson] * f[p] + b[p];
	f[p] = 1;
	b[p] = 0;
}
void update1(ll l, ll r, ll c, ll s, ll t, ll p){
	if (s >= l && t <= r){
		d[p] += (t - s + 1) * c;
		b[p] += c;
		return;
	}
	ll m = (s + t) >> 1;
	pushdown(p, s, t);
	if (l <= m)
		update1(l, r, c, s, m, p * 2);
	if (r >= m + 1)
		update1(l, r, c, m + 1, t, p * 2 + 1);
	d[p] = d[p * 2] + d[p * 2 + 1];
}
void update2(ll l, ll r, ll c, ll s, ll t, ll p){
	if (s >= l && t <= r){
		d[p] *= c;
		f[p] *= c;
		b[p] *= c;
		return;
	}
	ll m = (s + t) >> 1;
	pushdown(p, s, t);
	if (l <= m)
		update2(l, r, c, s, m, p * 2);
	if (r >= m + 1)
		update2(l, r, c, m + 1, t, p * 2 + 1);
}
ll getsum(ll l, ll r, ll s, ll t, ll p){
	if (l <= s && r >= t)
		return d[p];
	ll m = (s + t) >> 1;
	ll sum = 0;
	if (b[p]) {
		d[p * 2] += b[p] * (m - s + 1), d[p * 2 + 1] += b[p] * (t - m);
		b[p * 2] += b[p], b[p * 2 + 1] += b[p]; 
		b[p] = 0;                              
	}
	if (l <= m)
		sum += getsum(l, r, s, m, p * 2);
	if (r > m)
		sum += getsum(l , r, m + 1, t, p * 2 + 1);
	return sum;
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> n >> m;
	for (ll i = 1; i <= n; i++){
		cin >> a[i];
	}
	build(1, n, 1);
	for (int i = 1; i <= m; i++){
		ll op, x, y;
		cin >> op;
		cin >> x >> y;
		if (op == 1){
			ll k;
			cin >> k;
			update2(x, y, k, 1, n, 1);
		}
		else if (op == 3){
			cout << getsum(x, y, 1, n, 1) % m <<'\n';
		}
		else {
			ll k;
			cin >> k;
			update1(x, y, k, 1, n, 1);
		}
	}
	return 0;
}

回复

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

正在加载回复...