Cod sursa(job #1099083)

Utilizator FayedStratulat Alexandru Fayed Data 5 februarie 2014 15:49:08
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdio>
#define NMAX 100001

int n,m;
int V[NMAX];

void update(int ind,int val){

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

        V[ind]+=val;
            while((ind & (1<<poz)) == 0)
                ++poz;
        ind += (1<<poz);
        poz++;
    }

}

int Sum(int dr){

    int S = 0;
    int poz = 0;
    while(dr > 0){

        S+= V[dr];
        while((dr & (1<<poz)) == 0)
            poz++;
        dr = dr - (1<<poz);
      poz++;
    }
return S;
}

int Search(int x){

    int i, step;

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

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

    return -1;
}

int main(){

    int a,b;
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    scanf("%d%d",&n,&m);
    int val;
    for(register int i=1;i<=n;++i){

        scanf("%d",&val);
        update(i,val);
    }

    int option;
        while(m){

               scanf("%d",&option);

                    if(option < 2){
                        scanf("%d%d",&a,&b);
                        if(!option)
                            update(a,b);
                         else printf("%d\n",Sum(b) - Sum(a-1));
                    }
                        else {scanf("%d",&a);
                            printf("%d\n",Search(a));
                        }
--m;
        }

return 0;
}