Cod sursa(job #1796533)

Utilizator DobosDobos Paul Dobos Data 3 noiembrie 2016 16:14:23
Problema Arbori indexati binar Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

const int NMAX = 10005;

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

int AIB[NMAX],n;


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

int query(int poz){

    int C = 0,S = 0;
    while(poz > 0){
        S += AIB[poz];
        while(!(poz & (1 << C))) C++;
        poz -= (1<<C);
        C++;

    }
    return S;
}

int Search(int val){

    int step;

    for(step = 1; step < n; step <<= 1);

    for(int i = 0; step > 0; step >>= 1){

        if(i + step <= n){
            if(val >= AIB[step + i]){
                i += step; val -= AIB[i];
                if(!val) return i;
            }
        }

    }

    return -1;
}


int main()
{
    ios :: sync_with_stdio(false);
    fin.tie(NULL);

    int m,k,x,y;

    fin >> n >> m;

    for(int i = 1; i <= n; i++){
        fin >> x;
        update(i,x);
    }
    for(int i = 1; i <= m; i++){
        fin >> k ;
        if(k < 2){
            fin >> x >> y;
            if(k == 0){
                update(x,y);
            } else {
                fout << query(y) - query(x - 1) << "\n";
            }
        } else {
            fin >> x;
            fout << Search(x) << "\n";

        }
    }

    return 0;
}