Cod sursa(job #2868545)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 10 martie 2022 23:55:46
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
int n, m, i, tc, j, x, y, op;
vector <int> aib;
void update(int poz, int val)
{
	for (int i = poz; i <= n; i += i & (-i))
		aib[i] += val;
}
int query(int a)
{
	int s = 0;
	for (int i = a; i > 0; i -= i & (-i))
		s += aib[i];
	return s;
}
int finder(int a)
{
	int poz = 1, cp = 0;
	while (poz < n)
		poz *= 2;
	for (; poz > 0; poz /= 2)
	{
		if (cp + poz <= n && a >= aib[cp + poz])
		{
			cp += poz;
			a -= aib[cp];
			if (a == 0) return cp;
		}
	}
	return -1;
}
int main()
{
	fin >> n >> m; aib.resize(n + 1);
	for (i = 1; i <= n; i++)
		fin >> x, update(i, x);
	for (tc = 1; tc <= m; tc++)
	{
		fin >> op >> x;
		if (op == 0)
		{
			fin >> y;
			update(x, y);
		}
		else if (op == 1)
		{
			fin >> y;
			fout << query(y) - query(x - 1) << "\n";
		}
		else
		{
			fout << finder(x) << "\n";
		}
	}
	return 0;
}