Cod sursa(job #1943685)

Utilizator LolkekzorChiorean Tudor Lolkekzor Data 28 martie 2017 19:04:07
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

int n, m, i, x, y, op;
int AIB[ 250005 ];

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

int interval( int pos ) {
    int sum = 0;
    while ( pos > 0 ) {
        sum += AIB[ pos ];
        pos -= pos & (-pos);
    }
    return sum;
}

int query( int k ) {
    int pos = 1, sum = 0, prev = 1;
    while ( sum < k ) {
        if ( sum + AIB[ pos ] < k && pos <= n ) {
            prev = pos;
            pos += pos & (-pos);
        } else if ( sum + AIB[ pos ] == k ) {
            return pos;
        } else {
            pos = prev;
            sum += AIB[ pos ];
            pos++;
        }
    }
    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 >> x;
        if ( op == 0 ) {
            fin >> y;
            update( x , y );
        } else if ( op == 1 ) {
            fin >> y;
            fout << interval( y ) - interval( x - 1 ) << '\n';
        } else {
            fout << query( x ) << '\n';
        }
    }

    return 0;
}