Cod sursa(job #2200014)

Utilizator emiemiEmi Necula emiemi Data 29 aprilie 2018 23:33:05
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>

using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");

int a, b, m, n, c, v[100005], u[100005];

int det(int x) {
	int t = 1;
	while ((t & x) == 0)
		t <<= 1;
	return t;
}

void update() {
	int x = a;
	while (x <= n) {
		u[x] += b;
		x += det(x);
	}
}

int sum(int x) {
	int act = x;
	int suma = 0;
	while (act > 0) {
		suma += u[act];
		act -= det(act);
	}
	return suma;
}

void query() {
	g << sum(b) - sum(a - 1) << '\n';
}

void getPosition() {
	int step = 1, i, val;
	
	while (step <= n)
		step <<= 1;

	i = 0;
	val = a;
	while (step) {
		if (i + step <= n) {
			if (u[i + step] <= val) {
				val -= u[i + step];
				i += step;
			}
		}
		step >>= 1;
	}
	g << i << '\n';
}

int main() {
	int i;
	f >> n >> m;
	for (i = 1; i <= n; ++i) {
		a = i;
		f >> b;
		update();
	}

	for (i = 1; i <= m; ++i) {
		f >> c >> a;
		switch (c) {
		case 0:
			f >> b;
			update();
			break;
		case 1:
			f >> b;
			query();
			break;
		case 2:
			getPosition();
			break;
		}
	}

	return 0;
}