Cod sursa(job #2674607)

Utilizator davidcotigacotiga david davidcotiga Data 19 noiembrie 2020 18:19:19
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <algorithm>
#include <string>
#include <queue>
#include <vector>
#include <map>

using namespace std;

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

int N, M;
int v[100005];
int tree[100005];

void Update(int poz, int val) {
	for (; poz <= N; poz += (poz & -poz))
		tree[poz] += val;
}

int Query(int poz) {
	int rez = 0;
	for (; poz; poz -= (poz & -poz))
		rez += tree[poz];
	return rez;
}

int Query2(const int QUERY) {
	int st = 1, dr = N, mij;

	while (st <= dr) {
		mij = (st + dr) / 2;
		int rez = Query(mij);
		if (rez == QUERY)
			return mij;

		if (rez < QUERY)
			dr = mij - 1;
		else
			st = mij + 1;
	}
	return -1;
}

void Build() {
	for (int i = 1; i <= N; ++i)
		Update(i, v[i]);
}

int main() {
	fin >> N >> M;

	for (int i = 1; i <= N; ++i)
		fin >> v[i];

	Build();

	int tip;
	int a, b;
	for (int i = 0; i < M; ++i) {
		fin >> tip;

		if (tip == 0) {
			fin >> a >> b;
			Update(a, b);
		}
		else if (tip == 1) {
			fin >> a >> b;
			fout << Query(b) - Query(a - 1);
		}
		else {
			fin >> a;
			fout << Query2(a);
		}
	}

	return 0;
}