Cod sursa(job #3371025)

Utilizator G_b_yZamfirache Gabriel G_b_y Data 28 octombrie 2026 12:15:25
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5 + 5;
int N, M, v[NMAX], aib[NMAX];

void update (int i, int delta) {
    while (i <= N) {
        aib[i] += delta;
        i += (i&-i);
    }
}

int query (int i) {
    int ans = 0;
    while (i > 0) {
        ans += aib[i];
        i -= (i&-i);
    }
    return ans;
}

int cb_patrascu (int target) {
    int lg = 1;
    while (lg <= N / 2) {
        lg <<= 1;
    }
    int sum = 0, index = 0;
    while (lg > 0) {
        int next = index + lg;
        if (next <= N && sum + aib[next] < target) {
            sum += aib[next];
            index = next;
        }
        lg /= 2;
    }

    long long rez = index + 1;
    if (rez <= N && query(rez) == target) {
        return rez;
    }
    return -1;
}

void solve () {
    int type, a, b;
    in >> type;
    if (type == 0) {
        in >> a >> b;
        update(a, b);
    } else if (type == 1) {
        in >> a >> b;
        out << query(b) - query(a - 1) << '\n';
    } else {
        in >> a;
        out << cb_patrascu(a) << '\n';
    }
}

int main () {
    in >> N >> M;
    for (int i = 1; i <= N; ++i) {
        in >> v[i];
        update(i, v[i]);
    }
    while (M--) {
        solve();
    }
    return 0;
}