Cod sursa(job #1126066)

Utilizator vlad96Vlad Zuga vlad96 Data 26 februarie 2014 21:05:54
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <stdio.h>

using namespace std;

const int N = 100001;
int n, m, c, s;
int arb[N];

void update (int pos, int val)
{
    c = 0;
    while ( pos <= n )
    {
        arb[pos] += val;
        while ( !(pos & (1<<c)) ) c++;
        pos += (1<<c);
        c ++;
    }
}

int query (int pos)
{
    int c = 0, s = 0;
    while ( pos > 0 )
    {
        s += arb[pos];
        while ( !(pos & (1<<c)) ) c++;
        pos -= (1<<c);
        c ++;
    }
    return s;
}

int search (int val)
{
    int step;
    for ( step = 1; step < n; step <<= 1 );
    for (int i = 0; step; step >>= 1 )
    {
        if ( i + step <= n )
        {
            if ( val >= arb[i + step] )
            {
                i += step;
                val -= arb[i];
                if (!val)
                    return i;
            }
        }
    }
    return -1;
}

void solve ()
{
    int k, x, y;
    FILE *fis = fopen ("aib.in", "r");
    FILE *fis2 = fopen ("aib.out", "w");

    fscanf(fis, "%d %d", &n, &m);
    for (int i = 1, a; i <= n; i ++ )
        fscanf(fis, "%d", &a), update(i, a);
    for ( ; m; m-- )
    {
        fscanf(fis, "%d", &k);
        if ( k == 0 )
        {
            fscanf(fis, "%d %d", &x, &y);
            update(x, y);
        }
        else if ( k == 1 )
        {
            fscanf(fis, "%d %d", &x, &y);
            fprintf(fis2, "%d\n", query(y) - query(x-1) );
        }
        else if ( k == 2 )
        {
            fscanf(fis, "%d", &x);
            fprintf(fis2, "%d\n", search(x));
        }
    }
}

int main()
{
    solve();
    return 0;
}