Cod sursa(job #919980)

Utilizator FayedStratulat Alexandru Fayed Data 19 martie 2013 22:41:32
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <cstdio>
#define NMAX 100001

int Arb[NMAX];
int n,k,m;

inline void Update(int x,int ind){

    int bit=0;
        while(ind<=n){

                Arb[ind]+=x;
            while(!(ind & (1<<bit)))
                ++bit;
            ind = ind + (1<<bit);
            bit++;
        }
}

inline int Query(int ind){

int Sum = 0,bit=0;
        while(ind > 0){
            Sum+=Arb[ind];
                    while(!(ind & (1<<bit)))
                        ++bit;
                        ind = ind - (1<<bit);
                        bit++;
        }
    return Sum;
}

inline int Search(int x){

    int step,ind;
    for (step = 1;step < n; step <<= 1 );
     for(ind =0; step;step >>= 1 )
    {   if(ind + step <= n)
         {
            if( x >= Arb[ind+step] )
            {
                ind += step, x-= Arb[ind];
                if (!x) return ind;
            }
         }
    }
return -1;
}

inline void solve(){

    int x,y,cod;
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(register int i=1;i<=n;++i){
        scanf("%d",&x);
        Update(x,i);
    }

    while(m){

        scanf("%d",&cod);
            if(cod < 2){
                scanf("%d%d",&x,&y);
                if(!cod) Update(y,x);
                 else printf("%d\n", Query(y) - Query(x-1));
            }
        else {
            scanf("%d",&x);
            printf("%d\n",Search(x));
        }
    --m;
    }
}

int main(){

    solve();

return 0;
}