poj 3468(线段树)

线段树lazy的pushdown的需要注意一点,究竟是+=还是=

#include 
#include 
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn = 1e5 + 5;
typedef long long ll;
ll sum[maxn << 2], add[maxn << 2];
void pushup(int rt) {
    sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}

void pushdown(int rt, int m) {
    if(add[rt]) {
        add[rt << 1] += add[rt];
        add[rt << 1 | 1] += add[rt] ;
        sum[rt << 1] += (m - (m >> 1)) * add[rt];
        sum[rt << 1 | 1] += (m >> 1) * add[rt];
        add[rt] = 0;
    }
}
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 updata(int p, int L, int R, int l, int r, int rt) {
    if(L <= l && R >= r) {
        add[rt] += p;
        sum[rt] += (ll)p * (r - l + 1);
        return;
    }
    pushdown(rt, r - l + 1);
    int m = (l + r) >> 1;
    if(L <= m) updata(p, L, R, lson);
    if(R > m) updata(p, L, R, rson);
    pushup(rt);
}
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);
    ll ret = 0;
    int m = (l + r) >> 1;
    if(L <= m) ret += query(L, R, lson);
    if(R > m) ret += query(L, R, rson);
    return ret;
}
ll n, q;
int main() {
    scanf("%d%d", &n, &q);
    build(1, n, 1);
    for(int i = 1; i <= q; i++) {
        char op[2];
        int a, b, c;
        scanf("%s", op);
        if(op[0] == 'C') {
            scanf("%d%d%d", &a, &b, &c);
            updata(c, a, b, 1, n, 1);
        } else {
            scanf("%d%d", &a, &b);
            printf("%lld\n", query(a, b, 1, n, 1));
        }
    }
    return 0;
}

你可能感兴趣的:(ACM_线段树)