Cod sursa(job #3185628)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 19 decembrie 2023 19:24:50
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;

#ifndef HOME
	ifstream in("aib.in");
	ofstream out("aib.out");
	#define cin in
	#define cout out
#endif

unsigned int aib[100001], n;

int lsb(int x)
{
	return x & -x;
}

unsigned int query(int poz)
{
	unsigned int sum = 0;
	for(; poz > 0; poz -= lsb(poz))
		sum += aib[poz];
	return sum;
}

void update(int poz, int val)
{
	for(; poz <= n; poz += (lsb(poz)))
		aib[poz] += val;
}

int main()
{
#ifdef HOME
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif // HOME
    int q, t, a, b;
	unsigned int x;
	cin >> n >> q;
	for(int i = 1; i <= n; i++)
	{
		cin >> x;
		update(i, x);
	}
	while(q--)
	{
		cin >> t;
		if(t == 0)
		{
			cin >> a >> b;
			update(a, b);
		}
		else if(t == 1)
		{
			cin >> a >> b;
			cout << query(b) - query(a - 1) << '\n';
		}
		else
		{
			cin >> x;
			int r = 0, pas = 1 << 16;
			while(pas)
			{
				if(r + pas <= n && query(r + pas) <= x)
					r += pas;
				pas /= 2;
			}
			if(query(r) == x)
				cout << r << '\n';
			else
				cout << "-1\n";
		}
	}
    return 0;
}