Cod sursa(job #1700545)

Utilizator Tiberiu02Tiberiu Musat Tiberiu02 Data 10 mai 2016 19:31:34
Problema Arbori indexati binar Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.32 kb
# include <stdio.h>
# include <stdlib.h>

# define MAX_N 100000

int N;

int s[MAX_N];

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

int query( int pos ) {
    int S;

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

    return S;
}

int cbin( int val ) {
    int pos, pas;

    pos = 1;
    for ( pas = 30; pas >= 0; pas -- )
        if ( pos + ( 1 << pas ) <= N && query( pos + ( 1 << pas ) ) <= val )
            pos = pos + ( 1 << pas );

    return query( pos ) == val ? pos : -1;
}

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

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

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

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

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

    fclose( fin );
    fclose( fout );

    return 0;
}