Cod sursa(job #724131)

Utilizator tudgal1001Profir Tudor tudgal1001 Data 26 martie 2012 11:40:09
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include<cstdio>
using namespace std;

int a[100005],n;

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

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

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

int search (int sum)
{
    int st=1,dr=n,poz=-1,aux,mij;
    while (st<=dr)
    {
        mij=(st+dr)/2;
        aux=query(mij);
        if (aux==sum)
            poz=mij;
        if (aux>=sum)
            dr=mij-1;
        else st=mij+1;
    }
    return poz;
}

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