Cod sursa(job #1238358)

Utilizator xtreme77Patrick Sava xtreme77 Data 6 octombrie 2014 20:04:42
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <fstream>

const char IN [ ] = "aib.in" ;
const char OUT [ ] = "aib.out" ;
const int MAX = 100014 ;

using namespace std ;

ifstream fin ( IN ) ;
ofstream fout ( OUT ) ;

int n , arb [ MAX ] ;

int caut ( 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 == 0 )
                    return i ;
            }
        }
    }
    return -1 ;
}

void update ( int poz , int val )
{
    int C = 0 ;
    while ( poz <= n )
    {
        arb [ poz ] += val ;
        while ( not ( poz & ( 1 << C ) ) ) ++ C ;
        poz += ( 1 << C ) ;
        C ++ ;
    }
}

int easy_query ( int poz )
{
    int C = 0 , S = 0 ;
    while ( poz > 0 )
    {
        S += arb [ poz ] ;
        while ( not ( poz & ( 1 << C ) ) ) ++ C ;
        poz -= ( 1 << C ) ;
        C ++ ;
    }
    return S ;
}

int main(              )
{
    int  m ;
    fin >> n >> m ;
    for ( int i = 1 ; i <= n ; ++ i )
    {
        int x ;
        fin >> x ;
        update ( i , x ) ;
    }
    for ( ; m ; -- m )
    {
        int k ;
        fin >> k ;
        if ( k < 2 )
        {
            int x , y ;
            fin >> x >> y ;
            if ( ! k ){
                update ( x , y ) ;
            }
            else {
                fout << easy_query( y ) - easy_query( x - 1 ) << '\n' ;
            }
        }
        else {
            int x ;
            fin >> x ;
            fout << caut ( x ) << '\n' ;
        }
    }
    return 0;
}