Cod sursa(job #2431227)

Utilizator bluestorm57Vasile T bluestorm57 Data 18 iunie 2019 18:23:02
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5 + 10;
int arb[NMAX],n,m,t;

void update(int poz, int val){
    int c = 0;
    while(poz <= n){
        arb[poz] += val;
        while(!(poz & (1 << c)))
            c++;
        poz += (1 << c);
        c++;
    }
}

int cauta(int val){
    int i,step;
    for(step = 1 ; step < n ; step <<= 1);
    for(i = 0 ; step; step >>= 1){
        if(i + step <= n){
            if(val >= arb[i + step]){
                i += step;
                val -= arb[i];
                if(!val)
                    return i;
            }
        }
    }
    return -1;
}

int query(int poz){
    int c = 0, s = 0;
    while(poz > 0){
        s += arb[poz];
        while(!(poz & (1 << c)))
            c++;
        poz -= (1 << c);
        ++c;
    }
    return s;
}

int main(){
    int k,x,y,i;
    f >> n >> m;
    for(i = 1 ; i <= n ; i++){
        f >> t;
        update(i,t);
    }
    for(i = 1; i <= m ; i++){
        f >> k;
        if(k < 2){
            f >> x >> y;
            if(!k)
                update(x,y);
            else
                g << query(y) - query(x - 1) << "\n";
        }else{
            f >> x;
            g << cauta(x) << "\n";
        }
    }

    return 0;
}