Cod sursa(job #201198)

Utilizator tvladTataranu Vlad tvlad Data 29 iulie 2008 16:23:45
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>

const int N = 100001;

int n,m;
int aib[N];

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

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

int query ( int poz ) {
	int c = 0, s = 0;
	for (; poz > 0; poz -= (1 << c), ++c) {
		s += aib[poz];
		while (!(poz & (1 << c))) ++c;
	}
	return s;
}

int main() {
	freopen("aib.in","rt",stdin);
	freopen("aib.out","wt",stdout);
	scanf("%d %d",&n,&m);
	for (int i = 1, a; i <= n; ++i) {
		scanf("%d",&a);
		update(i,a);
	}
	for (int x, y, z; m; --m) {
		scanf("%d",&x);
		if (x == 0) {
			scanf("%d %d",&y,&z);
			update(y,z);
		} else
		if (x == 1) {
			scanf("%d %d",&y,&z);
			printf("%d\n",query(z)-query(y-1));
		} else {
			scanf("%d",&y);
			printf("%d\n",search(y));
		}
	}
	return 0;
}