Cod sursa(job #173984)

Utilizator M@2Te4iMatei Misarca M@2Te4i Data 8 aprilie 2008 12:50:05
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdio>

using namespace std;

#define vv 100001

inline int minim(int a, int b)
{
    if ( a < b )
        return a;
    return b;
}

int n, m, t;
int arb[vv];
int c, s;

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>=arb[i+step])
            {
                i+=step, val-=arb[i];
                if (!val)
                    return i;
            }
         }
    }

    return -1;
}

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

int query(int poz)
{
    c=0, s=0;
    while (poz>0)
    {
        s+=arb[poz];
        while (!(poz & (1<<c)))
            c++;
        poz-=(1<<c);
        ++c;
    }
    return s;
}

int main()
{
    //memset(arb,0,sizeof(arb));
    int k, x, y;

    freopen("aib.in","r",stdin);
    freopen("aib.out","w",stdout);

    scanf("%d%d", &n, &m);
    for (int i=1; i<=n; i++)
    {
        scanf("%d", &t);
        update(i,t);
    }

    for ( ; m; m--)
    {
        scanf("%d", &k);

        if (k<2)
        {
             scanf("%d%d", &x, &y);
             if (!k)
                update(x,y);
             else
                printf("%d\n", query(y)-query(x-1));
        }
        else
        {
            scanf("%d", &x);
            printf("%d\n", search(x));
        }
    }
}