Cod sursa(job #2441158)

Utilizator uvIanisUrsu Ianis Vlad uvIanis Data 20 iulie 2019 00:04:15
Problema Arbori indexati binar Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define MAXN int(1e5)

typedef unsigned int uInt;

uInt n, m;
uInt tree[MAXN+1];

inline uInt next_index(uInt i){
    return i + (i&-i);
}

inline uInt prev_index(uInt i){
    return i - (i&-i);
}


void update(uInt a, uInt b){
    uInt index = a;
    do{
        tree[index] += b;

    }while((index = next_index(index)) <= n);
}

uInt query(uInt x){
    uInt index = x;
    uInt sum = 0;
    do{
        sum += tree[index];

    }while((index = prev_index(index)));

    return sum;
}

inline uInt interval_query(uInt a, uInt b){
    return query(b) - query(a-1);
}

int search(uInt a){
    uInt index = 1;
    while(index < n) index = (index<<1);

    for(uInt i = 0; index != 0; index = (index>>1)){
        if(i + index <= n){
            if(tree[i+index] <= a){
                i = i + index;
                a -= tree[i];

                if(a==0) return i;
            }
        }
    }

    return -1;
}

int main()
{
    std::ifstream fin("aib.in");
    std::ofstream fout("aib.out");

    fin>>n>>m;

    uInt x;
    for(uInt i=1; i<=n; i++){
        fin>>x;
        tree[i]+= x;
        if(i+(i&-i)<=n) tree[i+(i&-i)] += tree[i];
    }

   uInt a, b, c;
   for(uInt i=1; i<=m; i++){

        fin>>c;

        fin>>a; if(c!=2) fin>>b;

        switch(c){
            case 0:
                update(a, b);
                break;

            case 1:
                fout<<interval_query(a, b)<<std::endl;
                break;

            default:
                fout<<search(a)<<std::endl;
        }
   }

}