POJ-3468-A Simple Problem with Integers(区间线段树模板题)

地址:http://poj.org/problem?id=3468

思路:区间线段树模板题。。

Code:

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;

const int MAX_N=1e5+5;
struct tree{
	int l,r;
	LL lazy;
	LL x;
	int mid(){
		return (l+r)>>1;
	}
};
int n,Q;
int a[MAX_N];
tree Tree[MAX_N<<2];

void PushUp(int rt);
void PushDown(int rt);
void Build(int l,int r,int rt);
void Update(int l,int r,LL x,int rt);
LL Query(int l,int r,int rt);
int main()
{
	scanf("%d%d",&n,&Q);
	for(int i=1;i<=n;++i)
		scanf("%d",&a[i]);
	Build(1,n,1);
	char ch[5];
	int l,r,x;
	while(Q--){
		scanf("%s%d%d",ch,&l,&r);
		if(ch[0]=='C'){
			scanf("%d",&x);
			Update(l,r,x,1);
		}else{
			printf("%lld\n",Query(l,r,1));
		}
	}
	
	return 0;
}

void PushUp(int rt)
{
	Tree[rt].x=Tree[rt<<1].x+Tree[(rt<<1)|1].x;
}

void PushDown(int rt)
{
	if(Tree[rt].lazy){
		int h=Tree[rt].r-Tree[rt].l+1;
		Tree[rt<<1].lazy+=Tree[rt].lazy;
		Tree[(rt<<1)|1].lazy+=Tree[rt].lazy;
		Tree[rt<<1].x+=Tree[rt].lazy*(h-(h>>1));
		Tree[(rt<<1)|1].x+=Tree[rt].lazy*(h>>1);
		Tree[rt].lazy=0;
	}
}

void Build(int l,int r,int rt)
{
	Tree[rt].l=l;	Tree[rt].r=r;
	if(l==r){
		Tree[rt].x=a[l];	return;
	}
	int h=(l+r)>>1;
	Build(l,h,rt<<1);
	Build(h+1,r,(rt<<1)|1);
	PushUp(rt);
}

void Update(int l,int r,LL x,int rt)
{
	if(l<=Tree[rt].l&&r>=Tree[rt].r){
		Tree[rt].lazy+=x;
		Tree[rt].x+=(Tree[rt].r-Tree[rt].l+1)*x;
		return;
	}
	PushDown(rt);
	int H=Tree[rt].mid();
	if(H>=l)	Update(l,r,x,rt<<1);
	if(H<r)	Update(l,r,x,(rt<<1)|1);
	PushUp(rt);
}

LL Query(int l,int r,int rt)
{
	if(l<=Tree[rt].l&&r>=Tree[rt].r)	return Tree[rt].x;
	PushDown(rt);
	LL res=0;
	int H=Tree[rt].mid();
	if(H>=l)	res+=Query(l,r,rt<<1);
	if(H<r)	res+=Query(l,r,(rt<<1)|1);
	return res;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值