Cod sursa(job #2783549)

Utilizator George_CristianGeorge Dan-Cristian George_Cristian Data 14 octombrie 2021 18:16:01
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>

using namespace std;

ifstream f("aib.in");
ofstream g("aib.out");

int n, m, aib[100005];

void actualizare(int poz, int val) {
    while (poz <= n) {
        aib[poz] += val;
        poz += poz & (-poz);
    }
}

void citire() {
    f >> n >> m;
    int x;
    for (int i = 1; i <= n; ++i) {
        f >> x;
        actualizare(i, x);
    }
}

int suma(int poz) {
    int s = 0;
    while (poz > 0) {
        s += aib[poz];
        poz -= poz & (-poz);
    }
    return s;
}

int cautare_binara(int val) {
    int st = 1, dr = n, mij;
    while (st <= dr) {
        mij = (st + dr) / 2;
        if (suma(mij) >= val)
            dr = mij - 1;
        else
            st = mij + 1;
    }
    if (suma(st) == val)
        return st;
    return -1;
}

void rezolvare() {
    int op, a, b;
    for (int i = 1; i <= m; ++i) {
        f >> op >> a;
        if (op == 0) {
            f >> b;
            actualizare(a, b);
        } else if (op == 1) {
            f >> b;
            g << suma(b) - suma(a - 1) << '\n';
        } else
            g << cautare_binara(a) << '\n';
    }
}

int main() {
    citire();
    rezolvare();
    return 0;
}