P3372 【模板】线段树 1 线段树模版+懒惰标记

9 篇文章 0 订阅

【模板】线段树 1

 

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 100005;
int a[maxn];
struct N{
	int l,r;
	ll pre,add;
}node[4*maxn+5];
void build(int p,int l,int r){//区间编号p 
	node[p].l = l;
        node[p].r = r;
        node[p].add = 0;
	if(l==r){//叶子结点直接赋值 
		node[p].pre = a[l];
		return ;
	}
	int mid = l+r >>1;
	build(2*p,l,mid);
	build(2*p+1,mid+1,r);
	node[p].pre = node[p*2].pre + node[p*2+1].pre;//维护区间和 
}
void spread(int p){
	if(node[p].add){//如果标记不为0 向下传递 
		node[2*p].pre+=(node[2*p].r - node[2*p].l + 1)*node[p].add;		
		node[2*p+1].pre+=(node[2*p+1].r - node[2*p+1].l + 1)*node[p].add;
		node[2*p].add+= node[p].add;
		node[2*p+1].add+= node[p].add;
		node[p].add = 0;
	}
}
void change(int p,int l,int r,int v){
	if(node[p].l>=l&&node[p].r<=r){//区间被覆盖 就对其进行修改 
		node[p].pre+=(ll)v*(node[p].r-node[p].l+1);
		node[p].add+= v; //加上懒惰标记 
		return ;
	}
	spread(p);//没有覆盖 下放懒惰标记 考虑儿子区间可能因为懒惰标记存在而没有修改
	int mid = node[p].l + node[p].r>>1; 
	if(l<=mid)change(p*2,l,r,v);
	if(r>mid)change(p*2+1,l,r,v);
	node[p].pre = node[2*p].pre + node[2*p+1].pre;
} 
ll query(int p,int l,int r){
    if(l==0)return 0;
    if(l>r)return 0;
	if(l<=node[p].l&&r>=node[p].r){//被覆盖 返回值 
		return node[p].pre;
	}
	spread(p);
	ll ans = 0;
	int mid = node[p].r+node[p].l>>1;
	 if(l<=mid)ans+=query(p*2,l,r);
	 if(r>mid)ans+=query(p*2+1,l,r);
	 return ans;
}
int main()
{
	int n,m;
	scanf("%d %d",&n,&m);	
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	build(1,1,n);
	while(m--){
		int op,l,r,k;
		scanf("%d %d %d",&op,&l,&r);
		if(op==1){
			scanf("%d",&k);
			change(1,l,r,k);
		}else {
			printf("%lld\n",query(1,l,r));
		}
	}
	return 0;
 } 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wym_king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值