POJ3468 A Simple Problem with Integers(线段树)

题目链接:poj3468

思路

区间更新:区间加上某个数
区间查询:区间和

小结

1A了。。

代码

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

typedef long long ll;

const int maxn = 100000+5;
ll tree[maxn<<2];
ll add[maxn<<2];

void build(int rt, int l, int r){
    if(l==r){
        scanf("%lld", &tree[rt]);
    }
    else{
        int mid = (l+r)>>1;
        build(rt<<1, l, mid);
        build(rt<<1|1, mid+1, r);
        tree[rt] = tree[rt<<1] + tree[rt<<1|1];
    }
}

void pushdown(int rt, int len){
    if(add[rt]!=0){ 
        add[rt<<1] += add[rt];
        add[rt<<1|1] += add[rt];
        tree[rt<<1] += (len - len/2) * add[rt];
        tree[rt<<1|1] += (len/2) * add[rt];
        add[rt] = 0;
    }
} 

void Add(int rt, int a, int b, int l, int r, ll x){
    if(a<=l && r<=b){
        add[rt] += x;
        tree[rt] += (ll)(x * (r-l+1));
    }
    else{
        pushdown(rt, r-l+1);
        int mid = (l+r)>>1;
        if(a<=mid) Add(rt<<1, a, b, l, mid, x);
        if(mid<b) Add(rt<<1|1, a, b, mid+1, r, x);
        tree[rt] = tree[rt<<1] + tree[rt<<1|1];
    }
}

ll query(int rt, int a, int b, int l, int r){
    if(a<=l && r<=b){
        return tree[rt];
    }
    else{
        pushdown(rt, r-l+1);
        int mid = (l+r)>>1;
        ll ans = 0;
        if(a<=mid) ans += query(rt<<1, a, b, l, mid);
        if(mid<b) ans += query(rt<<1|1, a, b, mid+1, r);
        return ans;
    }
}

int main(){
    ll c;
    int n, q, a, b;
    char opt[10];
    while(scanf("%d%d", &n, &q)!=EOF){
        memset(add, 0, sizeof(add));
        build(1, 1, n);
        for(int i=0; i<q; ++i){
            scanf("%s%d%d", opt, &a, &b);
            if(opt[0]=='Q'){
                printf("%lld\n", query(1, a, b, 1, n));
            }
            else if(opt[0]=='C'){
                scanf("%lld", &c);
                Add(1, a, b, 1, n, c);
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值