Cod sursa(job #743821)

Utilizator Stefex09Stefan Teodorescu Stefex09 Data 6 mai 2012 13:49:31
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include<iostream>
#include<fstream>

using namespace std;

ifstream in("aib.in");
ofstream out("aib.out");

inline int minim(int a, int b)
{
	return (a < b ? a : b);
}

int m, n, t;
int aib[100001];
int c, s;

int search(int val)
{
	int i, pas;
	
	for(pas = 1; pas < n; pas <<= 1);
	
	for(i = 0; pas; pas >>= 1)
		if(i + pas <= n)
			if(val >= aib[i + pas]){
				i += pas;
				val -= aib[i];
				if(!val) return i;
			}

	return -1;
}

void update(int poz, int val)
{
	c = 0;
	
	while(poz <= n){
		aib[poz] += val;
		while(!(poz & (1 << c))) c++;
		poz += (1 << c);
		c++;
	}
}

int query(int poz)
{
	c = 0; s = 0;
	while(poz > 0){
		s += aib[poz];
		while(!(poz & (1 << c))) c++;
		poz -= (1 << c);
		c++;
	}
	
	return s;
}

int main()
{
	int k, x, y, i;
	
	in >> n >> m;
	
	for(i = 1; i <= n; ++i){
		in >> t;
		update(i, t);
	}
	
	while(m--){
		in >> k;
		
		if(k < 2){
			in >> x >> y;
			if(!k) update(x, y);
			else out << (query(y) - query(x-1)) << "\n";
		}
		else{
			in >> x;
			out << search(x) << "\n";
		}
	}
	
	return 0;
}