Cod sursa(job #2020852)

Utilizator WebDesignbyTMGhiorghiu Ioan-Viorel WebDesignbyTM Data 11 septembrie 2017 20:21:54
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#define DM 100001
#include <fstream>
using namespace std;

ifstream fi ("aib.in");
ofstream fo ("aib.out");
unsigned int n, m, c, a, b, aib[DM], bgn = (1<<30);

void update (int pos, int val)
{
	int cpos;
	while (pos <= n)
	{
		cpos = pos - 1;
		cpos = cpos^pos;
		cpos = cpos&pos;
		aib[pos]+=val;
		pos+=cpos;
	}
}

int suma (int pos)
{
	int cpos, sma = 0;
	while (pos)
	{
		cpos = pos - 1;
		cpos = cpos^pos;
		cpos = pos&cpos;
		sma+=aib[pos];
		pos-=cpos;
	}
	return sma;
}

int query (int val)
{
	int lo = 1, hi = n, mid;
	while (hi != lo)
	{
		mid = (hi + lo + 1)/2;
		if (suma(mid) > val)
			hi = mid - 1;
		else
			lo = mid;
	}
	if (val == suma(lo))
		return lo;
	return -1;
}

int main()
{
	fi >> n >> m;
	for (int i = 1; i <= n; ++i)
	{
		fi >> a;
		update(i, a);
	}
	while (bgn > n)
		bgn>>=1;
	for (int i = 1; i <= m; ++i)
	{
		fi >> c;
		if (c == 0)
		{
			fi >> a >> b;
			update(a, b);
		}
		else if (c == 1)
		{
			fi >> a >> b;
			fo << suma(b) - suma(a - 1) << '\n';
		}
		else 
		{
			fi >> a;
			fo << query(a) << '\n';
		}
	}
	return 0;
}