POJ3468(线段树模板)

解题思路:线段树裸题。但有个地方苦恼了一下。最后这个ans必须得长整型才行。

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
struct node
{
	int l,r;
	ll w,sum;
}s[400009];
int p[100009];
int n,m;
ll ans;
void build(int t,int l,int r)
{
	s[t].l=l;s[t].r=r;s[t].w=0;
	if(s[t].l==s[t].r)
	{
		s[t].sum=p[l];
		return;
	}
	build(2*t,l,(l+r)/2);
	build(2*t+1,(l+r)/2+1,r);
	s[t].sum=s[2*t].sum+s[2*t+1].sum;
}
void query(int t,int l,int r)
{
	if(s[t].l==l&&s[t].r==r)
	{
		ans+=s[t].sum;
		return;
	}
	int mid=(s[t].l+s[t].r)/2;
	if(s[t].w)
	{
		s[2*t].sum+=s[t].w*(s[2*t].r-s[2*t].l+1);
		s[2*t+1].sum+=s[t].w*(s[2*t+1].r-s[2*t+1].l+1);
		s[2*t].w+=s[t].w;
		s[2*t+1].w+=s[t].w; 
		s[t].w=0;
	}
	if(r<=mid)
	{
		query(2*t,l,r);
	}else
	if(l>mid)
	{
		query(2*t+1,l,r);
	}else
	{
		query(2*t,l,mid);
		query(2*t+1,mid+1,r);
	}
}
void update(int t,int l,int r,int w)
{
	if(s[t].l==l&&s[t].r==r)
	{
		s[t].sum+=w*(s[t].r-s[t].l+1);
		s[t].w+=w;
		return;
	}
	if(s[t].w)
	{
		s[2*t].sum+=s[t].w*(s[2*t].r-s[2*t].l+1);
		s[2*t+1].sum+=s[t].w*(s[2*t+1].r-s[2*t+1].l+1);
		s[2*t].w+=s[t].w;
		s[2*t+1].w+=s[t].w; 	
		s[t].w=0;	
	}
	int mid=(s[t].l+s[t].r)/2;
	if(r<=mid)
	update(2*t,l,r,w);
	else
	if(l>mid)
	update(2*t+1,l,r,w);
	else
	{
		update(2*t,l,mid,w);
		update(2*t+1,mid+1,r,w);
	}
	s[t].sum=s[2*t].sum+s[2*t+1].sum;
}
int main()
{
	//freopen("t.txt","r",stdin);
	char tp;
	int a,b,c;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&p[i]);
		}
		build(1,1,n);
		while(m--)
		{
			getchar();
			scanf("%c",&tp);
			if(tp=='Q')
			{
				scanf("%d%d",&a,&b);
				ans=0;
				query(1,a,b);
				printf("%lld\n",ans);
			}else
			if(tp=='C')
			{
				scanf("%d%d%d",&a,&b,&c);
				update(1,a,b,c);
			}
		}
	}
	return 0;
} 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值