hdu 4267 A Simple Problem with Integers(线段树区间更新)

题目链接点这里

#include<stdio.h>
#include<algorithm>
#include<iostream>
#define LL long long
using namespace std;
const int N=110000;
LL num[N];
LL Sum;
struct node
{
    LL l;
    LL r;
    LL sum;
    LL add;
}tree[N*4];
LL n,q,i,j;
void pushdown(LL x)
{
    LL tmp=x<<1;
    tree[tmp].add+=tree[x].add;
    tree[tmp+1].add+=tree[x].add;
    tree[tmp].sum+=tree[x].add*(tree[tmp].r-tree[tmp].l+1);
    tree[tmp+1].sum+=tree[x].add*(tree[tmp+1].r-tree[tmp+1].l+1);
    tree[x].add=0;
}
void build(int x,int y,int n)
{
    tree[n].l=x;
    tree[n].r=y;
    tree[n].add=0;
    if(x==y)
    {
        tree[n].sum=num[x];
        return ;
    }
   // LL mid=(tree[n].l+tree[n].r)>>1;
     int  mid=(x+y)>>1;
    build(x,mid,2*n);
    build(mid+1,y,2*n+1);
    tree[n].sum=tree[n*2].sum+tree[n*2+1].sum;
}
void update(LL x,LL y,LL c,LL n)
{
    if(y<tree[n].l||x>tree[n].r)
        return ;
    if(tree[n].l>=x&&tree[n].r<=y)
    {
        tree[n].add+=c;
        tree[n].sum+=c*(tree[n].r-tree[n].l+1);
        return ;
    }
    if(tree[n].add)
     pushdown(n);
    LL tmp=n<<1;
    update(x,y,c,tmp);
    update(x,y,c,tmp+1);
    tree[n].sum=tree[n*2].sum+tree[n*2+1].sum;
}
void query(LL x,LL y,LL n)
{
    if(y<tree[n].l||tree[n].r<x)
        return ;
    if(tree[n].l>=x&&tree[n].r<=y)
    {
       Sum+=tree[n].sum;
       return ;
    }
     if(tree[n].add)
     pushdown(n);
    LL  mid=(tree[n].l+tree[n].r)>>1;
    if(mid>=y)
        query(x,y,2*n);
    else if(mid<x)
        query(x,y,2*n+1);
    else
    {
        query(x,mid,2*n);
        query(mid+1,y,2*n+1);
    }
}
int main()
{
    LL x1,y1,c;
    while(~scanf("%lld %lld",&n,&q))
    {
        for(i=1;i<=n;i++)
        {
            scanf("%lld",&num[i]);
        }
        build(1,n,1);
        char s[2];
        while(q--)
        {
            //Sum=0;
            scanf("%s",s);
            if(s[0]=='Q')
            {
                scanf("%lld%lld",&x1,&y1);
                Sum=0;
                query(x1,y1,1);
                printf("%lld\n",Sum);
            }
            else if(s[0]=='C')
            {
                scanf("%lld%lld%lld",&x1,&y1,&c);
                 update(x1,y1,c,1);
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值