Cod sursa(job #1148056)

Utilizator iarbaCrestez Paul iarba Data 20 martie 2014 13:21:36
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <cstdio>
using namespace std;
int a[100001],i,n,m,c,s,poz,x,y,val,caz;
void update(int poz, int val)
{
	c=0;
	while(poz<=n){
		a[poz]+=val;
		while(!(poz&(1<<c))){c++;}
		poz+=1<<c;c++;
				 }
}
int query(int poz)
{
	c=0;s=0;
	while(poz){
		s+=a[poz];
		while(!(poz&(1<<c))){c++;}
		poz-=1<<c;c++;
			  }
return s;
}
int search(int val)
{
	s=1;while(s<n){s<<=1;}
	i=0;
	while(s){
		if(i+s<=n){
			if(val>=a[i+s]){
				i+=s;val-=a[i];
				if(!val){return i;}
								}
				  }
		s>>=1;
			   }
return -1;
}
int main()
{
	freopen("aib.in","r",stdin);
	freopen("aib.out","w",stdout);
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;i++){
		scanf("%d",&val);
		update(i,val);
						   }
	while(m--){
		scanf("%d",&caz);
		if(caz==0){
			scanf("%d%d",&i,&val);
			update(i,val);
				}
		if(caz==1){
			scanf("%d%d",&x,&y);
			printf("%d\n",query(y)-query(x-1));
				}
		if(caz==2){
			scanf("%d",&val);
			printf("%d\n",search(val));
				}
			  }
return 0;
}