Cod sursa(job #809597)

Utilizator toranagahVlad Badelita toranagah Data 8 noiembrie 2012 18:38:25
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
using namespace std;
const int MAX_N = 100100;
ifstream fin("aib.in");
ofstream fout("aib.out");

int aib[MAX_N];
int N, M;

void update(int pos, int val);
int query(int pos);
int posOfSum(int sum);



int main() {
	fin >> N >> M;
	for (int i = 1; i <= N; ++i) {
		int x;
		fin >> x;
		update(i, x);
	}
	for (int i = 1; i <= M; ++i) {
		int action, a, b;
		fin >> action;
		if (action == 0) {
			fin >> a >> b;
			update(a, b);
		} else if (action == 1) {
			fin >> a >> b;
			fout << query(b) - query(a - 1) << '\n';
		} else {
			fin >> a;
			fout << posOfSum(a) << '\n';
		}
	}
	return 0;
}

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

int query(int pos) {
	int result = 0;
	while (pos > 0) {
		result += aib[pos];
		pos -= (pos & -pos);
	}
	return result;
}

int posOfSum(int sum) {
	int lo = 1, hi = N;
	while (lo < hi) {
		int mid = lo + (hi - lo) / 2;
		if (query(mid) >= sum) {
			hi = mid;
		} else {
			lo = mid + 1;
		}
	}
	if (query(lo) != sum) {
		return -1;
	}
	return lo;
}