Cod sursa(job #1609619)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 22 februarie 2016 21:42:41
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <cstring>

using namespace std;

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

class Aib {

private:

	int dim;
	vector<int> aib;

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

public:

	Aib(int dim) {

		this->dim = dim;
		aib.resize(dim + 5, 0);

	}

	void update(int pos, int val) {

		for (int i = pos; i <= dim; i += lsb(i))
			aib[i] += val;

	}

	int query1(int pos) {

		int ans = 0;
		for (int i = pos; i; i -= lsb(i))
			ans += aib[i];
		
		return ans;

	}

	int query2(int val) {

		int sum = 0, step = 1;
		while (step < dim)
			step <<= 1;

		int i;
		for (i = 0; step; step >>= 1) {

			if (i + step > dim)
				continue;

			if (sum + aib[i + step] < val) {
				sum += aib[i + step];
				i += step;
			}

		}

		if (i < dim && query1(i + 1) == val)
			return i + 1;
		else
			return -1;

	}

} *aib;

int main() {

	int n, m;
	fin >> n >> m;

	aib = new Aib(n);

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

		int x;
		fin >> x;

		aib->update(i, x);

	}

	while (m--) {

		int op;
		fin >> op;

		if (op == 0) {

			int a, b;
			fin >> a >> b;

			aib->update(a, b);

		}
		else if (op == 1) {

			int a, b;
			fin >> a >> b;

			fout << aib->query1(b) - aib->query1(a - 1) << '\n';

		}
		else {

			int a;
			fin >> a;

			fout << aib->query2(a) << '\n';

		}

	}

	return 0;

}

//Trust me, I'm the Doctor!