Cod sursa(job #1703595)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 17 mai 2016 10:52:17
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>

using namespace std;

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

int x, y, cer;
int arb[100005];
int n, m, i, a, b;

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

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

int bs(int val){
    int step = 1, i;
    while (step < n)
        step *= 2;
    for (i = 0; step; step /= 2){
        if (i+step <= n){
            if (sum(i+step) == val)
                return i+step;
            else if (sum(i+step) < val)
                i += step;
        }
    }
    return -1;
}

int main(){
    f >> n >> m;
    for (i = 1; i <= n; i++){
        f >> a;
        add(i, a);
    }

    while (m){
        f >> cer;
        if (cer < 2){
            f >> a >> b;
            if (cer == 0)
                add(a, b);
            else
                g << sum(b) - sum(a-1) << '\n';
        }
        else{
            f >> a;
            g << bs(a) << '\n';
        }
        m--;
    }

    return 0;
}