Cod sursa(job #3134562)

Utilizator Maftei_TudorMaftei Tudor Maftei_Tudor Data 29 mai 2023 16:34:43
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>

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

int n, q, x, tip, a, b, aib[100001];

int lsb(int x) {
    return x & (-x);
}

int query(int pos) {
    int ans = 0;

    while(pos) {
        ans += aib[pos];
        pos -= lsb(pos);
    }

    return ans;
}

void update(int pos, int val) {
    while(pos <= n) {
        aib[pos] += val;
        pos += lsb(pos);
    }
}

int cb(int val) {
    int pw = 1, pos = 0;
    while(pw <= n) {
        pw *= 2;
    }
    pw /= 2;

    while(pw) {
        if(pos + pw <= n)
            if(query(pos + pw) < val) {
                pos += pw;
            }

        pw /= 2;
    }

    return pos + 1;
}

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

    while(q--) {
        fin >> tip;
        if(tip == 0) {
            fin >> a >> b;
            update(a, b);
        }
        else if(tip == 1) {
            fin >> a >> b;
            fout << query(b) - query(a-1) << '\n';
        }
        else {
            fin >> a;
            int rez = cb(a);
            if(query(rez) == a)
                fout << rez << '\n';
            else fout << "-1\n";
        }
    }
    return 0;
}