Cod sursa(job #1743174)

Utilizator ValentinSavoiuFMI Savoiu Valentin-Marian ValentinSavoiu Data 17 august 2016 18:08:07
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <cstring>
#define dim 100001
using namespace std;
ifstream f ("aib.in");
ofstream g ("aib.out");

int N, M, t;
int Arb[dim];
int C, S;
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;
}

int main()
{
    int K, a, b;
    f>>N>>M;
    for ( int i = 1; i <= N; i++ )
    {
        f>>t;
        Update(i,t);
    }

    for (int i=1 ; i<=M; i++ )
    {
        f>>K;

        if ( K < 2 )
        {
             f>>a>>b;
             if ( !K ) Update(a,b);
             else      g<<Query(b)-Query(a-1)<<'\n';
        }
        else
        {
            f>>a;

            g<<Search(a)<<'\n';
        }
    }
}