Cod sursa(job #3176735)

Utilizator TheAndreiEnache Andrei Alexandru TheAndrei Data 27 noiembrie 2023 18:12:02
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
	#include <iostream>
	#include <algorithm>
	#include <fstream>
	using namespace std;
	ifstream fin("aib.in");
	ofstream fout("aib.out");
	int n, m, v[100005], tip, x, y, aib[100005];
	void update(int poz, int val) {
		while (poz <= n) {
			aib[poz] += val;
			poz = poz + (poz & (poz ^ (poz - 1)));
		}
	}
	int query(int poz) {
		int rez = 0;
		while (poz > 0) {
			rez += aib[poz];
			poz = poz - (poz & (poz ^ (poz - 1)));
		}
		return rez;
	}
	int cautare_binara(int x) {
		int rez = 0;
		for (int i = 17; i >= 0; i--) {
			if ((rez + (1 << i)) <= n && query(rez + (1 << i)) < x) {
				rez += (1 << i);
			}
		}
		return rez + 1;
	}
	int main() {
		fin >> n >> m;
		for (int i = 1; i <= n; i++) fin >> v[i];
		for (int i = 1; i <= m; i++) {
			fin >> tip;
			if (tip == 0) {
				fin >> x >> y;
				update(x, y);
			}
			else if (tip==1){
				fin >> x >> y;
				fout<<query(y)-query(x-1)<<"\n";
			}
			else {
				fin >> x;
				int rez = cautare_binara(x);
				if (rez == n + 1 || query(rez) != x) fout << -1 << "\n";
				else fout << rez << "\n";
			}
		}
	}