POJ-3468 A Simple Problem with Integers (区间求和,成段加减)

You have N integers, A1A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

Input

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

Sample Input

10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4

Sample Output

4
55
9
15

区间求和,成段加减

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

using namespace std;
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
typedef long long LL;
const int N = 100000 + 5;
LL T[N<<2],add[N<<2];

void PushUP(int rt){
    T[rt] = T[rt<<1] + T[rt<<1|1];
}

void PushDown(int rt, int m){
    if(add[rt]){
        add[rt<<1] += add[rt];
        add[rt<<1|1] += add[rt];
        T[rt<<1] += add[rt]*(LL)(m - (m >> 1));
        T[rt<<1|1] += add[rt]*(LL)(m >> 1);
        add[rt] = 0;
    }
}
void Build(int l, int r, int rt){
    add[rt] = 0;
    if(l == r){
        scanf("%lld",&T[rt]);
        return ;
    }
    int m = (l + r) >> 1;
    Build(lson);
    Build(rson);
    PushUP(rt);
}

void Updata(int L,int R, int c,int l, int r, int rt){
    if(L <= l && r <= R){
        add[rt] += c;
        T[rt] += (LL)c*(r - l + 1);
        return ;
    }
    PushDown(rt, r - l + 1);
    int m = (l + r) >> 1;
    if(L <= m) Updata(L, R, c, lson);
    if(R > m) Updata(L, R, c, rson);
    PushUP(rt);
}

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

int main(){
    int n,m;
    while(scanf("%d %d",&n,&m)==2){
        Build(1, n, 1);
        char ch[5];
        int a,b,c;
        while(m--){
            scanf("%s %d %d",ch,&a,&b);
            if(ch[0] == 'Q')printf("%lld
",Query(a, b, 1, n, 1));
            else{
                scanf("%d",&c);
                Updata(a, b, c, 1, n, 1);
            }
        }
    }
    return 0;
}
 


原文地址:https://www.cnblogs.com/Pretty9/p/7384046.html