Dynamic Range Sum Queries

Dynamic Range Sum Queries
CSES easy

You are given an array of \(n\) integers and \(q\) queries of two types:

  • 1 k u: set the value at position \(k\) to \(u\);
  • 2 a b: find the sum of the values at positions \(a\) to \(b\).

Constraints:

  • \(1 \le n, q \le 2 \cdot 10^5\)
  • \(1 \le x_i, u \le 10^9\)
  • \(1 \le k \le n\)
  • \(1 \le a \le b \le n\)

Input:

  • First line: two integers \(n\) and \(q\).
  • Second line: \(n\) integers \(x_1, x_2, \ldots, x_n\).
  • Next \(q\) lines: one query each, 1 k u or 2 a b.

Output:

  • For each query of type \(2\), one line with the sum.

Example:

Input:

8 4
3 2 4 5 1 1 5 3
2 1 4
2 5 6
1 3 1
2 1 4

Output:

14
2
11
Solution

This is the sum segment tree from the lesson on segment trees, without any changes to the algorithm: pointUpdate for type \(1\) and query(1, 1, N, a, b) for type \(2\).

The only difference is the type of the values in the tree. A sum can be up to \(2 \cdot 10^5 \cdot 10^9 = 2 \cdot 10^{14}\), which does not fit in int, so seg and query use long long.

Each query takes \(O(\log n)\) time.

#include <iostream>
using namespace std;

const int MAXN = 200000;
const int N = 262144;  // the first power of two that is at least MAXN

long long seg[N * 2];
int a[MAXN];

long long query(int id, int l, int r, int ql, int qr) {
    // check if disjoint
    if (ql > r || l > qr) {
        return 0;
    }
    // check if [ql, qr] fully covers [l, r]
    if (ql <= l && r <= qr) {
        return seg[id];
    }
    // recurse and merge
    int m = (l + r) / 2;
    return query(id * 2, l, m, ql, qr) + query(id * 2 + 1, m + 1, r, ql, qr);
}

void pointUpdate(int j, int v) {
    a[j - 1] = v;
    int idx = j + N - 1;
    seg[idx] = v;
    // reconstruct all ancestors
    for (int i = idx / 2; i > 0; i /= 2) {
        seg[i] = seg[i * 2] + seg[i * 2 + 1];
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, q;
    cin >> n >> q;

    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    for (int i = 0; i < n; i++) {
        seg[i + N] = a[i];
    }
    for (int i = n + N; i < 2*N; i++) {
        seg[i] = 0;  // padded value depends on the segment tree
    }
    for (int i = N - 1; i > 0; i--) {
        seg[i] = seg[i * 2] + seg[i * 2 + 1];
    }

    while (q--) {
        int type;
        cin >> type;

        if (type == 1) {
            int k, u;
            cin >> k >> u;
            pointUpdate(k, u);
        } else {
            int l, r;
            cin >> l >> r;
            cout << query(1, 1, N, l, r) << "\n";
        }
    }
}