Cod sursa(job #710646)

Utilizator Anonymous1010Chilivercu Cristian Anonymous1010 Data 10 martie 2012 15:31:22
Problema Arbori indexati binar Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include<stdio.h>

unsigned int n,m,i,j,sx,sy,x,y,c,pos,a[100002],val;
int ans;


void bs(int,int);

int main()
{
	freopen("aib.in","r",stdin);
	freopen("aib.out","w",stdout);
	
	scanf("%u %u",&n,&m);
	
	for(i=1;i<=n;i++)
	{
		pos=0;
		scanf("%u",&val);
		
		for(j=i;j<=n;pos++)
		{
			a[j]+=val;
			
			for(;!(j&1<<pos);pos++);
			
			j+=1<<pos;
		}
	}
	
	for(;m;m--)
	{
		scanf("%u",&c);
		
		if(c)
		{
			if(c==1)
			{
				scanf("%u %u",&x,&y);
				
				x--;
				
				sx=0;
				pos=0;
				
				for(;x>0;pos++)
				{
					sx+=a[x];
					
					for(;!(x&1<<pos);pos++);
					
					x-=1<<pos;
				}
				
				sy=0;
				pos=0;
				
				for(;y>0;pos++)
				{
					sy+=a[y];
					
					for(;!(y&1<<pos);pos++);
					
					y-=1<<pos;
				}
				
				printf("%u\n",sy-sx);
			}
			else
			{
				scanf("%u",&x);
				ans=0;
				
				bs(1,n);
				
				printf("%d\n",ans);
			}
		}
		else
		{
			pos=0;
			scanf("%u %u",&j,&val);
		
			for(;j<=n;pos++)
			{
				a[j]+=val;
				
				for(;!(j&1<<pos);pos++);
				
				j+=1<<pos;
			}			
		}
	}
	
	return 0;
}

void bs(int l, int r)
{
	int med,s;
	
	if(l<=r){
	
	med=(l+r)/2;
	y=med;
	s=0;
	pos=0;
	
	for(;y>0;pos++)
	{
		s+=a[y];
		
		for(;!(y&1<<pos);pos++);
			
		y-=1<<pos;
	}
	
	if(l==r)
	{
		if(s==x)
			ans=med;
		else
			if(!ans)
				ans=-1;
	}
	else
	{
		if(s==x)
		{
			ans=med;
			bs(l,med-1);
		}
		else
		{
			if(s>x)
				bs(l,med-1);
			else
				bs(med+1,r);
		}
	}
	}
}