Cod sursa(job #459803)

Utilizator darrenRares Buhai darren Data 31 mai 2010 11:34:27
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include<fstream>
using namespace std;

int n, m, aib[100001];
void update(int pos, int val)
{
	for (;pos <= n; pos += pos & -pos)
		aib[pos] += val;
}
int query(int pos)
{
	int sum = 0;
	for (; pos >= 1; pos -= pos & -pos)
		sum += aib[pos];
	return sum;
}
int search(int val)
{
	int step;
	for (step = 1; step << 1 <= n; step <<= 1);
	for (int i = 0; step; step >>= 1)
		if (i + step <= n)
		{
			int x = query(i + step);
			if (x <= val) i += step;
			if (x == val) return i;
		}
	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 << query(val) - query(pos - 1) << '\n';
			break;
		case 2:
			fin >> val;
			fout << search(val) << '\n';
			break;
		}
	}
}