Cod sursa(job #2938320)

Utilizator IanisBelu Ianis Ianis Data 11 noiembrie 2022 22:59:25
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>

using namespace std;

#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
ifstream fin("aib.in");
ofstream fout("aib.out");
#endif

#define LSB(idx) ((idx ^ (idx - 1)) & idx)

const int NMAX = 1e5+5;

int n, m;
int a[NMAX], aib[NMAX];

void update(int pos, int val) {
	while (pos <= n) {
		aib[pos] += val;
		pos += LSB(pos);
	}
}

int pref_sum(int i) {
	int sum = 0;
	while (i > 0) {
		sum += aib[i];
		i -= LSB(i);
	}
	return sum;
}

int sum(int x, int y) {
	return pref_sum(y) - (x == 1 ? 0 : pref_sum(x - 1));
}

int find_pref(int x) {
	int l = 1;
	int r = n;
	while (l <= r) {
		int mid = (l + r) / 2;
		if (pref_sum(mid) < x)
			l = mid + 1;
		else
			r = mid - 1;
	}
	return pref_sum(r + 1) == x ? r + 1 : -1;
}

void solve() {
	fin >> n >> m;
	for (int i = 1; i <= n; i++) {
		fin >> a[i];
		update(i, a[i]);
	}
	int t, x, y;
	while (m--) {
		fin >> t >> x;
		if (t != 2)
			fin >> y;
		if (t == 0)
			update(x, y);
		else if (t == 1)
			fout << sum(x, y) << '\n';
		else
			fout << find_pref(x) << '\n';
	}
}

int32_t main() {
	solve();
	return 0;
}