Cod sursa(job #1512177)

Utilizator zertixMaradin Octavian zertix Data 27 octombrie 2015 19:11:48
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <cstdio>
using namespace std;

int n,m,arb[100100],x,op,a,b;

void update(int ,int );
int query(int );
int caut(int);
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",&op);
        if (op<2)
        {
            scanf("%d%d",&a,&b);
            if (op==0)
                update(a,b);
            else
                printf("%d\n",query(b)-query(a-1));

        }
        else
        {
            scanf("%d",&a);
            printf("%d\n",caut(a));
        }

    }
    return 0;
}
int caut(int val)
{
    int st=1,dr=n,mij=(st+dr)/2;
    while (st<=dr)
    {
        mij=(st+dr)/2;
        int s=query(mij);
        if (s==val)
            return mij;
        if (s<val)
            st=mij+1;
            else
                dr=mij-1;
    }
    return -1;
}
void update(int poz , int val)
{
    int c=0;
    while (poz<=n)
    {
        arb[poz]+=val;
        while (!(poz & 1<<c))
            ++c;
        poz+=(1<<c);
        c+=1;
    }
}
int query(int poz)
{
    int s=0,c=0;
    while (poz > 0)
    {
        s+=arb[poz];
        while (!(poz & (1<<c)))
            ++c;
        poz-=(1<<c);
        c+=1;
    }
    return s;
}