Cod sursa(job #2189779)

Utilizator flibiaVisanu Cristian flibia Data 28 martie 2018 22:59:19
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

#define dim 100001
char buff[dim];
int pos = 0;

void read(int &nr){
	nr = 0;
	while(buff[pos] < '0' || buff[pos] > '9')
		if(++pos == dim) 
			fread(buff, 1, dim, stdin), pos = 0;
	while(buff[pos] >= '0' && buff[pos] <= '9'){
		nr = 10 * nr + buff[pos] - '0';
		if(++pos == dim) 
			fread(buff, 1, dim, stdin), pos = 0;
	}
}

int n, q, x, a[100100], cod, val, st, dr, mid;

void update(int pos, int val){
	for(; pos <= n; pos += (pos & -pos))
		a[pos] += val;
}

int query(int pos){
	int rs = 0;
	for(; pos > 0; pos -= (pos & -pos))
		rs += a[pos];
	return rs;
}

int solve(int st, int dr){
	return query(dr) - query(st - 1);
}

int main(){
	freopen("aib.in", "r", stdin);
	ofstream out("aib.out");
	read(n);
	read(q);
	for(int i = 1; i <= n; i++){
		read(x);
		update(i, x);
	}
	while(q--){
		read(cod);
		if(cod == 0){
			read(x);
			read(val);
			update(x, val);	
			continue;
		}
		if(cod == 1){
			read(st);
			read(dr);
			out << solve(st, dr) << '\n';
			continue;
		}
		read(x);
		st = 1;
		dr = n;
		while(st <= dr){
			mid = st + dr >> 1;
			if(query(mid) >= x)
				dr = mid - 1;
			else st = mid + 1;
		}
		out << (query(st) == x ? st : -1) << '\n';
	}
	return 0;
}