Cod sursa(job #3141038)

Utilizator Vasilescu_CosminVasilescu Cosmin Vasilescu_Cosmin Data 11 iulie 2023 21:38:56
Problema Arbori indexati binar Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include<bits/stdc++.h>

using namespace std;

#define ll long long

ifstream in("aib.in");
ofstream out("aib.out");

int n, q, v[100001], aib[1200005];

void update(int pos, int val) {
    for (int i = pos; i <= n; i += (i & (-i))) {
        aib[i] += val;
    }
}

int compute_cumulative(int pos) {
    int ans = 0;
    for (int i = pos; i >= 1; i -= (i & (-i)))
        ans += aib[i];
    return ans;
}

int search(int sum) {
    int step = 1;
    while (step <= n)
        step <<= 1;
    step >>= 1;

    int pos = 0;

    while (step && sum) {
        if (aib[pos + step] <= sum) {
            sum -= aib[pos + step];
            pos += step;
        }
        step /= 2;
    }
    if(sum == 0)
        return pos;
    return -1;
}

int main() {
    in >> n >> q;
    for (int i = 1; i <= n; ++i)
        in >> v[i], update(i, v[i]);
    for (int i = 1; i <= q; i++) {
        int type;
        in >> type;
        if (type == 0) {
            int a, b;
            in >> a >> b;
            update(a, b);
        } else if (type == 1) {
            int l, r;
            in >> l >> r;
            out << compute_cumulative(r) - compute_cumulative(l - 1) << '\n';
        } else {
            int sum;
            in >> sum;
            out << search(sum) << '\n';
        }
    }
    return 0;
}