Cod sursa(job #1700543)

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

# define MAX_N 100000

int N;

long long s[MAX_N];

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

long long query( int pos ) {
    long long S;

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

    return S;
}

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

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

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

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

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

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

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

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

    fclose( fin );
    fclose( fout );

    return 0;
}