Cod sursa(job #2847964)

Utilizator Langa_bLanga Radu Langa_b Data 11 februarie 2022 21:23:58
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb

#include <iostream>
#include <cstdio>

using namespace std;

#define DIM 100004

int N, M;
int aib[DIM];

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

int query(int pos) {
	int ans = 0;

	for (; pos; pos -= pos & (-pos)) {
		ans += aib[pos];
	}

	return ans;
}

int bin_search(int x) {
	int pw = 1;
	while (pw <= N) {
		pw <<= 1;
	}
	pw >>= 1;
	int pos = 0;
	while (pw) {
		if (pos + pw <= N) {
			if (query(pos + pw) <= x) {
				pos += pw;
			}
		}

		pw >>= 1;
	}

	return pos;
}

int main() {
	freopen("aib.in", "r", stdin);
	freopen("aib.out", "w", stdout);
	scanf("%d %d\n", &N, &M);
	for (int i = 1; i <= N; ++i) {
		int x;
		scanf("%d", &x);
		update(i, x);
	}

	while (M--) {
		int tip;
		scanf("%d", &tip);
		if (tip == 0) {
			int pos, value;
			scanf("%d %d\n", &pos, &value);
			update(pos, value);
		}
		if (tip == 1) {
			int x, y;
			scanf("%d %d\n", &x, &y);
			cout << query(y) - query(x - 1) << '\n';
		}
		if (tip == 2) {
			int x;
			scanf("%d\n", &x);
			int pos = bin_search(x);
			if (query(pos) != x || pos == 0) {
				cout << -1 << '\n';
			}
			else {
				cout << pos << '\n';
			}
		}
	}

	return 0;
}