Cod sursa(job #2721975)

Utilizator popoviciAna16Popovici Ana popoviciAna16 Data 12 martie 2021 15:19:03
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <iostream>
using namespace std;

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

int a[100001];

void update (int n, int poz, int val)
{
	while (poz <= n)
	{
		a[poz] += val;
		poz = poz + (poz & (-poz));
	}
}

int query (int poz)
{
	int rasp = 0;
	while (poz > 0)
	{
		rasp = rasp + a[poz];
		poz = poz - (poz & (-poz));
	}
	return rasp;
}

int cauta (int n, int s)
{
	int pas, i;
	for (pas = 1; pas <= n; pas <<= 1);
	pas = pas >> 1;
	
	for (i = 0; pas > 0; pas >>= 1)
	{
		if (i + pas <= n && s >= a[i + pas])
		{
			s = s - a[i + pas];
			i = i | pas;
			
			if (s == 0)
				return i;
		}
	}
	return -1;
}

int main()
{
	int n, q, i, t, a, b;
	fin >> n >> q;
	for (i = 1; i<=n; i++)
	{
		fin >> a;
		update (n, i, a);
	}
	for (i = 1; i<=q; i++)
	{
		fin >> t;
		if (t == 0)
		{
			fin >> a >> b;
			update (n, a, b);
		}
		else if (t == 1)
		{
			fin >> a >> b;
			fout << query(b) - query(a-1) << '\n';
		}
		else
		{
			fin >> a;
			fout << cauta (n, a) << '\n';
		}
	}
	return 0;
}