Cod sursa(job #1426379)

Utilizator gabi.cristacheGabi Cristache gabi.cristache Data 29 aprilie 2015 16:54:19
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>

#define MaxN 100005
#define MaxM 150005

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

int N, M;
int aib[MaxN];

int search(int value) {
	int step = 1, i = 0;

	for (; step < N; step <<= 1);
	
	for (; step > 0; step >>= 1) {
		if (i + step <= N) {
			if (value >= aib[i + step]) {
				i += step;
				value -= aib[i];

				if (value == 0)
					return i;
			}
		}
	}

	return -1;
}

void update(int poz, int value) {
	while (poz <= N) {
		aib[poz] += value;

		int zeroDigits = 0;
		while (((1 << zeroDigits) & poz) == 0)
			++zeroDigits;
		poz += (1 << zeroDigits);
	}
}

int query(int poz) {
	int result = 0;
	while (poz > 0) {
		result += aib[poz];

		int zeroDigits = 0;
		while (((1 << zeroDigits) & poz) == 0)
			++zeroDigits;
		poz -= (1 << zeroDigits);
	}
	return result;
}

int main() {
	fin >> N >> M;

	for (int i = 1; i <= N; ++i) {
		int x;
		fin >> x;
		update(i, x);
	}

	for (int i = 1; i <= M; ++i) {
		int op, a, b;
		fin >> op;
		if (op == 0) {
			fin >> a >> b;
			update(a, b);
		} else if (op == 1) {
			fin >> a >> b;
			fout << query(b) - query(a - 1) << '\n';
		} else {
			fin >> a;
			fout << search(a) << '\n';
		}
	}

	return 0;
}