Cod sursa(job #2450167)

Utilizator r00t_Roman Remus r00t_ Data 22 august 2019 11:04:13
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cmath>
#include <iomanip>

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

int aib[100100];

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

int sum(int k)
{
	int total = 0;
	while (k > 0)
	{
		total += aib[k];
		k -= k & -k;
	}
	return total;
}

int main()
{
	ios_base::sync_with_stdio(false);
	int n, m, Max = 0;
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		int x;
		cin >> x;
		Max = max(Max, x);
		add(i, n, x);
	}


	for (int i = 1; i <= m; i++)
	{
		int t, x, y;
		cin >> t;
		if (t == 0)
		{
			cin >> x >> y;
			add(x, n, y);
		}
		if (t == 1)
		{
			cin >> x >> y;
			cout << sum(y) - sum(x-1) << '\n';
		}
		if (t == 2)
		{
			cin >> x;
			int lhs = 1, rhs = n;
			int found = 0;
			while (lhs != rhs)
			{
				int mid = (lhs + rhs) / 2, vsum = sum(mid);

				if (vsum < x) 
					lhs = mid + 1;
				else
					if (vsum > x) rhs = mid;
					else
					{
						found = mid;
						break;
					}
			}
			if (found != 0)
				cout << found << '\n';
			else
				if (sum(lhs) == x)
					cout << lhs << '\n';
				else
					cout << -1 << '\n';
		}
	}


}