Cod sursa(job #3141041)

Utilizator Vasilescu_CosminVasilescu Cosmin Vasilescu_Cosmin Data 11 iulie 2023 21:43:58
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 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;

    int pos = 0;
    int ssum = sum;
    while (step) {
        if (pos + step <=n && aib[pos + step] < sum) {
            sum -= aib[pos + step];
            pos += step;
        }
        step /= 2;
    }
    if(compute_cumulative(pos+1) == ssum)
        return pos+1;
    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;
}