Cod sursa(job #1360122)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 25 februarie 2015 11:53:23
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <stdio.h>

#define N_MAX 100000

int aib[N_MAX + 1];

void add(int pos, int val)
{
	while (pos <= N_MAX) {
		aib[pos] += val;
		pos += pos & (-pos);
	}
}

int qr(int pos)
{
	int ret = 0;
	while (pos) {
		ret += aib[pos];
		pos &= pos - 1;
	}
	return ret;
}

int search(int val)
{
	int step = 65536, sum = 0, pos = 0;
	while (step) {
		if (aib[pos + step] + sum < val) {
			pos += step;
			sum += aib[pos];
		}
		step >>= 1;
	}
	if (qr(pos + 1) == val) {
		return pos + 1;
	} else {
		return -1;
	}
}

int main()
{
	FILE *fin, *fout;
	fin = fopen("aib.in", "r");
	fout = fopen("aib.out", "w");
	
	int N, M;
	fscanf(fin, "%d%d", &N, &M);
	
	int i;
	for (i = 1; i <= N; ++i) {
		int aux;
		fscanf(fin, "%d", &aux);
		add(i, aux);	
	}
	
	for (i = 0; i < M; ++i) {
		int op;
		fscanf(fin, "%d", &op);
		if (op == 0) {
			int a, b;
			fscanf(fin, "%d%d", &a, &b);
			add(a, b);
		} else if (op == 1) {
			int a, b;
			fscanf(fin, "%d%d", &a, &b);
			fprintf(fout, "%d\n", qr(b) - qr(a - 1));
		} else if (op == 2) {
			int a;
			fscanf(fin, "%d", &a);
			fprintf(fout, "%d\n", search(a));
		}
	}
	
	fclose(fin);
	fclose(fout);
	return 0;
}