Cod sursa(job #2788815)

Utilizator Rares31100Popa Rares Rares31100 Data 26 octombrie 2021 14:55:58
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;

template <class T> class AIB
{
private:
	T* tree, lung;
	T sum_part(int poz)
	{
		T rez = 0;

		while (poz)
		{
			rez += tree[poz];
			poz -= poz & -poz;
		}

		return rez;
	}
public:
	AIB(int lungime)
	{
		lung = lungime;
		tree = new T[lung + 1]();
	}
	~AIB()
	{
		delete[] tree;
	}
	void add(int poz, T value)
	{
		while (poz <= lung)
		{
			tree[poz] += value;
			poz += poz & -poz;
		}
	}
	T sum(int st, int dr)
	{
		return sum_part(dr) - sum_part(st - 1);
	}
};

int n, q;

int main()
{
	FILE *fin, *fout;
	fopen_s(&fin, "aib.in", "r");
	fopen_s(&fout, "aib.out", "w");

	fscanf_s(fin, "%d%d", &n, &q);

	AIB <int> aib(n);

	for (int i = 1, val; i <= n; i++)
	{
		fscanf_s(fin, "%d", &val);
		aib.add(i, val);
	}

	for (int t, a, b; q; q--)
	{
		fscanf_s(fin, "%d%d", &t, &a);
		if (t != 2)
			fscanf_s(fin, "%d", &b);

		switch (t)
		{
		case 0: aib.add(a, b); break;
		case 1: fprintf_s(fout, "%d\n", aib.sum(a, b)); break;
		case 2:
			int poz = 0;
			for (int p = n; p; p /= 2)
				while (poz + p <= n && aib.sum(1, poz + p) < a)
					poz += p;

			if (poz < n && aib.sum(1, poz + 1) == a)
				fprintf_s(fout, "%d\n", poz + 1);
			else
				fprintf_s(fout, "-1\n");
		}
	}

	fclose(fout);
	return 0;
}