Cod sursa(job #1400638)

Utilizator sergiunascaSergiu Nasca sergiunasca Data 25 martie 2015 13:04:26
Problema Arbori indexati binar Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <stdio.h>
#define NMax 100005
using namespace std;
int n,m,x,y,z,arb[5*NMax];
void _update(int pos,int val)
{
    int bit = 0;
    while( pos <= n)
    {
        arb[pos] += val;
        while( ! (pos&(1<<bit)) )++bit;
        pos = pos + (1<<bit);
        ++bit;
    }
}
int _query(int pos)
{
    int bit = 0,suma = 0;
    while( pos > 0 )
    {
        suma = suma + arb[pos];
        while( ! (pos&(1<<bit)) )++bit;
        pos = pos - (1<<bit);
        ++bit;
    }
    return suma;
}
inline int _binary_search(int val)
{
    int i, step;
    for (step = 1; step < n; step <<= 1);
    for (i = 0; step; step >>= 1)
    {
        if (i + step < n)
        {
            if(arb[i + step] <= val)
            {
                i+=step;
                val -= arb[i];
                if(val==0)return i;
            }
        }
    }

    return -1;
}
int main()
{
    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;++i)
    {
        scanf("%d",&x);
        _update(i,x);
    }
    for(int i=1;i<=m;++i)
    {
        scanf("%d %d",&x,&y);
        if(x==0)
        {
            scanf("%d",&z);
            _update(y,z);
        }
        else if(x==1)
        {
            scanf("%d",&z);
            printf("%d\n",_query(z)-_query(y-1));
        }
        else if(x==2)
        {
            printf("%d\n",_binary_search(y));
        }
    }
    return 0;
}