Cod sursa(job #3185654)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 19 decembrie 2023 19:50:15
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 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

long long aib[100001];
int n;

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

long long query(int poz)
{
	long long 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 cautbin(int x)
{
	int r = 0, pas = 1 << 16;
	while(pas)
	{
		if(r + pas <= n && aib[r + pas] <= x)
		{
			x -= aib[r + pas];
			r += pas;
		}
		pas /= 2;
	}
	if(x == 0)
		return r;
	return -1;
}

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