Cod sursa(job #2512180)

Utilizator radustn92Radu Stancu radustn92 Data 20 decembrie 2019 17:59:31
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <cstdio>
const int NMAX = 100505;
int N, ops;

int aib[NMAX];

inline int lsb(int pos) {
	return pos ^ (pos & (pos - 1));
}

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

int sum(int pos) {
	int result = 0;
	for ( ; pos ; pos -= lsb(pos)) {
		result += aib[pos];
	}

	return result;
}

int searchPrefixWithSum(int value) {
	int step;
	for (step = 1; step <= N; step <<= 1);

	int currPrefix = 0, currPrefixSum = 0;
	for ( ; step; step >>= 1) {
		if (currPrefix + step <= N && currPrefixSum + aib[currPrefix + step] <= value) {
			currPrefix += step;
			currPrefixSum += aib[currPrefix];
		}
	}

	return currPrefixSum == value ? currPrefix : -1;
}

int main() {
	freopen("aib.in", "r", stdin);
	freopen("aib.out", "w", stdout);

	scanf("%d%d", &N, &ops);
	int x;
	for (int i = 1; i <= N; i++) {
		scanf("%d", &x);
		update(i, x);
	}

	int opType, y;
	for (int op = 0; op < ops; op++) {
		scanf("%d", &opType);
		switch(opType) {
			case 0:
				scanf("%d%d", &x, &y);
				update(x, y);
				break;
			case 1:
				scanf("%d%d", &x, &y);
				printf("%d\n", sum(y) - sum(x - 1));
				break;
			case 2:
				scanf("%d", &x);
				printf("%d\n", searchPrefixWithSum(x));
				break;
		}
	}

	return 0;
}