Cod sursa(job #2225163)

Utilizator Luca19Hritcu Luca Luca19 Data 26 iulie 2018 10:53:12
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>

using namespace std;

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

const int nmax = 100005;
int n, m, i, j, arb[nmax], x, y, cer;

void aduna(int poz, int x) {
    while (poz <= n) {
        arb[poz] += x;
        poz += (poz & -poz);
    }
}

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

int main() {
    f >> n >> m;
    for (i = 1; i <= n; i++) {
        f >> x;
        aduna(i, x);
    }
    for (i = 1; i <= m; i++) {
        f >> cer >> x;
        if (cer == 0) {
            f >> y;
            aduna(x, y);
        } else if (cer == 1) {
            f >> y;
            g << suma(y) - suma(x-1) << '\n';
        } else {
            int p = 1;
            while (p < n) p *= 2;
            int w = 0;
            int ok = 0;
            for (;p > 0; p /= 2) {
                if (w+p > n) continue;
                y = suma(w+p);
                if (y == x) {
                    ok = 1;
                    g << w+p << '\n';
                    break;
                }
                else if (y < x)
                    w += p;
            }
            if (ok == 0)
                g << "-1\n";
        }
    }
}