Cod sursa(job #1203217)

Utilizator killer301Ioan Andrei Nicolae killer301 Data 30 iunie 2014 19:29:06
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <cstdio>

using namespace std;

int n, m;
int aib[100005];

void update(int poz, int val)
{
	for(;poz<=n;poz+=(poz&-poz))
		aib[poz]+=val;
}

int query(int poz)
{
	int s=0;
	for(;poz>=1;poz-=(poz&-poz))
		s+=aib[poz];
	return s;
}

int bin(int x)
{
	int st=1, dr=n;
	while(st<=dr)
	{
		int med=(st+dr)/2;
		int val=query(med);
		if(val==x)return med;
		else if(val<x) st=med+1;
		else dr=med-1;
	}
	return -1;
}

int main()
{
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(int i=0;i<n;i++)
	{
		int x;
		scanf("%d", &x);
		update(i+1, x);
	}
	for(int i=0;i<m;i++)
	{
		int type;
		scanf("%d", &type);
		if(type==0)
		{
			int a, b;
			scanf("%d%d", &a, &b);
			update(a, b);
		}
		else if(type==1)
		{
			int a, b;
			scanf("%d%d", &a, &b);
			printf("%d\n", query(b)-query(a-1));
		}
		else if(type==2)
		{
			int s;
			scanf("%d", &s);
			printf("%d\n", bin(s));
		}
	}
    return 0;
}