Cod sursa(job #727863)

Utilizator mottyMatei-Dan Epure motty Data 28 martie 2012 12:27:20
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>

using namespace std;

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

const int N = 100001;

int n, m;
int aib[N];

inline int jump(int x) {
	return (-x) & x;
}

void read() {
	in >> n >> m;

	for (int i = 1; i <= n; ++i) {
		int x;
		in >> x;

		aib[i] += x;

		if (i + jump(i) <= n)
			aib[i + jump(i)] += aib[i];
	}
}

void add(int poz, int val) {
	while (poz <= n) {
		aib[poz] += val;
		poz += jump(poz);
	}
}

int sum(int a, int b) {
	int sumA = 0;
	int sumB = 0;

	while (a) {
		sumA += aib[a];
		a -= jump(a);
	}

	while (b) {
		sumB += aib[b];
		b -= jump(b);
	}

	return sumB - sumA;
}

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

			if (val == 0)
				return i;
		}

	return -1;
}

void solve() {
	while (m--) {
		int type;
		in >> type;

		if (type == 0) {
			int a, b;
			in >> a >> b;

			add(a, b);
		}
		if (type == 1) {
			int a, b;
			in >> a >> b;

			out << sum(a - 1, b) << "\n";
		}
		if (type == 2) {
			int a;
			in >> a;

			out << findVal(a) << "\n";
		}
	}
}

int main() {
	read();
	solve();

	return 0;
}