Cod sursa(job #1489958)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 22 septembrie 2015 14:50:25
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <stdio.h>
#include <ctype.h>

const int BUFFSIZE = 1024;
const int MAX_N = 100000;

int fen[MAX_N + 1];
char buff[BUFFSIZE];
int ptr = BUFFSIZE;

int n;

inline char getChr()
{
	if (ptr == BUFFSIZE)
	{
		fread(buff, 1, BUFFSIZE, stdin);
		ptr = 0;
	}
	return buff[ ptr ++ ];
}

inline int readInt()
{
	register int q = 0;
	char c;

	do
	{
		c = getChr(); 
	} while ( ! isdigit( c ) );
	do
	{
		q = (q << 1) + (q << 3) + (c - '0');
		c = getChr();
	} while ( isdigit( c ) );
	return q;
}

inline void fenwickAdd(int pos, const int &x)
{
	for (; pos <= n; pos += (pos & -pos))
		fen[pos] += x;
}

inline int fenwickSum(int pos)
{
	int s = 0;
	for (; pos; pos &= (pos - 1))
		s += fen[ pos ];
	return s;
}

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

	n = readInt();
	m = readInt();
	for (int i = 1; i <= n; i++)
	{
		x = readInt();
		fenwickAdd(i, x);
	}
	for (int i = 0; i < m; i++)
	{
		type = readInt();
		x = readInt();
		if (type == 2)
		{
			int pos = 0;
			int interval = (1 << __builtin_clz(n));
			while (interval && x)
			{
				if ((interval + pos <= n) && (fen[interval + pos] <= x))
				{
					pos += interval;
					x -= fen[pos];
				}
				interval >>= 1;
			}
			if (!x)
				printf("%d\n", pos);
			else
				puts("-1");
		}
		else
		{
			y = readInt();
			if (!type)
				fenwickAdd(x, y);
			else
				printf("%d\n", fenwickSum(y) - fenwickSum(x - 1));
		}
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}