Cod sursa(job #2410054)

Utilizator LucaSeriSeritan Luca LucaSeri Data 19 aprilie 2019 18:00:13
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e5 + 1;

int aib[MAXN];

void update(int poz, int val) {
	for(; poz < MAXN; poz += poz&-poz) aib[poz] += val;
	return;
}
int query(int poz) {
	int ret = 0;
	for(; poz; poz -= poz&-poz) ret += aib[poz];

	return ret;
}

int main() {
	#ifdef BLAT
		freopen("input", "r", stdin);
	#else
		freopen("aib.in", "r", stdin);
		freopen("aib.out", "w", stdout);
	#endif

	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n, m;
	cin >> n >> m;

	for(int i = 1; i <= n; ++i) {
		int x;
		cin >> x;
		update(i, x);
	}

	for(int i = 0; i < m; ++i) {
		int t, a, b;
		cin >> t;
		cin >> a;
		if(t != 2) cin >> b;

		if(t == 0) {
			update(a, b);
		}
		if(t == 1) {
			cout << query(b) - query(a - 1) << '\n';
		}
		if(t == 2) {
			int nowSum = 0;
			int best = 0;

			for(int step = 20; step >= 0; --step) {
				if(best + (1<<step) < MAXN && nowSum + aib[best+(1<<step)] < a) {
					best += (1<<step);
					nowSum += aib[best];
				}
			}

			++best;
			if(query(best) == a) cout << best << '\n';
			else cout << "-1\n";
		}
	}
	return 0;
}