Cod sursa(job #2299333)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 9 decembrie 2018 12:35:44
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#define d(x) x&(-x)

const int MAX_N = 100000;

using namespace std;

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

int n, m;
int v[MAX_N + 5], AIB[MAX_N + 5];

void update(int p, int x) {
    for(; p <= n; p += d(p))
        AIB[p] +=x;
}

int query(int p) {
    int sum = 0;
    for(; p > 0; p -=d(p))
        sum += AIB[p];

    return sum;
}

int bs(int x) {
    int i = 0, p = (1 << 17);
    while(p > 0) {
        if((i + p <= n) && AIB[i + p] <= x) {
            i += p;
            x -= AIB[i];
            if(x == 0)
                return i;
        }
        p >>= 1;
    }

    return -1;
}

int main() {
    fin >> n >> m;
    for(int i = 1; i <= n; i++) {
        fin >> v[i];
        update(i, v[i]);
    }
    while(m--) {
        int op, a, b;
        fin >> op;
        if(op == 0) {
            fin >> a >> b;
            update(a, b);
        }
        else if(op == 1) {
            fin >> a >> b;
            fout << query(b) - query(a-1) <<'\n';
        }
        else {
            fin >> a;
            fout << bs(a) <<'\n';
        }
    }
    return 0;
}