Cod sursa(job #2492379)

Utilizator cyg_contnr1Rares Burghelea cyg_contnr1 Data 14 noiembrie 2019 17:45:42
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>
#include <fstream>
using namespace std;
#define dim 100001
inline int min(int a, int b) {
       if ( a < b ) return a;
       return b;
}
int n, m, t;
int arb[dim];
int c, s;

void Update(int,int);
int Query(int);
int Search(int);

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));
        }
    }
}

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 += 1;
     }
}
int Query(int poz)
{
    c = 0, s = 0;
    while ( poz > 0 )
    {
          s += arb[poz];
          while ( !(poz & (1<<c)) ) c++;
          poz -= (1<<c);
          c += 1;
    }
    return s;
}