萌新的线段树,样例过了,不知道哪里错了qwq
查看原帖
萌新的线段树,样例过了,不知道哪里错了qwq
496009
黄舀啊楼主2022/4/6 18:48
#include<iostream>
using namespace std;
const int MAXN = 100100;

long long n,m,c[MAXN];

struct Tree {
	int l,r;
	long long data,add;
};
Tree tree[MAXN*4];

void spread(int p) {
	if(tree[p].add) {
		tree[p*2].data += tree[p].add*(tree[p*2].r-tree[p*2].l+1);
		tree[p*2+1].data += tree[p].add*(tree[p*2+1].r-tree[p*2+1].l+1);
		tree[p*2].add += tree[p].add;
		tree[p*2+1].add += tree[p].add;
		tree[p].add = 0;
	}
}

void build(int p,int l,int r) {
	tree[p].l = l,tree[p].r = r;
	if(r == l) {
		tree[p].data = c[l];
		return ;
	}
	int mid = (l+r)/2;
	build(p*2,l,mid);
	build(p*2+1,mid+1,r);
	tree[p].data = tree[p*2].data+tree[p*2+1].data;
}

void change(int p,int x,int y,int v) {
	if(tree[p].l >=x && tree[p].r<=y) {
		tree[p].data += v*(tree[p].l-tree[p].r+1);
		tree[p].add += v;
		return ;
	}
	spread(p);
	int mid = (tree[p].l+tree[p].r)/2;
	if(x <= mid) change(p*2,x,y,v);
	if(y > mid)  change(p*2+1,x,y,v);
	tree[p].data = tree[p*2].data+tree[p*2+1].data;
}

long long ask(int p,int l,int r) {
	if(tree[p].l>=l && tree[p].r<=r) {
		return tree[p].data;
	}
	spread(p);
	int mid = (tree[p].l+tree[p].r)/2;
	long long ans = 0;
	if(l<=mid) ans += ask(p*2,l,r);
	if(r>mid)  ans += ask(p*2+1,l,r);
	return ans;
}

int main() {

	cin >> n >> m;
	for(int i=1 ; i<=n ; i++)
		cin >> c[i];
	build(1,1,n);
	long long x,y,k;
	for(int i=1 ; i<=m ; i++) {
		short f;
		cin >> f;
		if(f == 1) {
			cin >> x >> y >> k;
			change(1,x,y,k);
		} else {
			cin >> x >> y;
			cout << ask(1,x,y) << endl;
		}
	}

	return 0;
}
2022/4/6 18:48
加载中...