Cod sursa(job #2299329)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 9 decembrie 2018 12:28:38
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 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 = -1, p = 1 << 17;
    while(p > 0) {
        if((i + p <= n) && query(i + p) <= x)
            i += p;
        p >>= 1;
    }
    if(query(i) != x)
        return -1;
    return i;
}

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;
}