poj 3468 A Simple Problem with Integers ( 线段树 )

11 篇文章 0 订阅

全裸线段树。

写此篇主要是太久没写线段树,贴个模板备忘。

模板来自NotOnlySuccess的博客

 

#include <iostream>
#include <cstdio>

using namespace std;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N=100005;
typedef long long LL;
LL Sum[N<<2],Add[N<<2];

void pushUp(int rt)
{
    Sum[rt]=Sum[rt<<1]+Sum[rt<<1|1];
}

void build(int l,int r,int rt)
{
    Add[rt]=0;
    if(l==r)
    {
        scanf("%lld",&Sum[rt]);
        return ;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    pushUp(rt);
}

void pushDown(int rt,int len)
{
    if(Add[rt])
    {
        Add[rt<<1]+=Add[rt];
        Add[rt<<1|1]+=Add[rt];
        Sum[rt<<1]+=((len+1)>>1)*Add[rt];
        Sum[rt<<1|1]+=(len>>1)*Add[rt];
        Add[rt]=0;
    }
}

LL query(int L,int R,int l,int r,int rt)
{
    if(L<=l&&r<=R)
        return Sum[rt];
    pushDown(rt,r-l+1);
    int m=(l+r)>>1;
    LL ret=0;
    if(R<=m)
        ret=query(L,R,lson);
    else if(L>m)
        ret=query(L,R,rson);
    else
        ret=query(L,R,lson)+query(L,R,rson);
    return ret;
}

void update(int L,int R,LL add,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        Sum[rt]+=(r-l+1)*add;
        Add[rt]+=add;
        return ;
    }
    int m=(l+r)>>1;
    pushDown(rt,r-l+1);
    if(L<=m)
        update(L,R,add,lson);
    if(m<R)
        update(L,R,add,rson);
    pushUp(rt);
}

int main()
{
//    freopen("in","r",stdin);

    int n,q;
    scanf("%d%d",&n,&q);
    build(1,n,1);
    char op[5];
    int  a,b;
    LL c;
    while(q--)
    {
        scanf("%s",op);
        if(op[0]=='Q')
        {
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(a,b,1,n,1));
        }
        else
        {
            scanf("%d%d%lld",&a,&b,&c);
            update(a,b,c,1,n,1);
        }
    }
    return 0;
}

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值