P3372 模板线段树 1

Posted lightyachoo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了P3372 模板线段树 1相关的知识,希望对你有一定的参考价值。

P3372 【模板】线段树 1

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N=1e5+10;
ll a[N];
struct Node{
	ll it;
	ll l;
	ll r;
	ll data;
}tree[N<<2];
ll n,m;
void build(ll rt,ll l,ll r){
	tree[rt].l = l;
	tree[rt].r = r;
	tree[rt].it = 0;
	if(l == r) {
		tree[rt].data = a[l];
		return ;
	}
	ll mid = (l + r)>>1;
	build(rt*2,l,mid);
	build(rt*2+1,mid+1,r);
	tree[rt].data = tree[rt*2].data+tree[rt*2+1].data;
	return ;
}
void push_down(ll rt){
	if(tree[rt].it!=0){
		tree[rt*2].it+=tree[rt].it;
		tree[rt*2+1].it+=tree[rt].it;
		ll mid = (tree[rt].l+tree[rt].r)>>1;
		tree[rt*2].data+=tree[rt].it*(mid-tree[rt*2].l+1);
		tree[rt*2+1].data+=tree[rt].it*(tree[rt*2+1].r-mid);
		tree[rt].it=0;
	}
	return ;
}

void up_data(ll rt,ll l,ll r,ll k){
	if(tree[rt].l>=l&&tree[rt].r<=r){
		tree[rt].data+=k*(tree[rt].r-tree[rt].l+1);
		tree[rt].it+=k;
		return ;
	}
	push_down(rt);
	if(tree[rt*2].r>=l){
		up_data(rt*2,l,r,k);
	}
	if(tree[rt*2+1].l<=r){
		up_data(rt*2+1,l,r,k);
	}
	tree[rt].data = tree[rt*2].data + tree[rt*2+1].data;
	return ;
}



ll search(ll rt,ll l,ll r){
	if(tree[rt].l>=l&&tree[rt].r<=r){
		return tree[rt].data;
	}
	push_down(rt);
	ll num=0;
	if(tree[rt*2].r>=l){
		num+=search(rt*2,l,r);
	}
	if(tree[rt*2+1].l<=r){
		num+=search(rt*2+1,l,r);
	}
	return num;
}

int main(){
	scanf("%lld%lld",&n,&m);
	for(ll i=1;i<=n;i++){
		scanf("%lld",&a[i]);
	}
	build(1,1,n);
	for(ll i = 1;i <= m;i++){
		ll go;
		scanf("%lld",&go);
		if(go == 1){
			ll x,y,k;
			scanf("%lld%lld%lld",&x,&y,&k);
			up_data(1,x,y,k);
		}
		if(go == 2){
			ll x,y;
			scanf("%lld%lld",&x,&y);
			printf("%lld
",search(1,x,y));
		}
	}
	return 0;
}

 

以上是关于P3372 模板线段树 1的主要内容,如果未能解决你的问题,请参考以下文章

P3372 模板线段树 1

P3372 模板线段树 1(区间修改区间查询)(树状数组)

P3372 模板线段树 1

线段树模板1 [Luogu P3372]

洛谷P3372 模板线段树 1

P3372 模板线段树 1