Cod sursa(job #2582245)

Utilizator CosminMorarMorar Cosmin Andrei CosminMorar Data 16 martie 2020 15:34:52
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <iostream>
#include <fstream>
using namespace std;
FILE* fin=fopen("aib.in","r");
ofstream fout("aib.out");
const unsigned maxb=100192;
char buf[maxb];
unsigned ptr=maxb;

inline unsigned getInt(){
    unsigned nr=0;
    while(buf[ptr]<'0'||'9'<buf[ptr])
    if(++ptr>=maxb)
        fread(buf,maxb,1,fin),ptr=0;
    while('0'<=buf[ptr]&&buf[ptr]<='9'){
        nr=nr*10+buf[ptr]-'0';
        if(++ptr>=maxb)
            fread(buf,maxb,1,fin),ptr=0;
    }
    return nr;
}

int n, m, sol;
int arb[400100];

void update(int nod, int st, int dr, int pos, int value) {
    if (st == dr) {
        arb[nod] += value;
        return;
    }

    int mij = (st + dr) / 2;

    if (pos <= mij)
        update(2 * nod, st, mij, pos, value);
    else
        update(2 * nod + 1, mij + 1, dr, pos, value);

    arb[nod] = arb[2 * nod] + arb[2 * nod + 1];
}

long long ask(int nod, int st, int dr, int a, int b) {
    if (a <= st && dr <= b)
        return arb[nod];

    int mij = (st + dr) / 2;
    long long sol = 0;

    if (a <= mij)
        sol += ask(2 * nod, st, mij, a, b);
    if (b > mij)
        sol += ask(2 * nod + 1, mij + 1, dr, a, b);

    return sol;
}

void cautaInArbore(int nod, int st, int dr, int suma) {
    if (st == dr) {
        if (arb[nod] == suma)
            sol = st;
        return;
    }

    int mij = (st + dr) / 2;

    if (suma <= arb[2 * nod])
        cautaInArbore(2 * nod, st, mij, suma);
    else
        cautaInArbore(2 * nod + 1, mij + 1, dr, suma - arb[2 * nod]);
}

int main() {
    n = getInt();
    m = getInt();

    for (int i = 1; i <= n; i++) {
        int nr = getInt();
        update(1, 1, n, i, nr);
    }

    for (int i = 1; i <= m; i++) {
        int c = getInt();
        if (c == 0) {
            int a = getInt();
            int b = getInt();
            update(1, 1, n, a, b);
        } else if (c == 1) {
            int a = getInt();
            int b = getInt();
            fout << ask(1, 1, n, a, b) << '\n';
        } else {
            int a = getInt();
            sol = -1;
            cautaInArbore(1, 1, n, a);
            fout << sol << '\n';
        }
    }
    return 0;
}