Cod sursa(job #2466680)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 2 octombrie 2019 19:48:57
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>

using namespace std;

ifstream fin( "aib.in" );
ofstream fout( "aib.out" );

const int NMAX = 100002;

int N, T;
int tree[NMAX];

void Update( int pos, int val )
{
    while( pos <= N )
    {
        tree[pos] += val;
        pos += ( pos & -pos );
    }
}

int Query( int pos )
{
    int ans = 0;

    while( pos > 0 )
    {
        ans += tree[pos];
        pos -= ( pos & -pos );
    }

    return ans;
}

int BinSearch( int lf, int rg, int val )
{
    if( lf > rg ) return 2000000000;

    int mid = lf + ( rg - lf ) / 2;
    int aux = Query( mid );

    if( aux == val ) return min( mid, BinSearch( lf, mid - 1, val ) );
    if( aux > val ) return BinSearch( lf, mid - 1, val );
    else return BinSearch( mid + 1, rg, val );
}

int main()
{
    fin >> N >> T;

    for( int i = 1; i <= N; ++i )
    {
        int nr;
        fin >> nr;

        Update( i, nr );

    }

    int t, a, b;
    for( int i = 1; i <= T; ++i )
    {
        fin >> t >> a;
        if( t < 2 ) fin >> b;

        //fout << t << ' ' << a << '\n';

        if( t == 0 ) Update( a, b );
        if( t == 1 ) fout << Query( b ) - Query( a - 1 ) << '\n';
        if( t == 2 )
        {
            int aux = BinSearch( 1, N, a );
            if( aux == 2000000000 ) fout << "-1\n";
            else fout << aux << '\n';
        }
    }

    return 0;
}