CSES · 1648

Dynamic Range Sum Queries

This C++ solution uses fenwick tree for CSES 1648 Dynamic Range Sum Queries. Read the reasoning, inspect the code, or try your own test case below.

1648Graphs & treesFenwick treeC++54 lines
Solution082of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Fenwick tree

Dynamic Range Sum Queries matches point assignments and inclusive range-sum queries; the code implements them with a Fenwick tree.

Graphs & trees

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

Dynamic_Range_Sum_Queries.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    using ll = long long;
    using i128 = __int128;
    const int inf = 1e9;
    const ll INF = 2e18; //❄️
    struct BIT {
        int n;
        vector<ll> bit;
        BIT(int n) {
            this->n = n;
            bit.assign(n + 1, 0);
        }
        void add(int pos, ll val) {
            for (int i = pos; i <= n; i += i & -i) {
                bit[i] += val;
            }
        }
        ll sum(int pos) {
           ll res = 0;
            for (int i = pos; i > 0; i -= i & -i) {
                res += bit[i];
            }
            return res;
        }
        ll sum(int l, int r) {
            if (l > r) return 0;
            return sum(r) - sum(l - 1);
        }
     };
    int main() {
        ios::sync_with_stdio(0); cin.tie(0); 
        int n, q; cin >> n >> q;
        BIT bit(n);
        vector<ll> v(n + 1);
        for (int i = 1; i <= n; i++) {
            cin >> v[i];
            bit.add(i, v[i]);
        }
        while (q--) {
            int qry;
            cin >> qry;
            if (qry == 1) {
                int pos; ll val; cin >> pos >> val;
                ll diff = val - v[pos];
                v[pos] = val;
                bit.add(pos, diff);
            } else {
                int l, r; cin >> l >> r;
                cout << bit.sum(l, r) << '\n';
            }
        }
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.