Cod sursa(job #1245382)

Utilizator radudorosRadu Doros radudoros Data 19 octombrie 2014 00:59:55
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
using namespace std;


int t[100001];

ifstream fin("aib.in");
ofstream fout("aib.out");

int LSB(int x)
{
	return (x&(x - 1)) ^ x;
}

int MSB(int x)
{
	int aux = 1;
	while (x!=0)
	{
		x>>= 1; 
		aux <<= 1;
	}
	return aux >> 1;
}

void increment(int p, int val,int n)
{
	while (p <= n)
	{
		t[p] += val;
		p += LSB(p);
	}
}

int sum(int i, int sf)
{
	if (i != 1)
		return sum(1, sf) - sum(1, i - 1);
	int s =0;
	while (sf != 0)
	{
		s += t[sf];
		sf -= LSB(sf);
	}
	return s;
}

int posk(int s,int n)
{

	int min=-1;
	int lo = 1; int hi = n;
	while (hi - lo >= 1)
	{
		int mid = lo + (hi - lo)/2;
		int aux = sum(1, mid);

		if (aux >= s)
		{
			hi = mid - 1;
			if (aux==s)
				min = mid;
		}
		else
			lo = mid+1;
	
	}
	if (sum(1, lo) == s )
		min = lo;

	return min;


}




int main()
{
	int n;
	int m;
	fin >> n>>m;
	for (int i = 1; i <= n; i++)
	{
		int aux;
		fin >> aux;
		increment(i, aux, n);
	}
	for (int i = 1; i <= m; i++)
	{
		int aux;
		fin >> aux;
		if (aux == 0)
		{
			int poz; int x;
			fin >> poz >> x;
			increment(poz, x,n);
		}
		if (aux == 1)
		{
			int inc; int sf;
			fin >> inc >> sf;
			fout << sum(inc, sf) << '\n';
		}
		if (aux == 2)
		{
			int k;
			fin >> k;
			fout <<posk(k,n)<<'\n';
		}


	}
}