Cod sursa(job #3266290)

Utilizator Andercau_VasileAndercau Vasile Andercau_Vasile Data 7 ianuarie 2025 11:29:36
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
using namespace std;

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

#define NMAX 100005

int aib[NMAX];

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

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

int caut(int val, int n) {
    int step;
    for (step = 1; step < n; step <<= 1);

    int poz;
    for (poz = 0; step > 0; step >>= 1) {
        if (poz + step <= n) {
            if (aib[poz + step] <= val) {
                val -= aib[poz + step];
                poz += step;
            }
        }
    }
    return poz;
}

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

    for (int i = 1; i <= m; ++i) {
        int op;
        fin >> op;

        if (op == 0) {
            int a, b;
            fin >> a >> b;

            update(a, b, n);
        } else if (op == 1) {
            int a, b;
            fin >> a >> b;

            fout << query(b) - query(a - 1) << '\n';
        } else {
            int a;
            fin >> a;

            int poz = caut(a - 1, n);
            if (query(poz + 1) == a) {
                fout << poz + 1 << '\n';
            } else {
                fout << "-1\n";
            }
        }
    }
    return 0;
}