POJ3468 A Simple Problem with Integers---樹狀陣列(區間問題)

Ashenkkk發表於2020-11-04

POJ3468 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

Hint

The sums may exceed the range of 32-bit integers.

Code

#include<iostream>
#include<cstring>

using namespace std;

const int maxn = 1e5 + 3;

typedef long long ll;

// 思路是通過公式演變過來的,這裡不多講
// 第一個陣列存範圍變化的字首和
// 第二個陣列存 i * tree[0][i]的字首和
// 求解 get(l, r) = (sum[r] + (r + 1) * get(0, r) - get(1, r))  
// - (sum[l - 1] + l * get(0, l - 1) - get(1, l - 1))

char op;
ll sum[maxn], tree[2][maxn], n, q, l, r, v, ans;

inline ll lowbit(ll x) { return x & -x; }

void add(ll f, ll x, ll v) { for (; x <= n; x += lowbit(x)) tree[f][x] += v; }

ll get(ll f, ll x) { 
    ll ans = 0;
    for (; x; x -= lowbit(x)) ans += tree[f][x];
    return ans;
}

inline ll read() {
    ll f = 1, x = 0; char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - 48, ch = getchar();
    return f * x;
}

int main() {
    memset(tree, 0, sizeof tree);
    memset(sum, 0, sizeof sum);
    n = read(), q = read();
    for (ll i = 1; i <= n; i++) sum[i] = sum[i - 1] + read();
    while (q--) {
        op = getchar(), l = read(), r = read();
        if (op == 'Q') {
            ans = (sum[r] + (r + 1) * get(0, r) - get(1, r))  - (sum[l - 1] + l * get(0, l - 1) - get(1, l - 1));
            cout << ans << endl;
        }
        else {
            v = read();
            add(0, l, v);
            add(0, r + 1, -v);
            add(1, l, v * l);
            add(1, r + 1, -v * (r + 1));
        }
    }
    return 0;
}

相關文章