Cod sursa(job #1773048)

Utilizator Tiberiu02Tiberiu Musat Tiberiu02 Data 7 octombrie 2016 14:54:58
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
# include <stdio.h>
# include <stdlib.h>

# define MAX_N 100000

class aib {
    int n;
    int * s;

    public:
    aib( int _n ) {
        n = _n;
        s = new int[1 + n];

        for ( int i = 0; i <= n; i ++ )
            s[i] = 0;
    }

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

    int operator[]( int pos ) {
        int S;

        S = 0;
        while ( pos > 0 ) {
            S += s[pos];
            pos -= ( pos & -pos );
        }

        return S;
    }

    int cbin( int val ) {
        if ( val == 0 )
            return -1;

        int pos, pas;

        pos = 0;
        for ( pas = ( 1 << 20 ); pas > 0; pas >>= 1 )
            if ( pos + pas <= n && s[pos + pas] <= val ) {
                val -= s[pos + pas];
                pos = pos + pas;
            }

        return val == 0 ? pos : -1;
    }
};

int main() {
    FILE *fin = fopen( "aib.in", "r" ), *fout = fopen( "aib.out", "w" );

    int n, m, i, j, t, a, b, nr;

    fscanf( fin, "%d%d", &n, &m );

    aib s( n );
    for ( i = 1; i <= n; i ++ ) {
        fscanf( fin, "%d", &nr );
        s.update( i, nr );
    }

    j = 1;
    for ( i = 0; i < m; i ++ ) {
        fscanf( fin, "%d", &t );
        if ( t == 0 ) {
            fscanf( fin, "%d%d", &a, &b );
            s.update( a, b );
        } else if ( t == 1 ) {
            fscanf( fin, "%d%d", &a, &b );
            fprintf( fout, "%d\n", s[b] - s[a - 1] );
        } else {
            fscanf( fin, "%d", &a );
            fprintf( fout, "%d\n", s.cbin( a ) );
        }
    }

    fclose( fin );
    fclose( fout );

    return 0;
}