Cod sursa(job #184874)

Utilizator bogdanhm999Casu-Pop Bogdan bogdanhm999 Data 24 aprilie 2008 14:11:00
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <stdio.h>

long A[100005],N,m,i,x,y,t;

void update (long ind, long val){
   long poz=0;
   while (ind<=N){
         A[ind]+=val;
         while (!(ind&(1<<poz)))poz++;
         ind+=1<<poz;
         poz++;
   }
}

void query(long x, long y){
     long poz=0,s=0;
     x--;
     while (x){
           s-=A[x];
           while (!(x&(1<<poz)))poz++;
           x-=1<<poz;
           poz++;
     }
     poz=0;
     while (y){
           s+=A[y];
           while (!(y&(1<<poz)))poz++;
           y-=1<<poz;
           poz++;
     }
     printf("%ld\n",s);
}

void search(long x){
    long i,step=1;
    while (step<N)step<<=1;
    step<<=1;
    
    for (i=0;step;step>>=1)
        if (i+step<=N)
           if (x>=A[i+step]){
              i+=step;
              x-= A[i];
              if (!x){printf("%ld\n",i); return;}
           }
    printf("-1");
}

int main(){
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    
    scanf("%ld %ld",&N,&m);
    for (i=1;i<=N;i++){
        scanf("%ld",&x);
        update(i,x);
    }
    for (i=1;i<=m;i++){
        scanf("%ld",&t);
        if (t==0){
           scanf("%ld %ld",&x,&y);
           update(x,y);
        }
        else if (t==1){
                scanf("%ld %ld",&x,&y);
                query(x,y);
             }
             else{ scanf("%ld",&x); search(x); }
    }
return 0;
}