前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >P3372 【模板】线段树 1 线段树模版+懒惰标记

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

作者头像
用户2965768
发布2019-05-06 17:30:08
6180
发布2019-05-06 17:30:08
举报
文章被收录于专栏:wymwym

【模板】线段树 1

代码语言:javascript
复制
#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;
	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<=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;
 } 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年04月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档