Cod sursa(job #2055370)

Utilizator Victor24Vasiesiu Victor Victor24 Data 3 noiembrie 2017 10:01:49
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>

using namespace std;

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

int aib[100005], n , m, op, x, a, b, i;

void update ( int poz, int val )
{
    while ( poz <= n )
    {
        aib[poz] += val;
        poz += ( poz & ( -poz ) );
    }
}

int query ( int poz )
{
    int s = 0;

    while ( poz != 0 )
    {
        s += aib[poz];
        poz -= ( poz & ( -poz ) );
    }

    return s;

}

int sumfix ( int s )
{
    int i , poz = 0;

    for ( i = 1 ; i <= n ; i*=2 );
    for ( ; i >=1 ; i/=2 )
    {
        if ( poz + i <= n && aib[ poz + i ] <= s)
        {
            s -= aib[poz+i];
            poz += i;
            if ( s == 0 )
                return poz;
        }
    }
    return -1;

}

int main()
{

    fin>>n>>m;

    for ( i = 1; i <= n ; i++ )
    {
        fin>>x;

        update( i , x );

    }

    for ( i = 1 ; i <= m ; i++ )
    {
        fin>>op;

        if ( op == 0 )
        {
            fin>>a>>b;

            update( a , b );

        }
        else if ( op == 1 )
        {
            fin>>a>>b;

            fout << query ( b ) - query ( a - 1 ) << '\n';

        }
        else
        {
            fin>>x;

            fout<<sumfix ( x ) << '\n';

        }

    }

    return 0;
}