Cod sursa(job #1212276)

Utilizator pulseOvidiu Giorgi pulse Data 24 iulie 2014 11:59:15
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <cstdio>

using namespace std;

int n, q, type, a, b, Arb[100005], C, S;

int Search(int val)
{
	int i, step;

	for (step = 1; step < n; step <<= 1);

	for (i = 0; step; step >>= 1)
	{
		if (i + step <= n)
		{
			if (val >= Arb[i + step])
			{
				i += step, val -= Arb[i];
				if (!val) return i;
			}
		}
	}
	return -1;
}

void Update(int poz, int val)
{
	C = 0;
	while (poz <= n)
	{
		Arb[poz] += val;
		while ( !(poz & (1 << C)) ) C++;
		poz += (1 << C);
		C += 1;
	}
}

int Query(int poz)
{
	C = 0, S = 0;
	while (poz)
	{
		S += Arb[poz];
		while ( !(poz & (1 << C)) ) C++;
        poz -= (1 << C);
        C += 1;
	}
	return S;
}

int main()
{
	freopen("aib.in", "r", stdin);
	freopen("aib.out", "w", stdout);

	scanf ("%d%d", &n, &q);
	for (int i = 1; i <= n; ++i)
	{
		int x;
		scanf("%d", &x);
		Update(i, x);
	}

	while (q--)
	{
		scanf("%d", &type);
		if (type == 0)
		{
			scanf("%d%d", &a, &b);
			Update(a, b);
			continue;
		}
		if (type == 1)
		{
			scanf("%d%d", &a, &b);
			printf("%d\n", Query(b) - Query(a - 1));
			continue;
		}
		if (type == 2)
		{
			scanf("%d", &a);
			printf("%d\n", Search(a));
		}
	}

	return 0;
}