Cod sursa(job #1317442)

Utilizator serban_ioan97Ciofu Serban serban_ioan97 Data 14 ianuarie 2015 21:47:54
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <cstdio>
#include <algorithm>
#define nmax 100100

using namespace std;

int arb[nmax], n, m, t, c;
int s, i, x, y;
void tree_update(int position, int value)
{
    c=0;
    while(position<=n)
    {
        arb[position]+=value;
        while(!(position&(1<<c))) ++c;
        position+=(1<<c);
        ++c;
     }
}
int tree_query(int position)
{
    c=0, s=0;

    while(position>0)
    {
        s+=arb[position];
        while(!(position&(1<<c))) ++c;
        position-=(1<<c);
        ++c;
    }

    return s;
}
int tree_search(int value)
{
    int i, step;

    for(step=1; step<n; step<<=1);

    for(i=0; step; step>>=1)
    {
         if(i+step<=n)
         {
            if(value>=arb[i+step])
            {
                i+=step, value-=arb[i];
                if(!value) return i;
            }
         }
    }

    return -1;
}
int main()
{
    freopen("aib.in", "rt", stdin);
    freopen("aib.out", "wt", stdout);

    scanf("%d%d", &n, &m);

    for(i=1; i<=n; ++i)
    {
        scanf("%d", &x);
        tree_update(i, x);
    }

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

        if(t<2)
        {
            scanf("%d%d", &x, &y);
            if(!t) tree_update(x, y);
            else printf("%d\n", tree_query(y)-tree_query(x-1));
        }
        else
        {
            scanf("%d", &x);
            printf("%d\n", tree_search(x));
        }
    }
    return 0;
}