POJ 3468 线段树 区间增减 区间求和

题目链接


#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
const int maxn = 150000;
struct Node{
    long long sum,add;
}st[maxn<<2];
void up(int rt){
    st[rt].sum=st[rt<<1].sum+st[rt<<1|1].sum;
}
void down(int rt,int m){
    if(st[rt].add){
        st[rt<<1].add+=st[rt].add;
        st[rt<<1|1].add+=st[rt].add;
        st[rt<<1].sum+=(m-(m>>1))*st[rt].add;
        st[rt<<1|1].sum+=(m>>1)*st[rt].add;
        st[rt].add=0;
    }
}
void build(int l,int r,int rt){
    st[rt].add=0;
    if(l==r){
        scanf("%I64d",&st[rt].sum);
        return ;
    }
    int mid=(l+r)>>1;
    build(lson);
    build(rson);
    up(rt);
}
void update(int a,int b,int c,int l,int r,int rt){
    if(a<=l&&r<=b){
        st[rt].add+=c;
        st[rt].sum+=(long long)c*(r-l+1);
        return ;
    }
    down(rt,r-l+1);
    int mid=(l+r)>>1;
    if(a<=mid){
        update(a,b,c,lson);
    }
    if(mid<b){
        update(a,b,c,rson);
    }
    up(rt);
}
long long query(int a,int b,int l,int r,int rt){
    if(a<=l&&r<=b)return st[rt].sum;
    down(rt,r-l+1);
    int mid=(l+r)>>1;
    long long ret=0;
    if(a<=mid)ret+=query(a,b,lson);
    if(mid<b) ret+=query(a,b,rson);
    return ret;
}
int main()
{
    int n,q;
    scanf("%d%d",&n,&q);
    build(1,n,1);
    while(q--){
        char s[10];
        int a,b,c;
        scanf("%s",s);
        if(s[0]=='Q'){
            scanf("%d%d",&a,&b);
            printf("%I64d\n",query(a,b,1,n,1));
        }
        else{
            scanf("%d%d%d",&a,&b,&c);
            update(a,b,c,1,n,1);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值