Cod sursa(job #2908285)

Utilizator grecubogdanGrecu Bogdan grecubogdan Data 2 iunie 2022 17:43:28
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <cstring>
#include <fstream>
using namespace std;

ifstream f("aib.in");
ofstream g("aib.out");
#define dim 100001

inline int Minim(int a, int b) {
       if ( a < b ) return a;
       return b;
}

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()
{
    memset(Arb,0,sizeof(Arb));
    int K, X, Y;
    f>>N>>M;
    for ( int i = 1; i <= N; i++ )
    {
        f>>T;
        Update(i,T);
    }

    for ( ; M; M-- )
    {
        f>>K;

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