Cod sursa(job #1327886)

Utilizator vladrochianVlad Rochian vladrochian Data 27 ianuarie 2015 12:55:53
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
using namespace std;

const int kMaxN = 100005;

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

int N, M, aib[kMaxN], pw2;

void Update(int pos, int val) {
	for (int i = pos; i <= N; i += i & (-i))
		aib[i] += val;
}

int QuerySum(int pos) {
	int sol = 0;
	for (int i = pos; i > 0; i -= i & (-i))
		sol += aib[i];
	return sol;
}

int QuerySearch(int val) {
	for (int pos = 0, step = pw2; step; step >>= 1)
		if ((pos ^ step) <= N && aib[pos ^ step] <= val) {
			pos ^= step;
			val -= aib[pos];
			if (!val)
				return pos;
		}
	return -1;
}

int main() {
	fin >> N >> M;
	for (pw2 = 1; pw2 <= N; pw2 <<= 1);
	pw2 >>= 1;
	for (int i = 1; i <= N; ++i) {
		int x;
		fin >> x;
		Update(i, x);
	}
	while (M--) {
		int t, a, b;
		fin >> t;
		if (t == 0) {
			fin >> a >> b;
			Update(a, b);
		} else if (t == 1) {
			fin >> a >> b;
			fout << QuerySum(b) - QuerySum(a - 1) << "\n";
		} else {
			fin >> a;
			fout << QuerySearch(a) << "\n";
		}
	}
	return 0;
}