Cod sursa(job #600117)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 30 iunie 2011 16:32:41
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include<stdio.h>

#define maxN 100005

FILE*f=fopen("aib.in","r");
FILE*g=fopen("aib.out","w");

int n,m,i,x,Op,val,a,b,poz,aib[maxN],step,p2,next,start;

inline int lsb ( int poz ){
	return poz&-poz;
}

inline void update ( int poz , int val ){
	
	while ( poz <= n ){
		aib[poz] += val;
		poz += lsb(poz);
	}
}

inline int query_sum ( int poz ){
	int s = 0;
	
	while ( poz ){
		s += aib[poz];
		poz -= lsb(poz);
	}
	
	return s;
}

inline int query_sum ( int a, int b ){
	
	return query_sum(b) - query_sum(a-1);
}

inline int query_pos ( int val ){
	
	for ( start = 0, step = p2; step ; step >>= 1 ){
		next = start + step;
		
		if ( next <= n ){
			if ( aib[next] <= val ){
				val -= aib[next];
				start = next;
				
				if ( !val )
					return start;
			}
		}
	}
	
	return -1;
}

int main () {
	
	fscanf(f,"%d %d",&n,&m);
	
	for ( p2 = 1; p2 <= n ; p2 <<= 1 );
	
	for ( i = 1 ; i <= n ; ++i ){
		fscanf(f,"%d",&x);
		update(i,x);
	}
	
	for ( i = 1 ; i <= m ; ++i ){
		fscanf(f,"%d",&Op);
		
		if ( Op == 0 ){
			fscanf(f,"%d %d",&poz,&val);
			update(poz,val);
		}
		else{
			if ( Op == 1 ){
				fscanf(f,"%d %d",&a,&b);
				fprintf( g,"%d\n",query_sum(a,b) );
			}
			else{
				fscanf(f,"%d",&val);
				fprintf( g,"%d\n",query_pos(val) );
			}
		}
	}
	
	fclose(f);
	fclose(g);
	
	return 0;
}