Cod sursa(job #552496)

Utilizator tudorsTudor Siminic tudors Data 12 martie 2011 14:21:40
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <stdio.h>
#define N 100001
using namespace std;
int n,m,y;
int i,x,op,st,dr;
int C[N];

FILE *f,*g;

int bit(int x)
{
	return x&(-x);
}

void update(int poz, int x)
{
	int i;
	for (i=poz;i<=n;i+=bit(i))
		C[i]+=x;
}

int query(int x)
{
	int i,s=0;
	for (i=x;i>0;i-=bit(i))
		s+=C[i];
	return s;
}

int search(int a)
{
	int x=1;
	int y=n;
	int z=(x+y)/2;
	int s=query(z);
	while (x<=y)
	{
		z=(x+y)/2;
		s=query(z);
		if (s>a)
			y=z-1;
		else if (s<a)
			x=z+1;
		else break;
	}
	if (s==a)
		return z;
	else return -1;
}

int main()
{
	f=fopen("aib.in","r");
	g=fopen("aib.out","w");
	fscanf(f,"%d %d",&n,&m);
	for (i=1;i<=n;++i)
	{
		fscanf(f,"%d",&x);
		update(i,x);
	}
	for (i=1;i<=m;++i)
	{
		fscanf(f,"%d",&op);
		if (op==0)
		{
			fscanf(f,"%d %d",&x,&y);
			update(x,y);
		}
		else if (op==1)
		{
			fscanf(f,"%d %d",&st,&dr);
			fprintf(g,"%d\n",query(dr)-query(st-1));
		}
		else
		{
			fscanf(f,"%d",&x);
			fprintf(g,"%d\n",search(x));
		}
	}
	fclose(f);
	fclose(g);
	return 0;
}