POJ - 3468 A Simple Problem with Integers(线段树,区间修改查询)

POJ - 3468 A Simple Problem with Integers

树状数组写法

线段树写法

#include<cstdio>

typedef long long LL;
const int N = 100010;

int w[N];
int n,m;

struct tree
{
    int l,r,len;
    LL sum,lazy;
}tr[N*4];

void pushup(int u)
{
	tr[u].sum=tr[u<<1].sum+tr[u<<1|1].sum;
}

void pushdown(int u)
{
    if(tr[u].lazy)
    {
        tr[u<<1].lazy+=tr[u].lazy;
        tr[u<<1|1].lazy+=tr[u].lazy;
        tr[u<<1].sum+=tr[u<<1].len*tr[u].lazy;
        tr[u<<1|1].sum+=tr[u<<1|1].len*tr[u].lazy;
        tr[u].lazy=0;
    }
}

void build(int u,int l,int r)
{
    if(l==r) tr[u]={l,r,r-l+1,w[l]};
    else
    {
        tr[u]={l,r,r-l+1};
        int mid=l+r>>1;
        build(u<<1,l,mid);
		build(u<<1|1,mid+1,r);
        pushup(u);
    }
}

void update(int u,int l,int r,LL d)
{
    if(tr[u].l>=l&&tr[u].r<=r)
    {
        tr[u].sum+=tr[u].len*d;
        tr[u].lazy+=d;
    }
    else
    {
        pushdown(u);
        int mid=tr[u].l+tr[u].r>>1;
        if(l<=mid) update(u<<1,l,r,d);
        if(r>mid) update(u<<1|1,l,r,d);
        pushup(u);
    }
}

LL query(int u,int l,int r)
{
    if(tr[u].l>=l&&tr[u].r<=r) return tr[u].sum;
    else
    {
        pushdown(u);
        int mid=tr[u].l+tr[u].r>>1;
        LL res=0;
        if(l<=mid) res=query(u<<1,l,r);
        if(r>mid) res+=query(u<<1|1,l,r);
        return res;
    }
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++) scanf("%d",&w[i]);
	build(1,1,n);
	
	char op[2];
	int l,r,d;
	
	for(int i=1;i<=m;i++)
	{
		scanf("%s",&op);
		if(*op=='Q')
		{
			scanf("%d%d",&l,&r);
            printf("%lld\n",query(1,l,r));
		} 
		else
		{
			scanf("%d%d%d",&l,&r,&d);
            update(1,l,r,d);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Wa_Automata

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

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

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

打赏作者

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

抵扣说明:

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

余额充值