Cod sursa(job #1454279)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 25 iunie 2015 23:18:09
Problema Arbori indexati binar Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 1.21 kb
#include <stdio.h>
#define zeros(x) ((x ^ (x - 1)) & x)
#define MAX 100005

void initAIB();
int cb(int x);
void Add(int x, int q);
int Compute(int x);

int n, m, v[MAX], AIB[MAX], i, a, b, ind;

int main(){
	freopen("aib.in", "r", stdin);
	freopen("aib.out", "w", stdout);
	scanf("%d%d", &n, &m);
	for(i = 1; i <= n; i++)
		scanf("%d", &v[i]);

	initAIB();

	for(i = 0; i < m; i++){
		scanf("%d", &ind);
		switch(ind){
			case 0:{
							 scanf("%d%d", &a, &b);
							 Add(a, b);
						 }; break;
			case 1:{
							 scanf("%d%d", &a, &b);
							 printf("%d\n", Compute(b) - Compute(a - 1));
						 }; break;
			default:{
								scanf("%d", &a);
								printf("%d\n", cb(a));
							}
		}
	}
	return 0;
}

void initAIB(){
	int i, j;
	for(i = 1; i <= n; i++)
		for(j = i - zeros(i) + 1; j <= i; j++)
			AIB[i] += v[j];
}

void Add(int x, int q){
	int i;
	for(i = x; i <= n; i += zeros(i))
		AIB[i] += q;
}

int Compute(int x){
	int i, rez = 0;
	for(i = x; i > 0; i -= zeros(i))
		rez += AIB[i];
	return rez;
}

int cb(int x){
	int s = 1, d = n, mij;
	while(s < d){
		mij = (s + d) / 2;
		if(Compute(mij) == x)
			return mij;
		if(Compute(mij) > x)
			d = mij - 1;
		else
			s = mij + 1;
	}

	if(Compute(s) == x)
		return s;
	return -1;
}