Cod sursa(job #1700347)

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

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

	inline static int step(int x){
		return x & -x;
	}
public:
	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 val == aib[0] ? ans : -1;
	}
};

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

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

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

		if ( t == 0 )
			A.update(x, y);
		else if ( t == 1 )
			out << A.query(x, y) << '\n';
		else
			out << min( n, A.bsrc(x) ) << '\n';
	}
	return 0;
}