Cod sursa(job #2589578)

Utilizator mariaghinescu22Ghinescu Maria mariaghinescu22 Data 26 martie 2020 16:27:15
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int A = 100001;
const int L = 16;
int n, m, t, type, aib[A];

int search(int z) {
	if (z == 0) return -1;
	int p = 0, pas = 1 << L;
	while (pas != 0) {
		if (p + pas <= n && aib[p + pas] <= z) {
			p += pas;
			z -= aib[p];
		}
		pas /= 2;
	}
	if (z != 0) return -1;
	return p;
}

int question(int p) {
	//calc v[1] + v[2] + ... + v[p]
	int s = 0;
	while (p != 0) {
		s += aib[p];
		p -= (p & (-p));
	}
	return s;
}

void update(int p, int val) {
	while (p <= n) {
		aib[p] += val;
		p += (p & (-p));
	}
}

int main() {
	in >> n >> m;
	for (int i = 1; i <= n; i++) {
		in >> t;
		update(i, t);
	}
	for (int i = 1; i <= m; i++) {		
		int x, y;
		in >> type;
		if (type == 0) {
			in >> x >> y;
			update(x, y);
		}
		if (type == 1) {
			in >> x >> y;
			out << question(y) - question(x - 1) << '\n';
		}
		if (type == 2) {
			in >> x;
			out << search(x) << '\n';
		}
	}
	return 0;
}