Cod sursa(job #1182892)

Utilizator cristian.enciuCristian Enciu cristian.enciu Data 7 mai 2014 22:55:52
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <stdio.h>

int arb[100001];

int n;

void update(int poz, int val)
{
	int c = 0;
	while(poz <= n){
		arb[poz] += val;
		while(!(poz & (1<<c))) c++;
		poz += (1<<c);
		c += 1;
	}
}

int get(int poz)
{
	int c = 0, sum = 0;
	while(poz > 0){
		sum += arb[poz];
		while(!(poz & (1<<c))) ++c;
		poz -= (1<<c);
		c  += 1;
	}

	return sum;
}

int search(int val)
{
	int i, step;

	for(step = 1 ; step < n ; step  <<=1);

	for(i = 0 ; step > 0 ; step >>= 1){
		if(i + step <= n){
			if(val >= arb[i+step])
			{
				i += step;
				val -= arb[i];
				if(!val) return i;
			}
		}
	}
	return -1;
}

int main()
{
	int i, m, x, y;
	FILE *in, *out;

	in = fopen("aib.in", "r");
	out = fopen("aib.out", "w");

	fscanf(in, "%d%d", &n, &m);
	for(i = 1 ; i <=n ; ++i){
		fscanf(in, "%d", &x);
		update(i, x);
	}

	while(m-- > 0){
		fscanf(in, "%d", &i);
		if(i < 2){
			fscanf(in, "%d%d",&x,&y);
			if(i == 0) update(x, y);
			else fprintf(out, "%d\n",get(y)-get(x-1));
		}
		else{
			fscanf(in, "%d", &x);
			fprintf(out, "%d\n", search(x));
		}
	}

	fclose(in);
	fclose(out);

	return 0;
}