Cod sursa(job #3358005)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:51:40
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <vector>
using namespace std;

int N, M;
vector<int> aib;

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

int query(int pos) {
    int sum = 0;
    for (int i = pos; i > 0; i -= i & -i)
        sum += aib[i];
    return sum;
}

int find(int val) {
    int idx = 0, bitMask = 1;
    while (bitMask <= N) bitMask <<= 1;
    for (bitMask >>= 1; bitMask > 0; bitMask >>= 1) {
        int next = idx + bitMask;
        if (next <= N && aib[next] < val) {
            val -= aib[next];
            idx = next;
        }
    }
    if (idx + 1 <= N) return idx + 1;
    return -1;
}

int main() {
    ifstream fin("aib.in");
    ofstream fout("aib.out");

    fin >> N >> M;
    aib.assign(N + 1, 0);

    for (int i = 1; i <= N; ++i) {
        int x; fin >> x;
        update(i, x);
    }

    for (int i = 0; i < M; ++i) {
        int type; fin >> type;
        if (type == 0) {
            int a, b; fin >> a >> b;
            update(a, b);
        } else if (type == 1) {
            int a, b; fin >> a >> b;
            fout << query(b) - query(a - 1) << '\n';
        } else {
            int a; fin >> a;
            if (a == 0) fout << -1 << '\n';
            else {
                int pos = find(a);
                if (pos == -1 || query(pos) - query(pos-1) == 0) fout << -1 << '\n';
                else fout << pos << '\n';
            }
        }
    }

    fin.close();
    fout.close();
    return 0;
}