Cod sursa(job #2968720)

Utilizator cristiWTCristi Tanase cristiWT Data 21 ianuarie 2023 20:38:42
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

#define ll long long

using namespace std;

const int NMAX = 1e5 + 10, mod = 1e9 + 7;
int n, q, x, y, op;

struct aib {
    vector<int> _a;

    void resize(int _n) {
        _a = vector<int>(_n + 10);
    }

    void update(int pos, int val, int _n) {
        while (pos <= _n) {
            _a[pos] += val;
            pos += pos & -pos;
        }
    }

    int query(int pos) {
        int sum = 0;
        while (pos) {
            sum += _a[pos];
            pos -= pos & -pos;
        }
        return sum;
    }
};

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);

    cin >> n >> q;
    aib a;
    a.resize(n);
    for (int i = 1; i <= n; i++) {
        cin >> x;
        a.update(i, x, n);
    }
    while (q--) {
        cin >> op;
        if (op == 0) {
            cin >> x >> y;
            a.update(x, y, n);
        } else if (op == 1) {
            cin >> x >> y;
            cout << a.query(y) - a.query(x - 1) << '\n';
        } else {
            cin >> x;
            int left = 1, right = n, pos = -1;
            while (left <= right) {
                int mid = (left + right) / 2, sum = a.query(mid);
                if (sum == x) {
                    pos = mid;
                    right = mid - 1;
                } else if (sum < x)
                    left = mid + 1;
                else right = mid - 1;
            }
            cout << pos << '\n';
        }
    }
}