Cod sursa(job #3141758)

Utilizator Mihai_PopescuMihai Popescu Mihai_Popescu Data 16 iulie 2023 11:35:45
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
using namespace std;

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

#define NMAX 100005

int aib[NMAX];

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

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

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

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 c;
        fin >> c;
        if (c == 0) {
            int x, y;
            fin >> x >> y;
            update(x, y, n);
        } else if (c == 1) {
            int x, y;
            fin >> x >> y;
            fout << query(y) - query(x - 1) << '\n';
        } else {
            int x;
            fin >> x;
            int poz = caut(x - 1, n);
            if (query(poz + 1) == x) {
                fout << poz + 1 << '\n';
            } else {
                fout << "-1\n";
            }
        }
    }
    return 0;
}