Cod sursa(job #1700345)

Utilizator mihai995mihai995 mihai995 Data 10 mai 2016 02:22:56
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
using namespace std;

template<class Type, const int N>
class FenwickTree{
	Type aib[N + 1];
	int n;

	inline static int step(int x){
		return x & -x;
	}
public:
	void set(int n){ this -> n = n; }
	void update(int x, Type val){
		for (int i = x; i <= N; i += step(i))
			aib[i] += val;
	}
	Type query(int x){
		Type ans = aib[x];
		while ( x -= step(x) )
			ans += aib[x];
		return ans;
	}
	Type query(int x, int y){
		return query(y) - query(x - 1);
	}
	int bsrc(Type val){
		int ans = 0;
		for (int step = 1 << ( 31 - __builtin_clz(n) ); step; step >>= 1)
			if ( (ans ^ step) <= n && aib[ans ^ step] <= val )
				val -= aib[ans ^= step];
		return ans;
	}
};

FenwickTree<int, (int)(1e5)> A;

int main(){
	ifstream in("aib.in");
	ofstream out("aib.out");

	int n, times, x, y;
	in >> n >> times; A.set(n);
	for (int i = 1; i <= n; i++){
		in >> x;
		A.update(i, x);
	}
	while (times--){
		in >> n >> x;
		if (n != 2) in >> y;

		if ( n == 0 )
			A.update(x, y);
		else if ( n == 1 )
			out << A.query(x, y) << '\n';
		else {
			n = A.bsrc(x);
			out << (n ? n : -1) << '\n';
		}
	}
	return 0;
}