poj 3468 A Simple Problem with Integers

来源:互联网 发布:开淘宝都买宝马了 编辑:程序博客网 时间:2024/06/07 17:27
Description

You have N integers, A1, A2, ... , 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 A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+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

转自博客:http://www.cnblogs.com/wally/p/3614721.html

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define lson rt << 1#define rson rt << 1 | 1typedef long long ll;const int MAXN = (100000 +100);int N, Q;ll sum[MAXN << 2], add[MAXN << 2];void PushUp(int rt){    sum[rt] = sum[lson] + sum[rson];}void PushDown(int rt, int len){    if (add[rt]) {          //将父节点的增量转移到子节点上,然后进行清空        add[lson] += add[rt];        add[rson] += add[rt];        sum[lson] += (len - (len >> 1)) * add[rt];        sum[rson] += (len >> 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(L, M, lson);    Build(M + 1, R, rson);    PushUp(rt);             //每次输入完成以后,要父节点进行更新}void Update(int L, int R, int rt, int l, int r, int lnc){    if (l <= L && R <= r) {        add[rt] += lnc;<span style="white-space:pre"></span>//如果在区间里面,就进行改值,然后下移,对子节点进行更新        sum[rt] += (R - L + 1) * lnc;        return;    }    PushDown(rt, R - L + 1);    int M = (L + R) >> 1;    if (l <= M) Update(L, M, lson, l, r, lnc);    if (r > M) Update(M + 1, R, rson, l, r, lnc);    PushUp(rt);<span style="white-space:pre"></span>//更新完以后,要将最终的变化体现到父节点上}ll Query(int L, int R, int rt, int l, int r){    if (l <= L && R <= r) {        return sum[rt];    }    PushDown(rt, R - L + 1);    int M = (L + R) >> 1;    ll ret = 0;    if (l <= M) ret += Query(L, M, lson, l, r);    if (r > M) ret += Query(M + 1, R, rson, l, r);    return ret;}int main(){    scanf("%d %d", &N, &Q);    Build(1, N, 1);    while (Q--) {        char str[2];        int a, b, c;        scanf("%s", str);        if (str[0] == 'Q') {            scanf("%d %d", &a, &b);            printf("%lld\n", Query(1, N, 1, a, b));        } else if (str[0] == 'C') {            scanf("%d %d %d", &a, &b, &c);            Update(1, N, 1, a, b, c);        }    }    return 0;}


0 0
原创粉丝点击