Cod sursa(job #459645)

Utilizator darrenRares Buhai darren Data 30 mai 2010 15:47:43
Problema Arbori indexati binar Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include<fstream>
using namespace std;

int n, m, aib[100001];
void update(int pos, int val)
{
	int c;
	while (pos <= n)
	{
		aib[pos] += val;
		c = 0;
		while ((pos & (1 << c)) == 0)
			++c;
		pos += 1 << c;
	}
}
int querry(int pos)
{
	int c, sum = 0;
	while (pos >= 1)
	{
		sum += aib[pos];
		c = 0;
		while ((pos & (1 << c)) == 0)
			++c;
		pos -= 1 << c;
	}
	return sum;
}
int search(int val)
{
	int l1 = 1, l2 = n;
	while (l1 <= l2)
	{
		int md = (l2 + l1) >> 1;
		int sum = querry(md);
		
		if (sum == val)
			return md;
		if (sum > val)
			l2 = md - 1;
		else
			l1 = md + 1;
	}
	return -1;
}

int main()
{
	ifstream fin("aib.in");
	ofstream fout("aib.out");
	fin >> n >> m;
	
	int aux, pos, val;
	for (int i = 1; i <= n; ++i)
	{
		fin >> aux;
		update(i, aux);
	}
	for (int i = 1; i <= m; ++i)
	{
		fin >> aux;
		switch (aux)
		{
		case 0:
			fin >> pos >> val;
			update(pos, val);
			break;
		case 1:
			fin >> pos >> val;
			fout << querry(val) - querry(pos - 1) << '\n';
			break;
		case 2:
			fin >> val;
			fout << search(val) << '\n';
			break;
		}
	}
}