Cod sursa(job #1459866)

Utilizator aimrdlAndrei mrdl aimrdl Data 11 iulie 2015 01:27:41
Problema Arbori indexati binar Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <fstream>

#define MAX 100005

using namespace std;

long tree[MAX];
int n, B;

void update (int pos, long val) {
	while (pos <= n) {
		tree[pos] += val;
		pos += pos  & -pos;
	}
}

long query (int pos) {
	long s = 0;
	while (pos) {
		s += tree[pos];
		pos -= pos & -pos;
	}
	
	return s;
}

long find (long val) {
	int bitmask = B, i = 0;
	
	while (bitmask && (i < n)) {
		int pos = bitmask + i;
		if (pos <= n) {
			if (val >= tree[pos]) {
				val -= tree[pos];
				i += bitmask;
				if (!val) return pos;
			}
		}
		
		bitmask >>= 1;
	}
	
	return -1;
} 
	
int main (void) {
	ios::sync_with_stdio(false);
	
	freopen("aib.in", "r", stdin);
	freopen("aib.out", "w", stdout);
	
	int m;
	cin >> n >> m;
	
	for (B = 1; B < n; B <<= 1);
	
	for (int i = 1; i <= n; ++i) {
		int x;
		cin >> x;
		
		update(i, x);
	}
	
	for (int i = 0; i < m; ++i) {
		int x, a, b;
		cin >> x;
		if (x < 2) {
			cin >> a >> b;
			if (!x) {
				update(a, b);
			} else {
				cout << query(b) - query(a-1) << "\n";
			}
		} else {
			cin >> a;
			cout << find(a) << "\n";
		}
	}
		 
	return 0;
}