Cod sursa(job #1467749)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 4 august 2015 19:08:00
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;

class fenwick{
	vector<int> buf;
public:
	fenwick(const int x): buf(x+1, 0){}
	int get(const int poz){
		int rez = 0;
		for(int p = poz; p > 0; p -= p&-p){
			rez += buf[p]; }
		return rez; }
	void set(const int poz, const int delta){
		for(int p = poz; p < buf.size(); p += p&-p){
			buf[p] += delta; } }
	int get(const int st, const int dr){
		return get(dr) - get(st-1); } };

int main(){
	ifstream f("aib.in");
	ofstream g("aib.out");
	int n, m;
	f >> n >> m >> ws;
	fenwick fen(n);
	const int largest_pow_two = 1<<((int)log2(n));
	for(int i = 1, x; i <= n; ++i){
		f >> x;
		fen.set(i, x); }
	f >> ws;
	string str;
	for(int i = 0, t, a, b; i < m; ++i){
		getline(f, str);
		char* ptr = &str[0];
		t = strtol(ptr, &ptr, 10), a = strtol(ptr, &ptr, 10);
		if(t != 2){
			b = strtol(ptr, &ptr, 10); }
		if(t == 0){
			fen.set(a, b); }
		else if(t == 1){
			g << fen.get(a, b) << '\n'; }
		else{
			int rez = 1, step = largest_pow_two;
			for( ; step; step >>= 1){
				if(rez + step <= n && fen.get(rez + step) <= a){
					rez += step; } }
			g << (fen.get(rez)==a ? rez : -1) << '\n'; } }
	return 0; }