POJ 3468 A Simple Problem with Integers

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

线段树,区间修改,区间求和
CODE:
#include <iostream>
#include <cstdio>
#include <cstring>
#define REP(i, s, n) for(int i = s; i <= n; i ++)
#define REP_(i, s, n) for(int i = n; i >= s; i --)
#define MAX_N 100000 + 10

using namespace std;

int n, q, data[MAX_N];
typedef long long LL;
struct segtree{
    int l, r;
    LL sum, c;
}a[MAX_N << 2];

void update(int i){
    int t1 = i << 1, t2 = t1 + 1;
    a[i].sum = a[t1].sum + a[t2].sum;
}

void Make_Tree(int i, int l, int r){
    a[i].l = l; a[i].r = r;
    if(a[i].l == a[i].r){
        a[i].sum = data[l]; a[i].c = 0;
        return;
    }
    int mid = (a[i].l + a[i].r) >> 1, t1 = i << 1, t2 = t1 + 1;
    Make_Tree(t1, l, mid); Make_Tree(t2, mid + 1, r);
    update(i);
}

void lazy(int i){
    int t1 = i << 1, t2 = t1 + 1;
    a[t1].sum += (LL)(a[t1].r - a[t1].l + 1) * a[i].c; a[t2].sum += (LL)(a[t2].r - a[t2].l + 1) * a[i].c;
    a[t1].c += a[i].c; a[t2].c += a[i].c;
    a[i].c = 0;
}

void Modify(int i, int l, int r, int c){
    if(l > r) return;
    if(a[i].l == l && a[i].r == r){
        a[i].c += c; a[i].sum += (LL)(r - l + 1) * c;
        return;
    }
    lazy(i);
    int mid = (a[i].l + a[i].r) >> 1, t1 = i << 1, t2 = t1 + 1;
    if(r <= mid) Modify(t1, l, r, c);
    else if(l > mid) Modify(t2, l, r, c);
    else Modify(t1, l, mid, c), Modify(t2, mid + 1, r, c);
    update(i);
}

LL Query(int i, int l, int r){
    if(l > r) return 0;
    if(a[i].l == l && a[i].r == r) return a[i].sum;
    lazy(i);
    int mid = (a[i].l + a[i].r) >> 1, t1 = i << 1, t2 = t1 + 1;
    if(r <= mid) return Query(t1, l, r);
    else if(l > mid) return Query(t2, l, r);
    else return Query(t1, l, mid) + Query(t2, mid + 1, r); 
}

int main(){
    freopen("A.in", "r", stdin);
    scanf("%d%d", &n, &q);
    REP(i, 1, n) scanf("%d", &data[i]);
    Make_Tree(1, 1, n);
    char s[3]; int x, y, k;
    while(q --){
        scanf("%s", s);
        if(s[0] == 'C') scanf("%d%d%d", &x, &y, &k), Modify(1, x, y, k);
        else scanf("%d%d", &x, &y), cout << Query(1, x, y) << "\n";
    }
    return 0;
}

 

 
posted @ 2015-06-29 20:57  ALXPCUN  阅读(104)  评论(0编辑  收藏  举报