线段树蒟蒻求条
查看原帖
线段树蒟蒻求条
748328
jrzhr楼主2023/12/27 12:12
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll a[100001], w[400001];
int n, m;
ll lzy[400001];
void pushup(int u){
	w[u] = w[u * 2] + w[u * 2 + 1];
}
void build(int u, int L, int R){
	if(L == R){
		w[u] = a[L];
		return ;
	}
	int M = (L + R) / 2;
	build(u * 2, L, M);
	build(u * 2 + 1, M + 1, R);
	pushup(u);
}
ll query1(int u, int L, int R, int p){
	if(L == R){
		return w[u];
	}
	int M = (L + R) / 2;
	if(M >= p){
		return query1(u * 2, L, M, p);
	}else{
		return query1(u * 2 + 1, M + 1, R, p);
	}
}
void maketag(int u, int len, ll x){
	lzy[u] += x;
	w[u] += len * x;
}
void pushdown(int u, int L, int R){
	int M = (L + R) / 2;
	maketag(u * 2, M - L + 1, lzy[u]);
	maketag(u * 2 + 1, R - L, lzy[u]);
	lzy[u] = 0;
}
bool InRange(int L, int R, int l, int r){
	return (l <= L) && (r >= R);
}
bool OutofRange(int L, int R, int l, int r){
	return (r < L) || (l > R);
}
ll query(int u, int L, int R, int l, int r){
	if(InRange(L, R, l, r)){
		return w[u];
	}
	if(!OutofRange(L, R, l, r)){
		int M = (L + R) / 2;
		pushdown(u, L, R);
		return query(u * 2, L, M, l, r) + query(u * 2 + 1, M + 1, R, l, r);
	}
	return 0;
}
void update(int u, int L, int R, int l, int r, ll x){
	if(InRange(L, R, l, r)){
		maketag(u, R - L + 1, x);
	}else if(!OutofRange(L, R, l, r)){
		int M = (L + R) / 2;
		pushdown(u, L, R);
		update(u * 2, L, M, l, r, x);
		update(u * 2 + 1, M + 1, R, l, r, x);
		pushup(u);
	}
}
int main(){
	scanf("%lld%lld", &n, &m);
	for(int i = 1; i <= n; i++){
		scanf("%lld", &a[i]);
	}
	build(1, 1, n);
	for(int i = 1; i <= m; i++){
		int opt, x, y;
		ll k;
		scanf("%d", &opt);
		if(opt == 1){
			scanf("%d%d%lld", &x, &y, &k);
			update(1, 1, n, x, y, k);
		}else if(opt == 2){
			scanf("%d%d", &x, &y);
			printf("%lld\n", query(1, 1, n, x, y));
		}
	}
	return 0;
}
2023/12/27 12:12
加载中...