Cod sursa(job #3277947)

Utilizator ridicheTudor Diaconu ridiche Data 18 februarie 2025 11:03:46
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#define case break; case

using namespace std;

ifstream in;
ofstream ou;

int n, m, aib[100005];

void update(int pos, int x)
{
	while (pos <= n)
	{
		aib[pos] += x;
		pos += pos & -pos;
	}
}

int query(int pos)
{
	int r = 0;
	while (pos > 0)
	{
		r += aib[pos];
		pos -= pos & -pos;
	}
	return r;
}

int main()
{
	in.open("aib.in");
	ou.open("aib.out");
	in >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		int x;
		in >> x;
		update(i, x);
	}
	for (int i = 0; i < m; i++)
	{
		int t;
		in >> t;
		switch(t)
		{
			case 0:
			{
				int a, b;
				in >> a >> b;
				update(a, b);
			}
			case 1:
			{
				int a, b;
				in >> a >> b;
				ou << query(b) - query(a-1) << "\n";
			}
			case 2:
			{
				int x;
				in >> x;
				int st = 1, dr = n+1;
				while (st <= dr)
				{
					int mij = (st + dr) / 2;
					int qm = query(mij);
					if (qm == x)
					{
						dr = mij;
						if (st == dr)
							break;
					}
					else if (qm < x)
					{
						st = mij+1;
					}
					else
					{
						dr = mij-1;
					}
				}
				if (st == n+1 || st > dr)
					ou << "-1\n";
				else
					ou << st << "\n";
			}
		}
	}
}