Cod sursa(job #1084034)

Utilizator chiriacandrei25Chiriac Andrei chiriacandrei25 Data 16 ianuarie 2014 17:39:55
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <cstdio>
#define Nmax 100005

using namespace std;

int N,aib[Nmax];

inline void Update(int p, int x)
{
    while(p<=N)
    {
        aib[p]+=x;
        p+=(p&(-p));
    }
}

inline int Query(int p)
{
    int s=0;
    while(p>0)
    {
        s+=aib[p];
        p-=(p&(-p));
    }
    return s;
}

inline int BSearch(int x)
{
    int st,dr,mij;
    st=1; dr=N;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(Query(mij)>=x)
            dr=mij-1;
        else
            st=mij+1;
    }
    mij=(st+dr)/2;
    if(Query(mij)<x)
        ++mij;
    return mij;
}

int main()
{
    int i,x,y,tip,M;
    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);
    }
    while(M--)
    {
        scanf("%d", &tip);
        if(tip==2)
        {
            scanf("%d", &x);
            printf("%d\n", BSearch(x));
        }
        else
        {
            scanf("%d%d", &x,&y);
            if(tip==1)
                printf("%d\n", Query(y)-Query(x-1));
            else
                Update(x,y);
        }
    }
    return 0;
}