Cod sursa(job #750217)

Utilizator Stefex09Stefan Teodorescu Stefex09 Data 21 mai 2012 15:43:34
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include<iostream>
#include<fstream>

using namespace std;

ifstream in("aib.in");
ofstream out("aib.out");

int M, N;
int AIB[100001];

inline int lsb(int x)
{
	return ( x & (-x) );
}

int search(int val)
{
	int i, pas;
	
	for(pas = 1; pas < N; pas <<= 1);
	
	for(i = 0; pas; pas >>= 1)
		if(i + pas <= N)
			if(val >= AIB[i + pas]){
				i += pas;
				val -= AIB[i];
				if(!val) return i;
			}
}

void update(int poz, int val)
{
	while(poz <= N){
		AIB[poz] += val;
		poz += lsb(poz);
	}
}

int query(int poz)
{
	int s = 0;
	
	while(poz){
		s += AIB[poz];
		poz -= lsb(poz);
	}
	
	return s;
}

int main()
{
	int k, x, y, i, t;
	
	in >> N >> M;
	
	for(i = 1; i <= N; ++i){
		in >> t;
		update(i, t);
	}
	
	while(M--){
		in >> k;
		
		if(k < 2){
			in >> x >> y;
			
			if(!k)
				update(x, y);
			else
				out << query(y) - query(x - 1) << "\n";
		}
		else{
			in >> x;
			out << search(x) << "\n";
		}
	}
	
	return 0;
}