Cod sursa(job #195505)

Utilizator Matei14Popa-Matei Mihai Matei14 Data 19 iunie 2008 10:11:00
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include<stdio.h>
#include<string.h>
#define bit 100005
int n,m,T;
int Arb[bit];
int C,S;
int query(int poz){
    C=0,S=0;
    while(poz>0){
		S+=Arb[poz];
		while(!(poz&(1<<C)))
			C++;
		poz-=(1<<C);
		C+=1;
    }
    return S;
}
int solve(int val){
    int i,step;
    for(step=1;step<n;step<<=1);
    for(i=0;step;step>>=1){
		if(i+step<=n){
            if(val>=Arb[i+step]){
                i+=step, val-=Arb[i];
                if(!val)
					return i;
            }
		}
    }
    return -1;
}
void update(int poz, int val){
	C=0;
	while(poz<=n){
		Arb[poz]+=val;
		while(!(poz&(1<<C)))
			C++;
		poz+=(1<<C);
		C+=1;
	}
}
int main(){
    memset(Arb,0,sizeof(Arb));
    int K,X,Y;
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;++i){
        scanf("%d",&T);
        update(i,T);
    }
    for(;m;--m){
        scanf("%d",&K);
        if(K<2){
			scanf("%d%d",&X,&Y);
			if(!K)
				update(X,Y);
			else
				printf("%d\n",query(Y)-query(X-1));
        }
        else{
            scanf("%d",&X);
            printf("%d\n", solve(X));
        }
    }
}