Cod sursa(job #475821)

Utilizator robigiirimias robert robigi Data 8 august 2010 17:50:13
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
// Arbori indexati binar.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"
#include "stdio.h"

FILE *f=fopen("aib.in", "r");
FILE *g=fopen("aib.out", "w");

int n, m, v[100001];


void update(int poz, int val)
{
	int cv=0;
	while (poz<=n)
	{
		v[poz]+=val;
		while (!(poz&(1<<cv))) ++cv;
		poz+=(1<<cv);
		++cv;
	}
}


int query(int poz)
{
	int cv=0;
	int sum=0;
	while (poz>0)
	{
		sum+=v[poz];
		while (!(poz&(1<<cv))) ++cv;
		poz-=(1<<cv);
		++cv;
	}
	return sum;
}


int search(int val)
{
	int i, step;
	for (step=1; step<=n; step<<=1);
		for (i=0; step; step>>=1)
		{
			if (i+step<=n)
			{
				if (val>=v[i+step])
				{
					i+=step;
					val-=v[i];
					if (!val) return i;
				}
			}
		}
	return -1;
}


int main()
{
	fscanf(f, "%d%d", &n, &m);
	for (int i=1; i<=n; ++i)
	{
		int x;
		fscanf(f, "%d", &x);
		update(i, x);
	}
	for (int j=1; j<=m; ++j)
	{
		int o, a, b;
		fscanf(f, "%d%d", &o, &a);
		if (o==0)
		{
			fscanf(f, "%d", &b);
			update(a, b);
		}
		else
			if (o==1)
			{
				fscanf(f, "%d", &b);
				fprintf(g, "%d\n", query(b)-query(a-1));
			}
			else
			{
				fprintf(g, "%d\n", search(a));
			}
	}
	return 0;
}