Cod sursa(job #2901083)

Utilizator crastanRavariu Eugen crastan Data 12 mai 2022 21:36:47
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

void update(int *arbIB, int n, int poz, int val){
    int ind = poz+1;
    while(ind <= n){
        arbIB[ind] += val;
        ind = ind + (ind&(-ind));
    }

}

 int query(int *arbIB, int poz){
     int s = 0;
    int ind = poz;
    while(ind > 0){
        s += arbIB[ind];
        ind = ind - (ind&(-ind));

    }
    return s;
}


int main()
{
    int n, m;
    fin >> n >> m;
     int arbIB[n+5]={0};

    for(int i = 0; i < n; i++){
        int x;
        fin>>x;
        update(arbIB, n, i, x);
    }

    for(int i = 0; i < m; i++){
         int t,x,y;
        fin >> t ;
        if(t == 1){
            fin >> x >> y;
            fout << query(arbIB, y) - query(arbIB, x - 1) << '\n';
        } else if(t == 0){
            fin >> x >> y;
            update(arbIB, n, x-1, y);
        } else {
            fin >> x;
            int ind = 0;
            for(int j = 17; j >= 0; j--){
                ind += (1<<j);

                if(ind <= n){
                     int q = query(arbIB, ind);
                    if(q==x)break;
                    if(q <= x)
                        continue;
                }
                ind -= (1<<j);
            }

            if(query(arbIB, ind)!=x)ind = -1;
            if(ind == 0) ind = -1;
            fout << ind << "\n";
        }
    }
    return 0;
}