Cod sursa(job #424686)

Utilizator iuly2freemanVasiliev Iulian iuly2freeman Data 25 martie 2010 08:39:59
Problema Arbori indexati binar Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
//#include <iostream>
#include <fstream>

#define zeros(n) (n & -n)

using namespace std;

ifstream fin("aib.in");
ofstream fout("aib.out");

long int n, *c, k, st;

void add(long int x, long int y)
{
	while (x <= n)
	{
		c[x] += y;
		x += zeros(x);
	}
}

long int interog(long int x, long int y)
{
	if (x != 1) return interog(1, y) - interog(1, x - 1);
	
	long int sum = 0;
	while (y > 0)
	{
		sum += c[y];
		y -= zeros(y);
	}
	return sum;
}

int search(int x)
{
	int s = 1;
    
    while (s < n) s <<= 1;
    
    for (int i = 0; s != 0; s >>= 1)
    {
         if (i + s <= n)
         {
            if (x >= c[i + s]) 
            {
                i += s; x -= c[i];
                if ( !x ) return i;
            }
         }
    }
    
    return -1;
}

int main()
{
	long int x, y, z, t;
	fin >> n >> t; 
	
	c = new long int[n + 1];
	
	for (int i = 1; i <= n; ++i)
	{
		fin >> x;
		add(i, x);
	};
	
	for (int i = 0; i < t; ++i)
	{
		fin >> x;
		if (x == 0)
		{
			fin >> y >> z;
			add(y, z);
		}
		if (x == 1)
		{
			fin >> y >> z;
			fout << interog(y, z) << endl;
		}
		if (x == 2)
		{
			fin >> y;
			fout << search(y) << endl;
		}
	}
	
	return 0;
}