Cod sursa(job #1467743)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 4 august 2015 18:55:59
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
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);
	string str(800000, ' ');
	getline(f, str);
	char* ptr = &str[0];
	for(int i = 1, x; i <= n; ++i){
		fen.set(i, strtol(ptr, &ptr, 10)); }
	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 st = 1, dr = n;
			while(st != dr){
				int mij = st + (dr-st)/2;
				if(fen.get(mij) < a){
					st = mij+1; }
				else if(fen.get(mij) == a){
					st = dr = mij; }
				else{
					dr = mij-1; } }
			g << (fen.get(st)==a ? st : -1) << '\n'; } }
	return 0; }